fix red.
[kugel-rb/myfork.git] / apps / talk.c
blobb2e25e1f8f69a47aefde2692e99f79f64729ff76
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 #if CONFIG_CODEC == SWCODEC
44 #include "playback.h"
45 #endif
46 #include "debug.h"
49 /* Memory layout varies between targets because the
50 Archos (MASCODEC) devices cannot mix voice and audio playback
52 MASCODEC | MASCODEC | SWCODEC
53 (playing) | (stopped) |
54 audiobuf-----------+-----------+------------
55 audio | voice | thumbnail
56 |-----------|------------
57 | thumbnail | voice
58 | |------------
59 | | filebuf
60 | |------------
61 | | audio
62 audiobufend----------+-----------+------------
64 SWCODEC allocates dedicated buffers, MASCODEC reuses audiobuf. */
67 /***************** Constants *****************/
69 #define QUEUE_SIZE 64 /* must be a power of two */
70 #define QUEUE_MASK (QUEUE_SIZE-1)
71 const char* const dir_thumbnail_name = "_dirname.talk";
72 const char* const file_thumbnail_ext = ".talk";
74 /***************** Functional Macros *****************/
76 #define QUEUE_LEVEL ((queue_write - queue_read) & QUEUE_MASK)
78 #define LOADED_MASK 0x80000000 /* MSB */
80 #if CONFIG_CODEC == SWCODEC
81 #define MAX_THUMBNAIL_BUFSIZE 0x10000
82 #endif
84 /***************** Data types *****************/
86 struct clip_entry /* one entry of the index table */
88 int offset; /* offset from start of voicefile file */
89 int size; /* size of the clip */
92 struct voicefile /* file format of our voice file */
94 int version; /* version of the voicefile */
95 int target_id; /* the rockbox target the file was made for */
96 int table; /* offset to index table, (=header size) */
97 int id1_max; /* number of "normal" clips contained in above index */
98 int id2_max; /* number of "voice only" clips contained in above index */
99 struct clip_entry index[]; /* followed by the index tables */
100 /* and finally the mp3 clips, not visible here, bitswapped
101 for SH based players */
104 struct queue_entry /* one entry of the internal queue */
106 unsigned char* buf;
107 long len;
111 /***************** Globals *****************/
113 static unsigned char* p_thumbnail = NULL; /* buffer for thumbnails */
114 /* Multiple thumbnails can be loaded back-to-back in this buffer. */
115 static volatile int thumbnail_buf_used SHAREDBSS_ATTR; /* length of data in
116 thumbnail buffer */
117 static long size_for_thumbnail; /* total thumbnail buffer size */
118 static struct voicefile* p_voicefile; /* loaded voicefile */
119 static bool has_voicefile; /* a voicefile file is present */
120 static bool need_shutup; /* is there possibly any voice playing to be shutup */
121 static struct queue_entry queue[QUEUE_SIZE]; /* queue of scheduled clips */
122 static bool force_enqueue_next; /* enqueue next utterance even if enqueue is false */
123 static int queue_write; /* write index of queue, by application */
124 static int queue_read; /* read index of queue, by ISR context */
125 #if CONFIG_CODEC == SWCODEC
126 struct mutex queue_mutex SHAREDBSS_ATTR; /* protects queue_read, queue_write
127 and thumbnail_buf_used */
128 #define talk_queue_lock() ({ mutex_lock(&queue_mutex); })
129 #define talk_queue_unlock() ({ mutex_unlock(&queue_mutex); })
130 #else
131 #define talk_queue_lock() ({ })
132 #define talk_queue_unlock() ({ })
133 #endif /* CONFIG_CODEC */
134 static int sent; /* how many bytes handed over to playback, owned by ISR */
135 static unsigned char curr_hd[3]; /* current frame header, for re-sync */
136 static int filehandle = -1; /* global, so the MMC variant can keep the file open */
137 static unsigned char* p_silence; /* VOICE_PAUSE clip, used for termination */
138 static long silence_len; /* length of the VOICE_PAUSE clip */
139 static unsigned char* p_lastclip; /* address of latest clip, for silence add */
140 static unsigned long voicefile_size = 0; /* size of the loaded voice file */
141 static unsigned char last_lang[MAX_FILENAME+1]; /* name of last used lang file (in talk_init) */
142 static bool talk_initialized; /* true if talk_init has been called */
143 static int talk_temp_disable_count; /* if positive, temporarily disable voice UI (not saved) */
146 /***************** Private implementation *****************/
148 static int open_voicefile(void)
150 char buf[64];
151 char* p_lang = "english"; /* default */
153 if ( global_settings.lang_file[0] &&
154 global_settings.lang_file[0] != 0xff )
155 { /* try to open the voice file of the selected language */
156 p_lang = (char *)global_settings.lang_file;
159 snprintf(buf, sizeof(buf), LANG_DIR "/%s.voice", p_lang);
161 return open(buf, O_RDONLY);
165 /* fetch a clip from the voice file */
166 static unsigned char* get_clip(long id, long* p_size)
168 long clipsize;
169 unsigned char* clipbuf;
171 if (id > VOICEONLY_DELIMITER)
172 { /* voice-only entries use the second part of the table */
173 id -= VOICEONLY_DELIMITER + 1;
174 if (id >= p_voicefile->id2_max)
175 return NULL; /* must be newer than we have */
176 id += p_voicefile->id1_max; /* table 2 is behind table 1 */
178 else
179 { /* normal use of the first table */
180 if (id >= p_voicefile->id1_max)
181 return NULL; /* must be newer than we have */
184 clipsize = p_voicefile->index[id].size;
185 if (clipsize == 0) /* clip not included in voicefile */
186 return NULL;
187 clipbuf = (unsigned char *) p_voicefile + p_voicefile->index[id].offset;
189 #if (CONFIG_STORAGE & STORAGE_MMC) /* dynamic loading, on demand */
190 if (!(clipsize & LOADED_MASK))
191 { /* clip used for the first time, needs loading */
192 lseek(filehandle, p_voicefile->index[id].offset, SEEK_SET);
193 if (read(filehandle, clipbuf, clipsize) != clipsize)
194 return NULL; /* read error */
196 p_voicefile->index[id].size |= LOADED_MASK; /* mark as loaded */
198 else
199 { /* clip is in memory already */
200 clipsize &= ~LOADED_MASK; /* without the extra bit gives true size */
202 #endif
204 *p_size = clipsize;
205 return clipbuf;
209 /* load the voice file into the mp3 buffer */
210 static void load_voicefile(void)
212 int load_size;
213 int got_size;
214 int file_size;
215 #ifdef ROCKBOX_LITTLE_ENDIAN
216 int i;
217 #endif
219 filehandle = open_voicefile();
220 if (filehandle < 0) /* failed to open */
221 goto load_err;
223 file_size = filesize(filehandle);
224 if (file_size > audiobufend - audiobuf) /* won't fit? */
225 goto load_err;
227 #if (CONFIG_STORAGE & STORAGE_MMC) /* load only the header for now */
228 load_size = offsetof(struct voicefile, index);
229 #else /* load the full file */
230 load_size = file_size;
231 #endif
233 got_size = read(filehandle, audiobuf, load_size);
234 if (got_size != load_size /* failure */)
235 goto load_err;
237 #ifdef ROCKBOX_LITTLE_ENDIAN
238 logf("Byte swapping voice file");
239 structec_convert(audiobuf, "lllll", 1, true);
240 #endif
242 if (((struct voicefile*)audiobuf)->table /* format check */
243 == offsetof(struct voicefile, index))
245 p_voicefile = (struct voicefile*)audiobuf;
247 if (p_voicefile->version != VOICE_VERSION ||
248 p_voicefile->target_id != TARGET_ID)
250 logf("Incompatible voice file");
251 goto load_err;
253 #if CONFIG_CODEC != SWCODEC
254 /* MASCODEC: now use audiobuf for voice then thumbnail */
255 p_thumbnail = audiobuf + file_size;
256 p_thumbnail += (long)p_thumbnail % 2; /* 16-bit align */
257 size_for_thumbnail = audiobufend - p_thumbnail;
258 #endif
260 else
261 goto load_err;
263 #ifdef ROCKBOX_LITTLE_ENDIAN
264 for (i = 0; i < p_voicefile->id1_max + p_voicefile->id2_max; i++)
265 structec_convert(&p_voicefile->index[i], "ll", 1, true);
266 #endif
268 #if (CONFIG_STORAGE & STORAGE_MMC)
269 /* load the index table, now that we know its size from the header */
270 load_size = (p_voicefile->id1_max + p_voicefile->id2_max)
271 * sizeof(struct clip_entry);
272 got_size = read(filehandle,
273 (unsigned char *) p_voicefile + offsetof(struct voicefile, index), load_size);
274 if (got_size != load_size) /* read error */
275 goto load_err;
276 #else
277 close(filehandle); /* only the MMC variant leaves it open */
278 filehandle = -1;
279 #endif
281 /* make sure to have the silence clip, if available */
282 p_silence = get_clip(VOICE_PAUSE, &silence_len);
284 return;
286 load_err:
287 p_voicefile = NULL;
288 has_voicefile = false; /* don't try again */
289 if (filehandle >= 0)
291 close(filehandle);
292 filehandle = -1;
294 return;
298 /* called in ISR context if mp3 data got consumed */
299 static void mp3_callback(unsigned char** start, size_t* size)
301 queue[queue_read].len -= sent; /* we completed this */
302 queue[queue_read].buf += sent;
304 if (queue[queue_read].len > 0) /* current clip not finished? */
305 { /* feed the next 64K-1 chunk */
306 #if CONFIG_CODEC != SWCODEC
307 sent = MIN(queue[queue_read].len, 0xFFFF);
308 #else
309 sent = queue[queue_read].len;
310 #endif
311 *start = queue[queue_read].buf;
312 *size = sent;
313 return;
315 talk_queue_lock();
316 if(p_thumbnail
317 && queue[queue_read].buf == p_thumbnail +thumbnail_buf_used)
318 thumbnail_buf_used = 0;
319 if (sent > 0) /* go to next entry */
321 queue_read = (queue_read + 1) & QUEUE_MASK;
324 re_check:
326 if (QUEUE_LEVEL != 0) /* queue is not empty? */
327 { /* start next clip */
328 #if CONFIG_CODEC != SWCODEC
329 sent = MIN(queue[queue_read].len, 0xFFFF);
330 #else
331 sent = queue[queue_read].len;
332 #endif
333 *start = p_lastclip = queue[queue_read].buf;
334 *size = sent;
335 curr_hd[0] = p_lastclip[1];
336 curr_hd[1] = p_lastclip[2];
337 curr_hd[2] = p_lastclip[3];
339 else if (p_silence != NULL /* silence clip available */
340 && p_lastclip != p_silence /* previous clip wasn't silence */
341 && !(p_lastclip >= p_thumbnail /* ..or thumbnail */
342 && p_lastclip < p_thumbnail +size_for_thumbnail))
343 { /* add silence clip when queue runs empty playing a voice clip */
344 queue[queue_write].buf = p_silence;
345 queue[queue_write].len = silence_len;
346 queue_write = (queue_write + 1) & QUEUE_MASK;
348 goto re_check;
350 else
352 *size = 0; /* end of data */
354 talk_queue_unlock();
357 /***************** Public routines *****************/
359 /* stop the playback and the pending clips */
360 void talk_force_shutup(void)
362 /* Most of this is MAS only */
363 #if CONFIG_CODEC != SWCODEC
364 #ifdef SIMULATOR
365 return;
366 #endif
367 unsigned char* pos;
368 unsigned char* search;
369 unsigned char* end;
370 if (QUEUE_LEVEL == 0) /* has ended anyway */
371 return;
373 #if CONFIG_CPU == SH7034
374 CHCR3 &= ~0x0001; /* disable the DMA (and therefore the interrupt also) */
375 #endif /* CONFIG_CPU == SH7034 */
376 /* search next frame boundary and continue up to there */
377 pos = search = mp3_get_pos();
378 end = queue[queue_read].buf + queue[queue_read].len;
380 if (pos >= queue[queue_read].buf
381 && pos <= end) /* really our clip? */
382 { /* (for strange reasons this isn't nesessarily the case) */
383 /* find the next frame boundary */
384 while (search < end) /* search the remaining data */
386 if (*search++ != 0xFF) /* quick search for frame sync byte */
387 continue; /* (this does the majority of the job) */
389 /* look at the (bitswapped) rest of header candidate */
390 if (search[0] == curr_hd[0] /* do the quicker checks first */
391 && search[2] == curr_hd[2]
392 && (search[1] & 0x30) == (curr_hd[1] & 0x30)) /* sample rate */
394 search--; /* back to the sync byte */
395 break; /* From looking at it, this is our header. */
399 if (search-pos)
400 { /* play old data until the frame end, to keep the MAS in sync */
401 sent = search-pos;
403 queue_write = (queue_read + 1) & QUEUE_MASK; /* will be empty after next callback */
404 queue[queue_read].len = sent; /* current one ends after this */
406 #if CONFIG_CPU == SH7034
407 DTCR3 = sent; /* let the DMA finish this frame */
408 CHCR3 |= 0x0001; /* re-enable DMA */
409 #endif /* CONFIG_CPU == SH7034 */
410 thumbnail_buf_used = 0;
411 return;
414 #endif /* CONFIG_CODEC != SWCODEC */
416 /* Either SWCODEC, or MAS had nothing to do (was frame boundary or not our clip) */
417 mp3_play_stop();
418 talk_queue_lock();
419 queue_write = queue_read = 0; /* reset the queue */
420 thumbnail_buf_used = 0;
421 talk_queue_unlock();
422 need_shutup = false;
425 /* Shutup the voice, except if force_enqueue_next is set. */
426 void talk_shutup(void)
428 if (need_shutup && !force_enqueue_next)
429 talk_force_shutup();
432 /* schedule a clip, at the end or discard the existing queue */
433 static void queue_clip(unsigned char* buf, long size, bool enqueue)
435 int queue_level;
437 if (!enqueue)
438 talk_shutup(); /* cut off all the pending stuff */
439 /* Something is being enqueued, force_enqueue_next override is no
440 longer in effect. */
441 force_enqueue_next = false;
443 if (!size)
444 return; /* safety check */
445 #if CONFIG_CPU == SH7034
446 /* disable the DMA temporarily, to be safe of race condition */
447 CHCR3 &= ~0x0001;
448 #endif
449 talk_queue_lock();
450 queue_level = QUEUE_LEVEL; /* check old level */
452 if (queue_level < QUEUE_SIZE - 1) /* space left? */
454 queue[queue_write].buf = buf; /* populate an entry */
455 queue[queue_write].len = size;
456 queue_write = (queue_write + 1) & QUEUE_MASK;
458 talk_queue_unlock();
460 if (queue_level == 0)
461 { /* queue was empty, we have to do the initial start */
462 p_lastclip = buf;
463 #if CONFIG_CODEC != SWCODEC
464 sent = MIN(size, 0xFFFF); /* DMA can do no more */
465 #else
466 sent = size;
467 #endif
468 mp3_play_data(buf, sent, mp3_callback);
469 curr_hd[0] = buf[1];
470 curr_hd[1] = buf[2];
471 curr_hd[2] = buf[3];
472 mp3_play_pause(true); /* kickoff audio */
474 else
476 #if CONFIG_CPU == SH7034
477 CHCR3 |= 0x0001; /* re-enable DMA */
478 #endif
481 need_shutup = true;
483 return;
487 /* common code for talk_init() and talk_buffer_steal() */
488 static void reset_state(void)
490 queue_write = queue_read = 0; /* reset the queue */
491 p_voicefile = NULL; /* indicate no voicefile (trashed) */
492 #if CONFIG_CODEC == SWCODEC
493 /* Allocate a dedicated thumbnail buffer - once */
494 if (p_thumbnail == NULL)
496 size_for_thumbnail = audiobufend - audiobuf;
497 if (size_for_thumbnail > MAX_THUMBNAIL_BUFSIZE)
498 size_for_thumbnail = MAX_THUMBNAIL_BUFSIZE;
499 p_thumbnail = buffer_alloc(size_for_thumbnail);
501 #else
502 /* Just use the audiobuf, without allocating anything */
503 p_thumbnail = audiobuf;
504 size_for_thumbnail = audiobufend - audiobuf;
505 #endif
506 thumbnail_buf_used = 0;
507 p_silence = NULL; /* pause clip not accessible */
511 /***************** Public implementation *****************/
513 void talk_init(void)
515 talk_temp_disable_count = 0;
516 if (talk_initialized && !strcasecmp(last_lang, global_settings.lang_file))
518 /* not a new file, nothing to do */
519 return;
522 #if (CONFIG_STORAGE & STORAGE_MMC)
523 if (filehandle >= 0) /* MMC: An old voice file might still be open */
525 close(filehandle);
526 filehandle = -1;
528 #endif
530 #if CONFIG_CODEC == SWCODEC
531 if(!talk_initialized)
532 mutex_init(&queue_mutex);
533 #endif /* CONFIG_CODEC == SWCODEC */
535 talk_initialized = true;
536 strlcpy((char *)last_lang, (char *)global_settings.lang_file,
537 MAX_FILENAME);
539 #if CONFIG_CODEC == SWCODEC
540 audio_get_buffer(false, NULL); /* Must tell audio to reinitialize */
541 #endif
542 reset_state(); /* use this for most of our inits */
544 filehandle = open_voicefile();
545 has_voicefile = (filehandle >= 0); /* test if we can open it */
546 voicefile_size = 0;
548 if (has_voicefile)
550 voicefile_size = filesize(filehandle);
551 close(filehandle); /* close again, this was just to detect presence */
552 filehandle = -1;
557 #if CONFIG_CODEC == SWCODEC
558 /* return if a voice codec is required or not */
559 bool talk_voice_required(void)
561 return (voicefile_size != 0) /* Voice file is available */
562 || (global_settings.talk_dir_clip) /* Thumbnail clips are required */
563 || (global_settings.talk_file_clip);
565 #endif
567 /* return size of voice file */
568 int talk_get_bufsize(void)
570 return voicefile_size;
573 /* somebody else claims the mp3 buffer, e.g. for regular play/record */
574 void talk_buffer_steal(void)
576 #if CONFIG_CODEC != SWCODEC
577 mp3_play_stop();
578 #endif
579 #if (CONFIG_STORAGE & STORAGE_MMC)
580 if (filehandle >= 0) /* only relevant for MMC */
582 close(filehandle);
583 filehandle = -1;
585 #endif
586 reset_state();
590 /* play a voice ID from voicefile */
591 int talk_id(int32_t id, bool enqueue)
593 long clipsize;
594 unsigned char* clipbuf;
595 int32_t unit;
596 int decimals;
598 if (talk_temp_disable_count > 0)
599 return -1; /* talking has been disabled */
600 #if CONFIG_CODEC != SWCODEC
601 if (audio_status()) /* busy, buffer in use */
602 return -1;
603 #endif
605 if (p_voicefile == NULL && has_voicefile)
606 load_voicefile(); /* reload needed */
608 if (p_voicefile == NULL) /* still no voices? */
609 return -1;
611 if (id == -1) /* -1 is an indication for silence */
612 return -1;
614 decimals = (((uint32_t)id) >> DECIMAL_SHIFT) & 0x7;
616 /* check if this is a special ID, with a value */
617 unit = ((uint32_t)id) >> UNIT_SHIFT;
618 if (unit || decimals)
619 { /* sign-extend the value */
620 id = (uint32_t)id << (32-DECIMAL_SHIFT);
621 id >>= (32-DECIMAL_SHIFT);
623 talk_value_decimal(id, unit, decimals, enqueue); /* speak it */
624 return 0; /* and stop, end of special case */
627 clipbuf = get_clip(id, &clipsize);
628 if (clipbuf == NULL)
629 return -1; /* not present */
631 queue_clip(clipbuf, clipsize, enqueue);
633 return 0;
635 /* Speaks zero or more IDs (from an array). */
636 int talk_idarray(const long *ids, bool enqueue)
638 int r;
639 if(!ids)
640 return 0;
641 while(*ids != TALK_FINAL_ID)
643 if((r = talk_id(*ids++, enqueue)) <0)
644 return r;
645 enqueue = true;
647 return 0;
650 /* Make sure the current utterance is not interrupted by the next one. */
651 void talk_force_enqueue_next(void)
653 force_enqueue_next = true;
656 /* play a thumbnail from file */
657 /* Returns size of spoken thumbnail, so >0 means something is spoken,
658 <=0 means something went wrong. */
659 static int _talk_file(const char* filename,
660 const long *prefix_ids, bool enqueue)
662 int fd;
663 int size;
664 int thumb_used;
665 #if CONFIG_CODEC != SWCODEC
666 struct mp3entry info;
667 #endif
669 if (talk_temp_disable_count > 0)
670 return -1; /* talking has been disabled */
671 #if CONFIG_CODEC != SWCODEC
672 if (audio_status()) /* busy, buffer in use */
673 return -1;
674 #endif
676 if (p_thumbnail == NULL || size_for_thumbnail <= 0)
677 return -1;
679 #if CONFIG_CODEC != SWCODEC
680 if(mp3info(&info, filename)) /* use this to find real start */
682 return 0; /* failed to open, or invalid */
684 #endif
686 if (!enqueue)
687 /* shutup now to free the thumbnail buffer */
688 talk_shutup();
690 fd = open(filename, O_RDONLY);
691 if (fd < 0) /* failed to open */
693 return 0;
696 thumb_used = thumbnail_buf_used;
697 if(filesize(fd) > size_for_thumbnail -thumb_used)
698 { /* Don't play truncated clips */
699 close(fd);
700 return 0;
703 #if CONFIG_CODEC != SWCODEC
704 lseek(fd, info.first_frame_offset, SEEK_SET); /* behind ID data */
705 #endif
707 size = read(fd, p_thumbnail +thumb_used,
708 size_for_thumbnail -thumb_used);
709 close(fd);
711 /* ToDo: find audio, skip ID headers and trailers */
713 if (size > 0) /* Don't play missing clips */
715 #if CONFIG_CODEC != SWCODEC && !defined(SIMULATOR)
716 bitswap(p_thumbnail, size);
717 #endif
718 if(prefix_ids)
719 /* prefix thumbnail by speaking these ids, but only now
720 that we know there's actually a thumbnail to be
721 spoken. */
722 talk_idarray(prefix_ids, true);
723 talk_queue_lock();
724 thumbnail_buf_used = thumb_used +size;
725 talk_queue_unlock();
726 queue_clip(p_thumbnail +thumb_used, size, true);
729 return size;
732 int talk_file(const char *root, const char *dir, const char *file,
733 const char *ext, const long *prefix_ids, bool enqueue)
734 /* Play a thumbnail file */
736 char buf[MAX_PATH];
737 /* Does root end with a slash */
738 char *slash = (root && root[0]
739 && root[strlen(root)-1] != '/') ? "/" : "";
740 snprintf(buf, MAX_PATH, "%s%s%s%s%s%s",
741 root ? root : "", slash,
742 dir ? dir : "", dir ? "/" : "",
743 file ? file : "",
744 ext ? ext : "");
745 return _talk_file(buf, prefix_ids, enqueue);
748 static int talk_spell_basename(const char *path,
749 const long *prefix_ids, bool enqueue)
751 if(prefix_ids)
753 talk_idarray(prefix_ids, enqueue);
754 enqueue = true;
756 char buf[MAX_PATH];
757 /* Spell only the path component after the last slash */
758 strlcpy(buf, path, sizeof(buf));
759 if(strlen(buf) >1 && buf[strlen(buf)-1] == '/')
760 /* strip trailing slash */
761 buf[strlen(buf)-1] = '\0';
762 char *ptr = strrchr(buf, '/');
763 if(ptr && strlen(buf) >1)
764 ++ptr;
765 else ptr = buf;
766 return talk_spell(ptr, enqueue);
769 /* Play a file's .talk thumbnail, fallback to spelling the filename, or
770 go straight to spelling depending on settings. */
771 int talk_file_or_spell(const char *dirname, const char *filename,
772 const long *prefix_ids, bool enqueue)
774 if (global_settings.talk_file_clip)
775 { /* .talk clips enabled */
776 if(talk_file(dirname, NULL, filename, file_thumbnail_ext,
777 prefix_ids, enqueue) >0)
778 return 0;
780 if (global_settings.talk_file == 2)
781 /* Either .talk clips are disabled, or as a fallback */
782 return talk_spell_basename(filename, prefix_ids, enqueue);
783 return 0;
786 /* Play a directory's .talk thumbnail, fallback to spelling the filename, or
787 go straight to spelling depending on settings. */
788 int talk_dir_or_spell(const char* dirname,
789 const long *prefix_ids, bool enqueue)
791 if (global_settings.talk_dir_clip)
792 { /* .talk clips enabled */
793 if(talk_file(dirname, NULL, dir_thumbnail_name, NULL,
794 prefix_ids, enqueue) >0)
795 return 0;
797 if (global_settings.talk_dir == 2)
798 /* Either .talk clips disabled or as a fallback */
799 return talk_spell_basename(dirname, prefix_ids, enqueue);
800 return 0;
803 /* say a numeric value, this word ordering works for english,
804 but not necessarily for other languages (e.g. german) */
805 int talk_number(long n, bool enqueue)
807 int level = 2; /* mille count */
808 long mil = 1000000000; /* highest possible "-illion" */
810 if (talk_temp_disable_count > 0)
811 return -1; /* talking has been disabled */
812 #if CONFIG_CODEC != SWCODEC
813 if (audio_status()) /* busy, buffer in use */
814 return -1;
815 #endif
817 if (!enqueue)
818 talk_shutup(); /* cut off all the pending stuff */
820 if (n==0)
821 { /* special case */
822 talk_id(VOICE_ZERO, true);
823 return 0;
826 if (n<0)
828 talk_id(VOICE_MINUS, true);
829 n = -n;
832 while (n)
834 int segment = n / mil; /* extract in groups of 3 digits */
835 n -= segment * mil; /* remove the used digits from number */
836 mil /= 1000; /* digit place for next round */
838 if (segment)
840 int hundreds = segment / 100;
841 int ones = segment % 100;
843 if (hundreds)
845 talk_id(VOICE_ZERO + hundreds, true);
846 talk_id(VOICE_HUNDRED, true);
849 /* combination indexing */
850 if (ones > 20)
852 int tens = ones/10 + 18;
853 talk_id(VOICE_ZERO + tens, true);
854 ones %= 10;
857 /* direct indexing */
858 if (ones)
859 talk_id(VOICE_ZERO + ones, true);
861 /* add billion, million, thousand */
862 if (mil)
863 talk_id(VOICE_THOUSAND + level, true);
865 level--;
868 return 0;
871 /* Say time duration/interval. Input is time in seconds,
872 say hours,minutes,seconds. */
873 static int talk_time_unit(long secs, bool exact, bool enqueue)
875 int hours, mins;
876 if (!enqueue)
877 talk_shutup();
878 if((hours = secs/3600)) {
879 secs %= 3600;
880 talk_value(hours, UNIT_HOUR, true);
882 if((mins = secs/60)) {
883 secs %= 60;
884 if(exact || !hours)
885 talk_value(mins, UNIT_MIN, true);
886 else talk_number(mins, true); /* don't say "minutes" */
888 if((exact && secs) || (!hours && !mins))
889 talk_value(secs, UNIT_SEC, true);
890 else if(!hours && secs)
891 talk_number(secs, true);
892 return 0;
895 void talk_fractional(char *tbuf, int value, int unit)
897 int i;
898 /* strip trailing zeros from the fraction */
899 for (i = strlen(tbuf) - 1; (i >= 0) && (tbuf[i] == '0'); i--)
900 tbuf[i] = '\0';
902 talk_number(value, true);
903 if (tbuf[0] != 0)
905 talk_id(LANG_POINT, true);
906 talk_spell(tbuf, true);
908 talk_id(unit, true);
911 int talk_value(long n, int unit, bool enqueue)
913 return talk_value_decimal(n, unit, 0, enqueue);
916 /* singular/plural aware saying of a value */
917 int talk_value_decimal(long n, int unit, int decimals, bool enqueue)
919 int unit_id;
920 static const int unit_voiced[] =
921 { /* lookup table for the voice ID of the units */
922 [0 ... UNIT_LAST-1] = -1, /* regular ID, int, signed */
923 [UNIT_MS]
924 = VOICE_MILLISECONDS, /* here come the "real" units */
925 [UNIT_SEC]
926 = VOICE_SECONDS,
927 [UNIT_MIN]
928 = VOICE_MINUTES,
929 [UNIT_HOUR]
930 = VOICE_HOURS,
931 [UNIT_KHZ]
932 = VOICE_KHZ,
933 [UNIT_DB]
934 = VOICE_DB,
935 [UNIT_PERCENT]
936 = VOICE_PERCENT,
937 [UNIT_MAH]
938 = VOICE_MILLIAMPHOURS,
939 [UNIT_PIXEL]
940 = VOICE_PIXEL,
941 [UNIT_PER_SEC]
942 = VOICE_PER_SEC,
943 [UNIT_HERTZ]
944 = VOICE_HERTZ,
945 [UNIT_MB]
946 = LANG_MEGABYTE,
947 [UNIT_KBIT]
948 = VOICE_KBIT_PER_SEC,
949 [UNIT_PM_TICK]
950 = VOICE_PM_UNITS_PER_TICK,
953 static const int pow10[] = { /* 10^0 - 10^7 */
954 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000
957 char tbuf[8];
958 char fmt[] = "%0nd";
960 if (talk_temp_disable_count > 0)
961 return -1; /* talking has been disabled */
962 #if CONFIG_CODEC != SWCODEC
963 if (audio_status()) /* busy, buffer in use */
964 return -1;
965 #endif
967 /* special case for time duration */
968 if (unit == UNIT_TIME || unit == UNIT_TIME_EXACT)
969 return talk_time_unit(n, unit == UNIT_TIME_EXACT, enqueue);
971 if (unit < 0 || unit >= UNIT_LAST)
972 unit_id = -1;
973 else
974 unit_id = unit_voiced[unit];
976 if ((n==1 || n==-1) /* singular? */
977 && unit_id >= VOICE_SECONDS && unit_id <= VOICE_HOURS)
979 unit_id--; /* use the singular for those units which have */
982 /* special case with a "plus" before */
983 if (n > 0 && (unit == UNIT_SIGNED || unit == UNIT_DB))
985 talk_id(VOICE_PLUS, enqueue);
986 enqueue = true;
989 if (decimals)
991 /* needed for the "-0.5" corner case */
992 if (n < 0)
994 talk_id(VOICE_MINUS, enqueue);
995 n = -n;
998 fmt[2] = '0' + decimals;
1000 snprintf(tbuf, sizeof(tbuf), fmt, n % pow10[decimals]);
1001 talk_fractional(tbuf, n / pow10[decimals], unit_id);
1003 return 0;
1006 talk_number(n, enqueue); /* say the number */
1007 talk_id(unit_id, true); /* say the unit, if any */
1009 return 0;
1012 /* spell a string */
1013 int talk_spell(const char* spell, bool enqueue)
1015 char c; /* currently processed char */
1017 if (talk_temp_disable_count > 0)
1018 return -1; /* talking has been disabled */
1019 #if CONFIG_CODEC != SWCODEC
1020 if (audio_status()) /* busy, buffer in use */
1021 return -1;
1022 #endif
1024 if (!enqueue)
1025 talk_shutup(); /* cut off all the pending stuff */
1027 while ((c = *spell++) != '\0')
1029 /* if this grows into too many cases, I should use a table */
1030 if (c >= 'A' && c <= 'Z')
1031 talk_id(VOICE_CHAR_A + c - 'A', true);
1032 else if (c >= 'a' && c <= 'z')
1033 talk_id(VOICE_CHAR_A + c - 'a', true);
1034 else if (c >= '0' && c <= '9')
1035 talk_id(VOICE_ZERO + c - '0', true);
1036 else if (c == '-')
1037 talk_id(VOICE_MINUS, true);
1038 else if (c == '+')
1039 talk_id(VOICE_PLUS, true);
1040 else if (c == '.')
1041 talk_id(VOICE_DOT, true);
1042 else if (c == ' ')
1043 talk_id(VOICE_PAUSE, true);
1044 else if (c == '/')
1045 talk_id(VOICE_CHAR_SLASH, true);
1048 return 0;
1051 void talk_disable(bool disable)
1053 if (disable)
1054 talk_temp_disable_count++;
1055 else
1056 talk_temp_disable_count--;
1059 void talk_setting(const void *global_settings_variable)
1061 const struct settings_list *setting;
1062 if (!global_settings.talk_menu)
1063 return;
1064 setting = find_setting(global_settings_variable, NULL);
1065 if (setting == NULL)
1066 return;
1067 if (setting->lang_id)
1068 talk_id(setting->lang_id,false);
1072 #if CONFIG_RTC
1073 void talk_date(const struct tm *tm, bool enqueue)
1075 talk_id(LANG_MONTH_JANUARY + tm->tm_mon, enqueue);
1076 talk_number(tm->tm_mday, true);
1077 talk_number(1900 + tm->tm_year, true);
1080 void talk_time(const struct tm *tm, bool enqueue)
1082 if (global_settings.timeformat == 1)
1084 /* Voice the hour */
1085 long am_pm_id = VOICE_AM;
1086 int hour = tm->tm_hour;
1087 if (hour >= 12)
1089 am_pm_id = VOICE_PM;
1090 hour -= 12;
1092 if (hour == 0)
1093 hour = 12;
1094 talk_number(hour, enqueue);
1096 /* Voice the minutes */
1097 if (tm->tm_min == 0)
1099 /* Say o'clock if the minute is 0. */
1100 talk_id(VOICE_OCLOCK, true);
1102 else
1104 /* Pronounce the leading 0 */
1105 if(tm->tm_min < 10)
1106 talk_id(VOICE_OH, true);
1107 talk_number(tm->tm_min, true);
1109 talk_id(am_pm_id, true);
1111 else
1113 /* Voice the time in 24 hour format */
1114 talk_number(tm->tm_hour, enqueue);
1115 if (tm->tm_min == 0)
1117 talk_id(VOICE_HUNDRED, true);
1118 talk_id(VOICE_HOUR, true);
1120 else
1122 /* Pronounce the leading 0 */
1123 if(tm->tm_min < 10)
1124 talk_id(VOICE_OH, true);
1125 talk_number(tm->tm_min, true);
1130 #endif