Correct the BBX clause (no visual changes)
[kugel-rb/myfork.git] / apps / talk.c
blob44ba063655b9da30fa660e49676dbe8e27ff7521
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"
47 #include "kernel.h"
50 /* Memory layout varies between targets because the
51 Archos (MASCODEC) devices cannot mix voice and audio playback
53 MASCODEC | MASCODEC | SWCODEC
54 (playing) | (stopped) |
55 audiobuf-----------+-----------+------------
56 audio | voice | thumbnail
57 |-----------|------------
58 | thumbnail | voice
59 | |------------
60 | | filebuf
61 | |------------
62 | | audio
63 audiobufend----------+-----------+------------
65 SWCODEC allocates dedicated buffers, MASCODEC reuses audiobuf. */
68 /***************** Constants *****************/
70 #define QUEUE_SIZE 64 /* must be a power of two */
71 #define QUEUE_MASK (QUEUE_SIZE-1)
72 const char* const dir_thumbnail_name = "_dirname.talk";
73 const char* const file_thumbnail_ext = ".talk";
75 /***************** Functional Macros *****************/
77 #define QUEUE_LEVEL ((queue_write - queue_read) & QUEUE_MASK)
79 #define LOADED_MASK 0x80000000 /* MSB */
81 #if CONFIG_CODEC == SWCODEC
82 #define MAX_THUMBNAIL_BUFSIZE 0x10000
83 #endif
85 /***************** Data types *****************/
87 struct clip_entry /* one entry of the index table */
89 int offset; /* offset from start of voicefile file */
90 int size; /* size of the clip */
93 struct voicefile /* file format of our voice file */
95 int version; /* version of the voicefile */
96 int target_id; /* the rockbox target the file was made for */
97 int table; /* offset to index table, (=header size) */
98 int id1_max; /* number of "normal" clips contained in above index */
99 int id2_max; /* number of "voice only" clips contained in above index */
100 struct clip_entry index[]; /* followed by the index tables */
101 /* and finally the mp3 clips, not visible here, bitswapped
102 for SH based players */
105 struct queue_entry /* one entry of the internal queue */
107 unsigned char* buf;
108 long len;
112 /***************** Globals *****************/
114 static unsigned char* p_thumbnail = NULL; /* buffer for thumbnails */
115 /* Multiple thumbnails can be loaded back-to-back in this buffer. */
116 static volatile int thumbnail_buf_used SHAREDBSS_ATTR; /* length of data in
117 thumbnail buffer */
118 static long size_for_thumbnail; /* total thumbnail buffer size */
119 static struct voicefile* p_voicefile; /* loaded voicefile */
120 static bool has_voicefile; /* a voicefile file is present */
121 static bool need_shutup; /* is there possibly any voice playing to be shutup */
122 static struct queue_entry queue[QUEUE_SIZE]; /* queue of scheduled clips */
123 static bool force_enqueue_next; /* enqueue next utterance even if enqueue is false */
124 static int queue_write; /* write index of queue, by application */
125 static int queue_read; /* read index of queue, by ISR context */
126 #if CONFIG_CODEC == SWCODEC
127 struct mutex queue_mutex SHAREDBSS_ATTR; /* protects queue_read, queue_write
128 and thumbnail_buf_used */
129 #define talk_queue_lock() ({ mutex_lock(&queue_mutex); })
130 #define talk_queue_unlock() ({ mutex_unlock(&queue_mutex); })
131 #else
132 #define talk_queue_lock() ({ })
133 #define talk_queue_unlock() ({ })
134 #endif /* CONFIG_CODEC */
135 static int sent; /* how many bytes handed over to playback, owned by ISR */
136 static unsigned char curr_hd[3]; /* current frame header, for re-sync */
137 static int filehandle = -1; /* global, so the MMC variant can keep the file open */
138 static unsigned char* p_silence; /* VOICE_PAUSE clip, used for termination */
139 static long silence_len; /* length of the VOICE_PAUSE clip */
140 static unsigned char* p_lastclip; /* address of latest clip, for silence add */
141 static unsigned long voicefile_size = 0; /* size of the loaded voice file */
142 static unsigned char last_lang[MAX_FILENAME+1]; /* name of last used lang file (in talk_init) */
143 static bool talk_initialized; /* true if talk_init has been called */
144 static int talk_temp_disable_count; /* if positive, temporarily disable voice UI (not saved) */
147 /***************** Private implementation *****************/
149 static int open_voicefile(void)
151 char buf[64];
152 char* p_lang = "english"; /* default */
154 if ( global_settings.lang_file[0] &&
155 global_settings.lang_file[0] != 0xff )
156 { /* try to open the voice file of the selected language */
157 p_lang = (char *)global_settings.lang_file;
160 snprintf(buf, sizeof(buf), LANG_DIR "/%s.voice", p_lang);
162 return open(buf, O_RDONLY);
166 /* fetch a clip from the voice file */
167 static unsigned char* get_clip(long id, long* p_size)
169 long clipsize;
170 unsigned char* clipbuf;
172 if (id > VOICEONLY_DELIMITER)
173 { /* voice-only entries use the second part of the table */
174 id -= VOICEONLY_DELIMITER + 1;
175 if (id >= p_voicefile->id2_max)
176 return NULL; /* must be newer than we have */
177 id += p_voicefile->id1_max; /* table 2 is behind table 1 */
179 else
180 { /* normal use of the first table */
181 if (id >= p_voicefile->id1_max)
182 return NULL; /* must be newer than we have */
185 clipsize = p_voicefile->index[id].size;
186 if (clipsize == 0) /* clip not included in voicefile */
187 return NULL;
188 clipbuf = (unsigned char *) p_voicefile + p_voicefile->index[id].offset;
190 #if (CONFIG_STORAGE & STORAGE_MMC) /* dynamic loading, on demand */
191 if (!(clipsize & LOADED_MASK))
192 { /* clip used for the first time, needs loading */
193 lseek(filehandle, p_voicefile->index[id].offset, SEEK_SET);
194 if (read(filehandle, clipbuf, clipsize) != clipsize)
195 return NULL; /* read error */
197 p_voicefile->index[id].size |= LOADED_MASK; /* mark as loaded */
199 else
200 { /* clip is in memory already */
201 clipsize &= ~LOADED_MASK; /* without the extra bit gives true size */
203 #endif
205 *p_size = clipsize;
206 return clipbuf;
210 /* load the voice file into the mp3 buffer */
211 static void load_voicefile(void)
213 int load_size;
214 int got_size;
215 int file_size;
216 #ifdef ROCKBOX_LITTLE_ENDIAN
217 int i;
218 #endif
220 filehandle = open_voicefile();
221 if (filehandle < 0) /* failed to open */
222 goto load_err;
224 file_size = filesize(filehandle);
225 if (file_size > audiobufend - audiobuf) /* won't fit? */
226 goto load_err;
228 #if (CONFIG_STORAGE & STORAGE_MMC) /* load only the header for now */
229 load_size = offsetof(struct voicefile, index);
230 #else /* load the full file */
231 load_size = file_size;
232 #endif
234 got_size = read(filehandle, audiobuf, load_size);
235 if (got_size != load_size /* failure */)
236 goto load_err;
238 #ifdef ROCKBOX_LITTLE_ENDIAN
239 logf("Byte swapping voice file");
240 structec_convert(audiobuf, "lllll", 1, true);
241 #endif
243 if (((struct voicefile*)audiobuf)->table /* format check */
244 == offsetof(struct voicefile, index))
246 p_voicefile = (struct voicefile*)audiobuf;
248 if (p_voicefile->version != VOICE_VERSION ||
249 p_voicefile->target_id != TARGET_ID)
251 logf("Incompatible voice file");
252 goto load_err;
254 #if CONFIG_CODEC != SWCODEC
255 /* MASCODEC: now use audiobuf for voice then thumbnail */
256 p_thumbnail = audiobuf + file_size;
257 p_thumbnail += (long)p_thumbnail % 2; /* 16-bit align */
258 size_for_thumbnail = audiobufend - p_thumbnail;
259 #endif
261 else
262 goto load_err;
264 #ifdef ROCKBOX_LITTLE_ENDIAN
265 for (i = 0; i < p_voicefile->id1_max + p_voicefile->id2_max; i++)
266 structec_convert(&p_voicefile->index[i], "ll", 1, true);
267 #endif
269 #if (CONFIG_STORAGE & STORAGE_MMC)
270 /* load the index table, now that we know its size from the header */
271 load_size = (p_voicefile->id1_max + p_voicefile->id2_max)
272 * sizeof(struct clip_entry);
273 got_size = read(filehandle,
274 (unsigned char *) p_voicefile + offsetof(struct voicefile, index), load_size);
275 if (got_size != load_size) /* read error */
276 goto load_err;
277 #else
278 close(filehandle); /* only the MMC variant leaves it open */
279 filehandle = -1;
280 #endif
282 /* make sure to have the silence clip, if available */
283 p_silence = get_clip(VOICE_PAUSE, &silence_len);
285 return;
287 load_err:
288 p_voicefile = NULL;
289 has_voicefile = false; /* don't try again */
290 if (filehandle >= 0)
292 close(filehandle);
293 filehandle = -1;
295 return;
299 /* called in ISR context if mp3 data got consumed */
300 static void mp3_callback(unsigned char** start, size_t* size)
302 queue[queue_read].len -= sent; /* we completed this */
303 queue[queue_read].buf += sent;
305 if (queue[queue_read].len > 0) /* current clip not finished? */
306 { /* feed the next 64K-1 chunk */
307 #if CONFIG_CODEC != SWCODEC
308 sent = MIN(queue[queue_read].len, 0xFFFF);
309 #else
310 sent = queue[queue_read].len;
311 #endif
312 *start = queue[queue_read].buf;
313 *size = sent;
314 return;
316 talk_queue_lock();
317 if(p_thumbnail
318 && queue[queue_read].buf == p_thumbnail +thumbnail_buf_used)
319 thumbnail_buf_used = 0;
320 if (sent > 0) /* go to next entry */
322 queue_read = (queue_read + 1) & QUEUE_MASK;
325 re_check:
327 if (QUEUE_LEVEL != 0) /* queue is not empty? */
328 { /* start next clip */
329 #if CONFIG_CODEC != SWCODEC
330 sent = MIN(queue[queue_read].len, 0xFFFF);
331 #else
332 sent = queue[queue_read].len;
333 #endif
334 *start = p_lastclip = queue[queue_read].buf;
335 *size = sent;
336 curr_hd[0] = p_lastclip[1];
337 curr_hd[1] = p_lastclip[2];
338 curr_hd[2] = p_lastclip[3];
340 else if (p_silence != NULL /* silence clip available */
341 && p_lastclip != p_silence /* previous clip wasn't silence */
342 && !(p_lastclip >= p_thumbnail /* ..or thumbnail */
343 && p_lastclip < p_thumbnail +size_for_thumbnail))
344 { /* add silence clip when queue runs empty playing a voice clip */
345 queue[queue_write].buf = p_silence;
346 queue[queue_write].len = silence_len;
347 queue_write = (queue_write + 1) & QUEUE_MASK;
349 goto re_check;
351 else
353 *size = 0; /* end of data */
355 talk_queue_unlock();
358 /***************** Public routines *****************/
360 /* stop the playback and the pending clips */
361 void talk_force_shutup(void)
363 /* Most of this is MAS only */
364 #if CONFIG_CODEC != SWCODEC
365 #ifdef SIMULATOR
366 return;
367 #endif
368 unsigned char* pos;
369 unsigned char* search;
370 unsigned char* end;
371 if (QUEUE_LEVEL == 0) /* has ended anyway */
372 return;
374 #if CONFIG_CPU == SH7034
375 CHCR3 &= ~0x0001; /* disable the DMA (and therefore the interrupt also) */
376 #endif /* CONFIG_CPU == SH7034 */
377 /* search next frame boundary and continue up to there */
378 pos = search = mp3_get_pos();
379 end = queue[queue_read].buf + queue[queue_read].len;
381 if (pos >= queue[queue_read].buf
382 && pos <= end) /* really our clip? */
383 { /* (for strange reasons this isn't nesessarily the case) */
384 /* find the next frame boundary */
385 while (search < end) /* search the remaining data */
387 if (*search++ != 0xFF) /* quick search for frame sync byte */
388 continue; /* (this does the majority of the job) */
390 /* look at the (bitswapped) rest of header candidate */
391 if (search[0] == curr_hd[0] /* do the quicker checks first */
392 && search[2] == curr_hd[2]
393 && (search[1] & 0x30) == (curr_hd[1] & 0x30)) /* sample rate */
395 search--; /* back to the sync byte */
396 break; /* From looking at it, this is our header. */
400 if (search-pos)
401 { /* play old data until the frame end, to keep the MAS in sync */
402 sent = search-pos;
404 queue_write = (queue_read + 1) & QUEUE_MASK; /* will be empty after next callback */
405 queue[queue_read].len = sent; /* current one ends after this */
407 #if CONFIG_CPU == SH7034
408 DTCR3 = sent; /* let the DMA finish this frame */
409 CHCR3 |= 0x0001; /* re-enable DMA */
410 #endif /* CONFIG_CPU == SH7034 */
411 thumbnail_buf_used = 0;
412 return;
415 #endif /* CONFIG_CODEC != SWCODEC */
417 /* Either SWCODEC, or MAS had nothing to do (was frame boundary or not our clip) */
418 mp3_play_stop();
419 talk_queue_lock();
420 queue_write = queue_read = 0; /* reset the queue */
421 thumbnail_buf_used = 0;
422 talk_queue_unlock();
423 need_shutup = false;
426 /* Shutup the voice, except if force_enqueue_next is set. */
427 void talk_shutup(void)
429 if (need_shutup && !force_enqueue_next)
430 talk_force_shutup();
433 /* schedule a clip, at the end or discard the existing queue */
434 static void queue_clip(unsigned char* buf, long size, bool enqueue)
436 int queue_level;
438 if (!enqueue)
439 talk_shutup(); /* cut off all the pending stuff */
440 /* Something is being enqueued, force_enqueue_next override is no
441 longer in effect. */
442 force_enqueue_next = false;
444 if (!size)
445 return; /* safety check */
446 #if CONFIG_CPU == SH7034
447 /* disable the DMA temporarily, to be safe of race condition */
448 CHCR3 &= ~0x0001;
449 #endif
450 talk_queue_lock();
451 queue_level = QUEUE_LEVEL; /* check old level */
453 if (queue_level < QUEUE_SIZE - 1) /* space left? */
455 queue[queue_write].buf = buf; /* populate an entry */
456 queue[queue_write].len = size;
457 queue_write = (queue_write + 1) & QUEUE_MASK;
459 talk_queue_unlock();
461 if (queue_level == 0)
462 { /* queue was empty, we have to do the initial start */
463 p_lastclip = buf;
464 #if CONFIG_CODEC != SWCODEC
465 sent = MIN(size, 0xFFFF); /* DMA can do no more */
466 #else
467 sent = size;
468 #endif
469 mp3_play_data(buf, sent, mp3_callback);
470 curr_hd[0] = buf[1];
471 curr_hd[1] = buf[2];
472 curr_hd[2] = buf[3];
473 mp3_play_pause(true); /* kickoff audio */
475 else
477 #if CONFIG_CPU == SH7034
478 CHCR3 |= 0x0001; /* re-enable DMA */
479 #endif
482 need_shutup = true;
484 return;
488 /* common code for talk_init() and talk_buffer_steal() */
489 static void reset_state(void)
491 queue_write = queue_read = 0; /* reset the queue */
492 p_voicefile = NULL; /* indicate no voicefile (trashed) */
493 #if CONFIG_CODEC == SWCODEC
494 /* Allocate a dedicated thumbnail buffer - once */
495 if (p_thumbnail == NULL)
497 size_for_thumbnail = audiobufend - audiobuf;
498 if (size_for_thumbnail > MAX_THUMBNAIL_BUFSIZE)
499 size_for_thumbnail = MAX_THUMBNAIL_BUFSIZE;
500 p_thumbnail = buffer_alloc(size_for_thumbnail);
502 #else
503 /* Just use the audiobuf, without allocating anything */
504 p_thumbnail = audiobuf;
505 size_for_thumbnail = audiobufend - audiobuf;
506 #endif
507 thumbnail_buf_used = 0;
508 p_silence = NULL; /* pause clip not accessible */
512 /***************** Public implementation *****************/
514 void talk_init(void)
516 talk_temp_disable_count = 0;
517 if (talk_initialized && !strcasecmp(last_lang, global_settings.lang_file))
519 /* not a new file, nothing to do */
520 return;
523 #if (CONFIG_STORAGE & STORAGE_MMC)
524 if (filehandle >= 0) /* MMC: An old voice file might still be open */
526 close(filehandle);
527 filehandle = -1;
529 #endif
531 #if CONFIG_CODEC == SWCODEC
532 if(!talk_initialized)
533 mutex_init(&queue_mutex);
534 #endif /* CONFIG_CODEC == SWCODEC */
536 talk_initialized = true;
537 strncpy((char *) last_lang, (char *)global_settings.lang_file,
538 MAX_FILENAME);
540 #if CONFIG_CODEC == SWCODEC
541 audio_get_buffer(false, NULL); /* Must tell audio to reinitialize */
542 #endif
543 reset_state(); /* use this for most of our inits */
545 filehandle = open_voicefile();
546 has_voicefile = (filehandle >= 0); /* test if we can open it */
547 voicefile_size = 0;
549 if (has_voicefile)
551 voicefile_size = filesize(filehandle);
552 close(filehandle); /* close again, this was just to detect presence */
553 filehandle = -1;
558 #if CONFIG_CODEC == SWCODEC
559 /* return if a voice codec is required or not */
560 bool talk_voice_required(void)
562 return (voicefile_size != 0) /* Voice file is available */
563 || (global_settings.talk_dir_clip) /* Thumbnail clips are required */
564 || (global_settings.talk_file_clip);
566 #endif
568 /* return size of voice file */
569 int talk_get_bufsize(void)
571 return voicefile_size;
574 /* somebody else claims the mp3 buffer, e.g. for regular play/record */
575 void talk_buffer_steal(void)
577 #if CONFIG_CODEC != SWCODEC
578 mp3_play_stop();
579 #endif
580 #if (CONFIG_STORAGE & STORAGE_MMC)
581 if (filehandle >= 0) /* only relevant for MMC */
583 close(filehandle);
584 filehandle = -1;
586 #endif
587 reset_state();
591 /* play a voice ID from voicefile */
592 int talk_id(int32_t id, bool enqueue)
594 long clipsize;
595 unsigned char* clipbuf;
596 int32_t unit;
597 int decimals;
599 if (talk_temp_disable_count > 0)
600 return -1; /* talking has been disabled */
601 #if CONFIG_CODEC != SWCODEC
602 if (audio_status()) /* busy, buffer in use */
603 return -1;
604 #endif
606 if (p_voicefile == NULL && has_voicefile)
607 load_voicefile(); /* reload needed */
609 if (p_voicefile == NULL) /* still no voices? */
610 return -1;
612 if (id == -1) /* -1 is an indication for silence */
613 return -1;
615 decimals = (((uint32_t)id) >> DECIMAL_SHIFT) & 0x7;
617 /* check if this is a special ID, with a value */
618 unit = ((uint32_t)id) >> UNIT_SHIFT;
619 if (unit || decimals)
620 { /* sign-extend the value */
621 id = (uint32_t)id << (32-DECIMAL_SHIFT);
622 id >>= (32-DECIMAL_SHIFT);
624 talk_value_decimal(id, unit, decimals, enqueue); /* speak it */
625 return 0; /* and stop, end of special case */
628 clipbuf = get_clip(id, &clipsize);
629 if (clipbuf == NULL)
630 return -1; /* not present */
632 queue_clip(clipbuf, clipsize, enqueue);
634 return 0;
636 /* Speaks zero or more IDs (from an array). */
637 int talk_idarray(const long *ids, bool enqueue)
639 int r;
640 if(!ids)
641 return 0;
642 while(*ids != TALK_FINAL_ID)
644 if((r = talk_id(*ids++, enqueue)) <0)
645 return r;
646 enqueue = true;
648 return 0;
651 /* Make sure the current utterance is not interrupted by the next one. */
652 void talk_force_enqueue_next(void)
654 force_enqueue_next = true;
657 /* play a thumbnail from file */
658 /* Returns size of spoken thumbnail, so >0 means something is spoken,
659 <=0 means something went wrong. */
660 static int _talk_file(const char* filename,
661 const long *prefix_ids, bool enqueue)
663 int fd;
664 int size;
665 int thumb_used;
666 #if CONFIG_CODEC != SWCODEC
667 struct mp3entry info;
668 #endif
670 if (talk_temp_disable_count > 0)
671 return -1; /* talking has been disabled */
672 #if CONFIG_CODEC != SWCODEC
673 if (audio_status()) /* busy, buffer in use */
674 return -1;
675 #endif
677 if (p_thumbnail == NULL || size_for_thumbnail <= 0)
678 return -1;
680 #if CONFIG_CODEC != SWCODEC
681 if(mp3info(&info, filename)) /* use this to find real start */
683 return 0; /* failed to open, or invalid */
685 #endif
687 if (!enqueue)
688 /* shutup now to free the thumbnail buffer */
689 talk_shutup();
691 fd = open(filename, O_RDONLY);
692 if (fd < 0) /* failed to open */
694 return 0;
697 thumb_used = thumbnail_buf_used;
698 if(filesize(fd) > size_for_thumbnail -thumb_used)
699 { /* Don't play truncated clips */
700 close(fd);
701 return 0;
704 #if CONFIG_CODEC != SWCODEC
705 lseek(fd, info.first_frame_offset, SEEK_SET); /* behind ID data */
706 #endif
708 size = read(fd, p_thumbnail +thumb_used,
709 size_for_thumbnail -thumb_used);
710 close(fd);
712 /* ToDo: find audio, skip ID headers and trailers */
714 if (size > 0) /* Don't play missing clips */
716 #if CONFIG_CODEC != SWCODEC && !defined(SIMULATOR)
717 bitswap(p_thumbnail, size);
718 #endif
719 if(prefix_ids)
720 /* prefix thumbnail by speaking these ids, but only now
721 that we know there's actually a thumbnail to be
722 spoken. */
723 talk_idarray(prefix_ids, true);
724 talk_queue_lock();
725 thumbnail_buf_used = thumb_used +size;
726 talk_queue_unlock();
727 queue_clip(p_thumbnail +thumb_used, size, true);
730 return size;
733 int talk_file(const char *root, const char *dir, const char *file,
734 const char *ext, const long *prefix_ids, bool enqueue)
735 /* Play a thumbnail file */
737 char buf[MAX_PATH];
738 /* Does root end with a slash */
739 char *slash = (root && root[0]
740 && root[strlen(root)-1] != '/') ? "/" : "";
741 snprintf(buf, MAX_PATH, "%s%s%s%s%s%s",
742 root ? root : "", slash,
743 dir ? dir : "", dir ? "/" : "",
744 file ? file : "",
745 ext ? ext : "");
746 return _talk_file(buf, prefix_ids, enqueue);
749 static int talk_spell_basename(const char *path,
750 const long *prefix_ids, bool enqueue)
752 if(prefix_ids)
754 talk_idarray(prefix_ids, enqueue);
755 enqueue = true;
757 char buf[MAX_PATH];
758 /* Spell only the path component after the last slash */
759 strncpy(buf, path, MAX_PATH);
760 if(strlen(buf) >1 && buf[strlen(buf)-1] == '/')
761 /* strip trailing slash */
762 buf[strlen(buf)-1] = '\0';
763 char *ptr = strrchr(buf, '/');
764 if(ptr && strlen(buf) >1)
765 ++ptr;
766 else ptr = buf;
767 return talk_spell(ptr, enqueue);
770 /* Play a file's .talk thumbnail, fallback to spelling the filename, or
771 go straight to spelling depending on settings. */
772 int talk_file_or_spell(const char *dirname, const char *filename,
773 const long *prefix_ids, bool enqueue)
775 if (global_settings.talk_file_clip)
776 { /* .talk clips enabled */
777 if(talk_file(dirname, NULL, filename, file_thumbnail_ext,
778 prefix_ids, enqueue) >0)
779 return 0;
781 if (global_settings.talk_file == 2)
782 /* Either .talk clips are disabled, or as a fallback */
783 return talk_spell_basename(filename, prefix_ids, enqueue);
784 return 0;
787 /* Play a directory's .talk thumbnail, fallback to spelling the filename, or
788 go straight to spelling depending on settings. */
789 int talk_dir_or_spell(const char* dirname,
790 const long *prefix_ids, bool enqueue)
792 if (global_settings.talk_dir_clip)
793 { /* .talk clips enabled */
794 if(talk_file(dirname, NULL, dir_thumbnail_name, NULL,
795 prefix_ids, enqueue) >0)
796 return 0;
798 if (global_settings.talk_dir == 2)
799 /* Either .talk clips disabled or as a fallback */
800 return talk_spell_basename(dirname, prefix_ids, enqueue);
801 return 0;
804 /* say a numeric value, this word ordering works for english,
805 but not necessarily for other languages (e.g. german) */
806 int talk_number(long n, bool enqueue)
808 int level = 2; /* mille count */
809 long mil = 1000000000; /* highest possible "-illion" */
811 if (talk_temp_disable_count > 0)
812 return -1; /* talking has been disabled */
813 #if CONFIG_CODEC != SWCODEC
814 if (audio_status()) /* busy, buffer in use */
815 return -1;
816 #endif
818 if (!enqueue)
819 talk_shutup(); /* cut off all the pending stuff */
821 if (n==0)
822 { /* special case */
823 talk_id(VOICE_ZERO, true);
824 return 0;
827 if (n<0)
829 talk_id(VOICE_MINUS, true);
830 n = -n;
833 while (n)
835 int segment = n / mil; /* extract in groups of 3 digits */
836 n -= segment * mil; /* remove the used digits from number */
837 mil /= 1000; /* digit place for next round */
839 if (segment)
841 int hundreds = segment / 100;
842 int ones = segment % 100;
844 if (hundreds)
846 talk_id(VOICE_ZERO + hundreds, true);
847 talk_id(VOICE_HUNDRED, true);
850 /* combination indexing */
851 if (ones > 20)
853 int tens = ones/10 + 18;
854 talk_id(VOICE_ZERO + tens, true);
855 ones %= 10;
858 /* direct indexing */
859 if (ones)
860 talk_id(VOICE_ZERO + ones, true);
862 /* add billion, million, thousand */
863 if (mil)
864 talk_id(VOICE_THOUSAND + level, true);
866 level--;
869 return 0;
872 /* Say time duration/interval. Input is time in seconds,
873 say hours,minutes,seconds. */
874 static int talk_time_unit(long secs, bool exact, bool enqueue)
876 int hours, mins;
877 if (!enqueue)
878 talk_shutup();
879 if((hours = secs/3600)) {
880 secs %= 3600;
881 talk_value(hours, UNIT_HOUR, true);
883 if((mins = secs/60)) {
884 secs %= 60;
885 if(exact || !hours)
886 talk_value(mins, UNIT_MIN, true);
887 else talk_number(mins, true); /* don't say "minutes" */
889 if((exact && secs) || (!hours && !mins))
890 talk_value(secs, UNIT_SEC, true);
891 else if(!hours && secs)
892 talk_number(secs, true);
893 return 0;
896 void talk_fractional(char *tbuf, int value, int unit)
898 int i;
899 /* strip trailing zeros from the fraction */
900 for (i = strlen(tbuf) - 1; (i >= 0) && (tbuf[i] == '0'); i--)
901 tbuf[i] = '\0';
903 talk_number(value, true);
904 if (tbuf[0] != 0)
906 talk_id(LANG_POINT, true);
907 talk_spell(tbuf, true);
909 talk_id(unit, true);
912 int talk_value(long n, int unit, bool enqueue)
914 return talk_value_decimal(n, unit, 0, enqueue);
917 /* singular/plural aware saying of a value */
918 int talk_value_decimal(long n, int unit, int decimals, bool enqueue)
920 int unit_id;
921 static const int unit_voiced[] =
922 { /* lookup table for the voice ID of the units */
923 [0 ... UNIT_LAST-1] = -1, /* regular ID, int, signed */
924 [UNIT_MS]
925 = VOICE_MILLISECONDS, /* here come the "real" units */
926 [UNIT_SEC]
927 = VOICE_SECONDS,
928 [UNIT_MIN]
929 = VOICE_MINUTES,
930 [UNIT_HOUR]
931 = VOICE_HOURS,
932 [UNIT_KHZ]
933 = VOICE_KHZ,
934 [UNIT_DB]
935 = VOICE_DB,
936 [UNIT_PERCENT]
937 = VOICE_PERCENT,
938 [UNIT_MAH]
939 = VOICE_MILLIAMPHOURS,
940 [UNIT_PIXEL]
941 = VOICE_PIXEL,
942 [UNIT_PER_SEC]
943 = VOICE_PER_SEC,
944 [UNIT_HERTZ]
945 = VOICE_HERTZ,
946 [UNIT_MB]
947 = LANG_MEGABYTE,
948 [UNIT_KBIT]
949 = VOICE_KBIT_PER_SEC,
950 [UNIT_PM_TICK]
951 = VOICE_PM_UNITS_PER_TICK,
954 static const int pow10[] = { /* 10^0 - 10^7 */
955 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000
958 char tbuf[8];
959 char fmt[] = "%0nd";
961 if (talk_temp_disable_count > 0)
962 return -1; /* talking has been disabled */
963 #if CONFIG_CODEC != SWCODEC
964 if (audio_status()) /* busy, buffer in use */
965 return -1;
966 #endif
968 /* special case for time duration */
969 if (unit == UNIT_TIME || unit == UNIT_TIME_EXACT)
970 return talk_time_unit(n, unit == UNIT_TIME_EXACT, enqueue);
972 if (unit < 0 || unit >= UNIT_LAST)
973 unit_id = -1;
974 else
975 unit_id = unit_voiced[unit];
977 if ((n==1 || n==-1) /* singular? */
978 && unit_id >= VOICE_SECONDS && unit_id <= VOICE_HOURS)
980 unit_id--; /* use the singular for those units which have */
983 /* special case with a "plus" before */
984 if (n > 0 && (unit == UNIT_SIGNED || unit == UNIT_DB))
986 talk_id(VOICE_PLUS, enqueue);
987 enqueue = true;
990 if (decimals)
992 /* needed for the "-0.5" corner case */
993 if (n < 0)
995 talk_id(VOICE_MINUS, enqueue);
996 n = -n;
999 fmt[2] = '0' + decimals;
1001 snprintf(tbuf, sizeof(tbuf), fmt, n % pow10[decimals]);
1002 talk_fractional(tbuf, n / pow10[decimals], unit_id);
1004 return 0;
1007 talk_number(n, enqueue); /* say the number */
1008 talk_id(unit_id, true); /* say the unit, if any */
1010 return 0;
1013 /* spell a string */
1014 int talk_spell(const char* spell, bool enqueue)
1016 char c; /* currently processed char */
1018 if (talk_temp_disable_count > 0)
1019 return -1; /* talking has been disabled */
1020 #if CONFIG_CODEC != SWCODEC
1021 if (audio_status()) /* busy, buffer in use */
1022 return -1;
1023 #endif
1025 if (!enqueue)
1026 talk_shutup(); /* cut off all the pending stuff */
1028 while ((c = *spell++) != '\0')
1030 /* if this grows into too many cases, I should use a table */
1031 if (c >= 'A' && c <= 'Z')
1032 talk_id(VOICE_CHAR_A + c - 'A', true);
1033 else if (c >= 'a' && c <= 'z')
1034 talk_id(VOICE_CHAR_A + c - 'a', true);
1035 else if (c >= '0' && c <= '9')
1036 talk_id(VOICE_ZERO + c - '0', true);
1037 else if (c == '-')
1038 talk_id(VOICE_MINUS, true);
1039 else if (c == '+')
1040 talk_id(VOICE_PLUS, true);
1041 else if (c == '.')
1042 talk_id(VOICE_DOT, true);
1043 else if (c == ' ')
1044 talk_id(VOICE_PAUSE, true);
1045 else if (c == '/')
1046 talk_id(VOICE_CHAR_SLASH, true);
1049 return 0;
1052 void talk_disable(bool disable)
1054 if (disable)
1055 talk_temp_disable_count++;
1056 else
1057 talk_temp_disable_count--;
1060 void talk_setting(const void *global_settings_variable)
1062 const struct settings_list *setting;
1063 if (!global_settings.talk_menu)
1064 return;
1065 setting = find_setting(global_settings_variable, NULL);
1066 if (setting == NULL)
1067 return;
1068 if (setting->lang_id)
1069 talk_id(setting->lang_id,false);
1073 #if CONFIG_RTC
1074 void talk_date(const struct tm *tm, bool enqueue)
1076 talk_id(LANG_MONTH_JANUARY + tm->tm_mon, enqueue);
1077 talk_number(tm->tm_mday, true);
1078 talk_number(1900 + tm->tm_year, true);
1081 void talk_time(const struct tm *tm, bool enqueue)
1083 if (global_settings.timeformat == 1)
1085 /* Voice the hour */
1086 long am_pm_id = VOICE_AM;
1087 int hour = tm->tm_hour;
1088 if (hour >= 12)
1090 am_pm_id = VOICE_PM;
1091 hour -= 12;
1093 if (hour == 0)
1094 hour = 12;
1095 talk_number(hour, enqueue);
1097 /* Voice the minutes */
1098 if (tm->tm_min == 0)
1100 /* Say o'clock if the minute is 0. */
1101 talk_id(VOICE_OCLOCK, true);
1103 else
1105 /* Pronounce the leading 0 */
1106 if(tm->tm_min < 10)
1107 talk_id(VOICE_OH, true);
1108 talk_number(tm->tm_min, true);
1110 talk_id(am_pm_id, true);
1112 else
1114 /* Voice the time in 24 hour format */
1115 talk_number(tm->tm_hour, enqueue);
1116 if (tm->tm_min == 0)
1118 talk_id(VOICE_HUNDRED, true);
1119 talk_id(VOICE_HOUR, true);
1121 else
1123 /* Pronounce the leading 0 */
1124 if(tm->tm_min < 10)
1125 talk_id(VOICE_OH, true);
1126 talk_number(tm->tm_min, true);
1131 #endif