Build doom on clipv2 and clip+
[kugel-rb.git] / apps / talk.c
blobe07dcb8262aeab21bf8afba83daeed09ff78a33d
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 "debug.h"
47 /* Memory layout varies between targets because the
48 Archos (MASCODEC) devices cannot mix voice and audio playback
50 MASCODEC | MASCODEC | SWCODEC
51 (playing) | (stopped) |
52 audiobuf-----------+-----------+------------
53 audio | voice | thumbnail
54 |-----------|------------
55 | thumbnail | voice
56 | |------------
57 | | filebuf
58 | |------------
59 | | audio
60 audiobufend----------+-----------+------------
62 SWCODEC allocates dedicated buffers, MASCODEC reuses audiobuf. */
65 /***************** Constants *****************/
67 #define QUEUE_SIZE 64 /* must be a power of two */
68 #define QUEUE_MASK (QUEUE_SIZE-1)
69 const char* const dir_thumbnail_name = "_dirname.talk";
70 const char* const file_thumbnail_ext = ".talk";
72 /***************** Functional Macros *****************/
74 #define QUEUE_LEVEL ((queue_write - queue_read) & QUEUE_MASK)
76 #define LOADED_MASK 0x80000000 /* MSB */
78 #if CONFIG_CODEC == SWCODEC
79 #define MAX_THUMBNAIL_BUFSIZE 0x10000
80 #endif
82 /***************** Data types *****************/
84 struct clip_entry /* one entry of the index table */
86 int offset; /* offset from start of voicefile file */
87 int size; /* size of the clip */
90 struct voicefile /* file format of our voice file */
92 int version; /* version of the voicefile */
93 int target_id; /* the rockbox target the file was made for */
94 int table; /* offset to index table, (=header size) */
95 int id1_max; /* number of "normal" clips contained in above index */
96 int id2_max; /* number of "voice only" clips contained in above index */
97 struct clip_entry index[]; /* followed by the index tables */
98 /* and finally the mp3 clips, not visible here, bitswapped
99 for SH based players */
102 struct queue_entry /* one entry of the internal queue */
104 unsigned char* buf;
105 long len;
109 /***************** Globals *****************/
111 static unsigned char* p_thumbnail = NULL; /* buffer for thumbnails */
112 /* Multiple thumbnails can be loaded back-to-back in this buffer. */
113 static volatile int thumbnail_buf_used SHAREDBSS_ATTR; /* length of data in
114 thumbnail buffer */
115 static long size_for_thumbnail; /* total thumbnail buffer size */
116 static struct voicefile* p_voicefile; /* loaded voicefile */
117 static bool has_voicefile; /* a voicefile file is present */
118 static bool need_shutup; /* is there possibly any voice playing to be shutup */
119 static struct queue_entry queue[QUEUE_SIZE]; /* queue of scheduled clips */
120 static bool force_enqueue_next; /* enqueue next utterance even if enqueue is false */
121 static int queue_write; /* write index of queue, by application */
122 static int queue_read; /* read index of queue, by ISR context */
123 #if CONFIG_CODEC == SWCODEC
124 /* protects queue_read, queue_write and thumbnail_buf_used */
125 static struct mutex queue_mutex SHAREDBSS_ATTR;
126 #define talk_queue_lock() ({ mutex_lock(&queue_mutex); })
127 #define talk_queue_unlock() ({ mutex_unlock(&queue_mutex); })
128 #else
129 #define talk_queue_lock() ({ })
130 #define talk_queue_unlock() ({ })
131 #endif /* CONFIG_CODEC */
132 static int sent; /* how many bytes handed over to playback, owned by ISR */
133 static unsigned char curr_hd[3]; /* current frame header, for re-sync */
134 static int filehandle = -1; /* global, so the MMC variant can keep the file open */
135 static unsigned char* p_silence; /* VOICE_PAUSE clip, used for termination */
136 static long silence_len; /* length of the VOICE_PAUSE clip */
137 static unsigned char* p_lastclip; /* address of latest clip, for silence add */
138 static unsigned long voicefile_size = 0; /* size of the loaded voice file */
139 static unsigned char last_lang[MAX_FILENAME+1]; /* name of last used lang file (in talk_init) */
140 static bool talk_initialized; /* true if talk_init has been called */
141 static int talk_temp_disable_count; /* if positive, temporarily disable voice UI (not saved) */
144 /***************** Private implementation *****************/
146 static int open_voicefile(void)
148 char buf[64];
149 char* p_lang = "english"; /* default */
151 if ( global_settings.lang_file[0] &&
152 global_settings.lang_file[0] != 0xff )
153 { /* try to open the voice file of the selected language */
154 p_lang = (char *)global_settings.lang_file;
157 snprintf(buf, sizeof(buf), LANG_DIR "/%s.voice", p_lang);
159 return open(buf, O_RDONLY);
163 /* fetch a clip from the voice file */
164 static unsigned char* get_clip(long id, long* p_size)
166 long clipsize;
167 unsigned char* clipbuf;
169 if (id > VOICEONLY_DELIMITER)
170 { /* voice-only entries use the second part of the table */
171 id -= VOICEONLY_DELIMITER + 1;
172 if (id >= p_voicefile->id2_max)
173 return NULL; /* must be newer than we have */
174 id += p_voicefile->id1_max; /* table 2 is behind table 1 */
176 else
177 { /* normal use of the first table */
178 if (id >= p_voicefile->id1_max)
179 return NULL; /* must be newer than we have */
182 clipsize = p_voicefile->index[id].size;
183 if (clipsize == 0) /* clip not included in voicefile */
184 return NULL;
185 clipbuf = (unsigned char *) p_voicefile + p_voicefile->index[id].offset;
187 #if (CONFIG_STORAGE & STORAGE_MMC) /* dynamic loading, on demand */
188 if (!(clipsize & LOADED_MASK))
189 { /* clip used for the first time, needs loading */
190 lseek(filehandle, p_voicefile->index[id].offset, SEEK_SET);
191 if (read(filehandle, clipbuf, clipsize) != clipsize)
192 return NULL; /* read error */
194 p_voicefile->index[id].size |= LOADED_MASK; /* mark as loaded */
196 else
197 { /* clip is in memory already */
198 clipsize &= ~LOADED_MASK; /* without the extra bit gives true size */
200 #endif
202 *p_size = clipsize;
203 return clipbuf;
207 /* load the voice file into the mp3 buffer */
208 static void load_voicefile(void)
210 int load_size;
211 int got_size;
212 int file_size;
213 #ifdef ROCKBOX_LITTLE_ENDIAN
214 int i;
215 #endif
217 filehandle = open_voicefile();
218 if (filehandle < 0) /* failed to open */
219 goto load_err;
221 file_size = filesize(filehandle);
222 if (file_size > audiobufend - audiobuf) /* won't fit? */
223 goto load_err;
225 #if (CONFIG_STORAGE & STORAGE_MMC) /* load only the header for now */
226 load_size = offsetof(struct voicefile, index);
227 #else /* load the full file */
228 load_size = file_size;
229 #endif
231 got_size = read(filehandle, audiobuf, load_size);
232 if (got_size != load_size /* failure */)
233 goto load_err;
235 #ifdef ROCKBOX_LITTLE_ENDIAN
236 logf("Byte swapping voice file");
237 structec_convert(audiobuf, "lllll", 1, true);
238 #endif
240 if (((struct voicefile*)audiobuf)->table /* format check */
241 == offsetof(struct voicefile, index))
243 p_voicefile = (struct voicefile*)audiobuf;
245 if (p_voicefile->version != VOICE_VERSION ||
246 p_voicefile->target_id != TARGET_ID)
248 logf("Incompatible voice file");
249 goto load_err;
251 #if CONFIG_CODEC != SWCODEC
252 /* MASCODEC: now use audiobuf for voice then thumbnail */
253 p_thumbnail = audiobuf + file_size;
254 p_thumbnail += (long)p_thumbnail % 2; /* 16-bit align */
255 size_for_thumbnail = audiobufend - p_thumbnail;
256 #endif
258 else
259 goto load_err;
261 #ifdef ROCKBOX_LITTLE_ENDIAN
262 for (i = 0; i < p_voicefile->id1_max + p_voicefile->id2_max; i++)
263 structec_convert(&p_voicefile->index[i], "ll", 1, true);
264 #endif
266 #if (CONFIG_STORAGE & STORAGE_MMC)
267 /* load the index table, now that we know its size from the header */
268 load_size = (p_voicefile->id1_max + p_voicefile->id2_max)
269 * sizeof(struct clip_entry);
270 got_size = read(filehandle,
271 (unsigned char *) p_voicefile + offsetof(struct voicefile, index), load_size);
272 if (got_size != load_size) /* read error */
273 goto load_err;
274 #else
275 close(filehandle); /* only the MMC variant leaves it open */
276 filehandle = -1;
277 #endif
279 /* make sure to have the silence clip, if available */
280 p_silence = get_clip(VOICE_PAUSE, &silence_len);
282 return;
284 load_err:
285 p_voicefile = NULL;
286 has_voicefile = false; /* don't try again */
287 if (filehandle >= 0)
289 close(filehandle);
290 filehandle = -1;
292 return;
296 /* called in ISR context if mp3 data got consumed */
297 static void mp3_callback(unsigned char** start, size_t* size)
299 queue[queue_read].len -= sent; /* we completed this */
300 queue[queue_read].buf += sent;
302 if (queue[queue_read].len > 0) /* current clip not finished? */
303 { /* feed the next 64K-1 chunk */
304 #if CONFIG_CODEC != SWCODEC
305 sent = MIN(queue[queue_read].len, 0xFFFF);
306 #else
307 sent = queue[queue_read].len;
308 #endif
309 *start = queue[queue_read].buf;
310 *size = sent;
311 return;
313 talk_queue_lock();
314 if(p_thumbnail
315 && queue[queue_read].buf == p_thumbnail +thumbnail_buf_used)
316 thumbnail_buf_used = 0;
317 if (sent > 0) /* go to next entry */
319 queue_read = (queue_read + 1) & QUEUE_MASK;
322 re_check:
324 if (QUEUE_LEVEL != 0) /* queue is not empty? */
325 { /* start next clip */
326 #if CONFIG_CODEC != SWCODEC
327 sent = MIN(queue[queue_read].len, 0xFFFF);
328 #else
329 sent = queue[queue_read].len;
330 #endif
331 *start = p_lastclip = queue[queue_read].buf;
332 *size = sent;
333 curr_hd[0] = p_lastclip[1];
334 curr_hd[1] = p_lastclip[2];
335 curr_hd[2] = p_lastclip[3];
337 else if (p_silence != NULL /* silence clip available */
338 && p_lastclip != p_silence /* previous clip wasn't silence */
339 && !(p_lastclip >= p_thumbnail /* ..or thumbnail */
340 && p_lastclip < p_thumbnail +size_for_thumbnail))
341 { /* add silence clip when queue runs empty playing a voice clip */
342 queue[queue_write].buf = p_silence;
343 queue[queue_write].len = silence_len;
344 queue_write = (queue_write + 1) & QUEUE_MASK;
346 goto re_check;
348 else
350 *size = 0; /* end of data */
352 talk_queue_unlock();
355 /***************** Public routines *****************/
357 /* stop the playback and the pending clips */
358 void talk_force_shutup(void)
360 /* Most of this is MAS only */
361 #if CONFIG_CODEC != SWCODEC
362 #ifdef SIMULATOR
363 return;
364 #endif
365 unsigned char* pos;
366 unsigned char* search;
367 unsigned char* end;
368 if (QUEUE_LEVEL == 0) /* has ended anyway */
369 return;
371 #if CONFIG_CPU == SH7034
372 CHCR3 &= ~0x0001; /* disable the DMA (and therefore the interrupt also) */
373 #endif /* CONFIG_CPU == SH7034 */
374 /* search next frame boundary and continue up to there */
375 pos = search = mp3_get_pos();
376 end = queue[queue_read].buf + queue[queue_read].len;
378 if (pos >= queue[queue_read].buf
379 && pos <= end) /* really our clip? */
380 { /* (for strange reasons this isn't nesessarily the case) */
381 /* find the next frame boundary */
382 while (search < end) /* search the remaining data */
384 if (*search++ != 0xFF) /* quick search for frame sync byte */
385 continue; /* (this does the majority of the job) */
387 /* look at the (bitswapped) rest of header candidate */
388 if (search[0] == curr_hd[0] /* do the quicker checks first */
389 && search[2] == curr_hd[2]
390 && (search[1] & 0x30) == (curr_hd[1] & 0x30)) /* sample rate */
392 search--; /* back to the sync byte */
393 break; /* From looking at it, this is our header. */
397 if (search-pos)
398 { /* play old data until the frame end, to keep the MAS in sync */
399 sent = search-pos;
401 queue_write = (queue_read + 1) & QUEUE_MASK; /* will be empty after next callback */
402 queue[queue_read].len = sent; /* current one ends after this */
404 #if CONFIG_CPU == SH7034
405 DTCR3 = sent; /* let the DMA finish this frame */
406 CHCR3 |= 0x0001; /* re-enable DMA */
407 #endif /* CONFIG_CPU == SH7034 */
408 thumbnail_buf_used = 0;
409 return;
412 #endif /* CONFIG_CODEC != SWCODEC */
414 /* Either SWCODEC, or MAS had nothing to do (was frame boundary or not our clip) */
415 mp3_play_stop();
416 talk_queue_lock();
417 queue_write = queue_read = 0; /* reset the queue */
418 thumbnail_buf_used = 0;
419 talk_queue_unlock();
420 need_shutup = false;
423 /* Shutup the voice, except if force_enqueue_next is set. */
424 void talk_shutup(void)
426 if (need_shutup && !force_enqueue_next)
427 talk_force_shutup();
430 /* schedule a clip, at the end or discard the existing queue */
431 static void queue_clip(unsigned char* buf, long size, bool enqueue)
433 int queue_level;
435 if (!enqueue)
436 talk_shutup(); /* cut off all the pending stuff */
437 /* Something is being enqueued, force_enqueue_next override is no
438 longer in effect. */
439 force_enqueue_next = false;
441 if (!size)
442 return; /* safety check */
443 #if CONFIG_CPU == SH7034
444 /* disable the DMA temporarily, to be safe of race condition */
445 CHCR3 &= ~0x0001;
446 #endif
447 talk_queue_lock();
448 queue_level = QUEUE_LEVEL; /* check old level */
450 if (queue_level < QUEUE_SIZE - 1) /* space left? */
452 queue[queue_write].buf = buf; /* populate an entry */
453 queue[queue_write].len = size;
454 queue_write = (queue_write + 1) & QUEUE_MASK;
456 talk_queue_unlock();
458 if (queue_level == 0)
459 { /* queue was empty, we have to do the initial start */
460 p_lastclip = buf;
461 #if CONFIG_CODEC != SWCODEC
462 sent = MIN(size, 0xFFFF); /* DMA can do no more */
463 #else
464 sent = size;
465 #endif
466 mp3_play_data(buf, sent, mp3_callback);
467 curr_hd[0] = buf[1];
468 curr_hd[1] = buf[2];
469 curr_hd[2] = buf[3];
470 mp3_play_pause(true); /* kickoff audio */
472 else
474 #if CONFIG_CPU == SH7034
475 CHCR3 |= 0x0001; /* re-enable DMA */
476 #endif
479 need_shutup = true;
481 return;
485 /* common code for talk_init() and talk_buffer_steal() */
486 static void reset_state(void)
488 queue_write = queue_read = 0; /* reset the queue */
489 p_voicefile = NULL; /* indicate no voicefile (trashed) */
490 #if CONFIG_CODEC == SWCODEC
491 /* Allocate a dedicated thumbnail buffer - once */
492 if (p_thumbnail == NULL)
494 size_for_thumbnail = audiobufend - audiobuf;
495 if (size_for_thumbnail > MAX_THUMBNAIL_BUFSIZE)
496 size_for_thumbnail = MAX_THUMBNAIL_BUFSIZE;
497 p_thumbnail = buffer_alloc(size_for_thumbnail);
499 #else
500 /* Just use the audiobuf, without allocating anything */
501 p_thumbnail = audiobuf;
502 size_for_thumbnail = audiobufend - audiobuf;
503 #endif
504 thumbnail_buf_used = 0;
505 p_silence = NULL; /* pause clip not accessible */
509 /***************** Public implementation *****************/
511 void talk_init(void)
513 talk_temp_disable_count = 0;
514 if (talk_initialized && !strcasecmp(last_lang, global_settings.lang_file))
516 /* not a new file, nothing to do */
517 return;
520 #if (CONFIG_STORAGE & STORAGE_MMC)
521 if (filehandle >= 0) /* MMC: An old voice file might still be open */
523 close(filehandle);
524 filehandle = -1;
526 #endif
528 #if CONFIG_CODEC == SWCODEC
529 if(!talk_initialized)
530 mutex_init(&queue_mutex);
531 #endif /* CONFIG_CODEC == SWCODEC */
533 talk_initialized = true;
534 strlcpy((char *)last_lang, (char *)global_settings.lang_file,
535 MAX_FILENAME);
537 #if CONFIG_CODEC == SWCODEC
538 audio_get_buffer(false, NULL); /* Must tell audio to reinitialize */
539 #endif
540 reset_state(); /* use this for most of our inits */
542 filehandle = open_voicefile();
543 size_t audiobufsz = audiobufend - audiobuf;
544 /* test if we can open and if it fits in the audiobuffer */
545 has_voicefile = filehandle >= 0 && filesize(filehandle) <= (off_t)audiobufsz;
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 #ifdef LOGF_ENABLE
632 if (id > VOICEONLY_DELIMITER)
633 logf("\ntalk_id: Say voice clip 0x%x\n", id);
634 else
635 logf("\ntalk_id: Say '%s'\n", str(id));
636 #endif
638 queue_clip(clipbuf, clipsize, enqueue);
640 return 0;
642 /* Speaks zero or more IDs (from an array). */
643 int talk_idarray(const long *ids, bool enqueue)
645 int r;
646 if(!ids)
647 return 0;
648 while(*ids != TALK_FINAL_ID)
650 if((r = talk_id(*ids++, enqueue)) <0)
651 return r;
652 enqueue = true;
654 return 0;
657 /* Make sure the current utterance is not interrupted by the next one. */
658 void talk_force_enqueue_next(void)
660 force_enqueue_next = true;
663 /* play a thumbnail from file */
664 /* Returns size of spoken thumbnail, so >0 means something is spoken,
665 <=0 means something went wrong. */
666 static int _talk_file(const char* filename,
667 const long *prefix_ids, bool enqueue)
669 int fd;
670 int size;
671 int thumb_used;
672 #if CONFIG_CODEC != SWCODEC
673 struct mp3entry info;
674 #endif
676 if (talk_temp_disable_count > 0)
677 return -1; /* talking has been disabled */
678 #if CONFIG_CODEC != SWCODEC
679 if (audio_status()) /* busy, buffer in use */
680 return -1;
681 #endif
683 if (p_thumbnail == NULL || size_for_thumbnail <= 0)
684 return -1;
686 #if CONFIG_CODEC != SWCODEC
687 if(mp3info(&info, filename)) /* use this to find real start */
689 return 0; /* failed to open, or invalid */
691 #endif
693 if (!enqueue)
694 /* shutup now to free the thumbnail buffer */
695 talk_shutup();
697 fd = open(filename, O_RDONLY);
698 if (fd < 0) /* failed to open */
700 return 0;
703 thumb_used = thumbnail_buf_used;
704 if(filesize(fd) > size_for_thumbnail -thumb_used)
705 { /* Don't play truncated clips */
706 close(fd);
707 return 0;
710 #if CONFIG_CODEC != SWCODEC
711 lseek(fd, info.first_frame_offset, SEEK_SET); /* behind ID data */
712 #endif
714 size = read(fd, p_thumbnail +thumb_used,
715 size_for_thumbnail -thumb_used);
716 close(fd);
718 /* ToDo: find audio, skip ID headers and trailers */
720 if (size > 0) /* Don't play missing clips */
722 #if CONFIG_CODEC != SWCODEC && !defined(SIMULATOR)
723 bitswap(p_thumbnail, size);
724 #endif
725 if(prefix_ids)
726 /* prefix thumbnail by speaking these ids, but only now
727 that we know there's actually a thumbnail to be
728 spoken. */
729 talk_idarray(prefix_ids, true);
730 talk_queue_lock();
731 thumbnail_buf_used = thumb_used +size;
732 talk_queue_unlock();
733 queue_clip(p_thumbnail +thumb_used, size, true);
736 return size;
739 int talk_file(const char *root, const char *dir, const char *file,
740 const char *ext, const long *prefix_ids, bool enqueue)
741 /* Play a thumbnail file */
743 char buf[MAX_PATH];
744 /* Does root end with a slash */
745 char *slash = (root && root[0]
746 && root[strlen(root)-1] != '/') ? "/" : "";
747 snprintf(buf, MAX_PATH, "%s%s%s%s%s%s",
748 root ? root : "", slash,
749 dir ? dir : "", dir ? "/" : "",
750 file ? file : "",
751 ext ? ext : "");
752 return _talk_file(buf, prefix_ids, enqueue);
755 static int talk_spell_basename(const char *path,
756 const long *prefix_ids, bool enqueue)
758 if(prefix_ids)
760 talk_idarray(prefix_ids, enqueue);
761 enqueue = true;
763 char buf[MAX_PATH];
764 /* Spell only the path component after the last slash */
765 strlcpy(buf, path, sizeof(buf));
766 if(strlen(buf) >1 && buf[strlen(buf)-1] == '/')
767 /* strip trailing slash */
768 buf[strlen(buf)-1] = '\0';
769 char *ptr = strrchr(buf, '/');
770 if(ptr && strlen(buf) >1)
771 ++ptr;
772 else ptr = buf;
773 return talk_spell(ptr, enqueue);
776 /* Play a file's .talk thumbnail, fallback to spelling the filename, or
777 go straight to spelling depending on settings. */
778 int talk_file_or_spell(const char *dirname, const char *filename,
779 const long *prefix_ids, bool enqueue)
781 if (global_settings.talk_file_clip)
782 { /* .talk clips enabled */
783 if(talk_file(dirname, NULL, filename, file_thumbnail_ext,
784 prefix_ids, enqueue) >0)
785 return 0;
787 if (global_settings.talk_file == 2)
788 /* Either .talk clips are disabled, or as a fallback */
789 return talk_spell_basename(filename, prefix_ids, enqueue);
790 return 0;
793 /* Play a directory's .talk thumbnail, fallback to spelling the filename, or
794 go straight to spelling depending on settings. */
795 int talk_dir_or_spell(const char* dirname,
796 const long *prefix_ids, bool enqueue)
798 if (global_settings.talk_dir_clip)
799 { /* .talk clips enabled */
800 if(talk_file(dirname, NULL, dir_thumbnail_name, NULL,
801 prefix_ids, enqueue) >0)
802 return 0;
804 if (global_settings.talk_dir == 2)
805 /* Either .talk clips disabled or as a fallback */
806 return talk_spell_basename(dirname, prefix_ids, enqueue);
807 return 0;
810 /* say a numeric value, this word ordering works for english,
811 but not necessarily for other languages (e.g. german) */
812 int talk_number(long n, bool enqueue)
814 int level = 2; /* mille count */
815 long mil = 1000000000; /* highest possible "-illion" */
817 if (talk_temp_disable_count > 0)
818 return -1; /* talking has been disabled */
819 #if CONFIG_CODEC != SWCODEC
820 if (audio_status()) /* busy, buffer in use */
821 return -1;
822 #endif
824 if (!enqueue)
825 talk_shutup(); /* cut off all the pending stuff */
827 if (n==0)
828 { /* special case */
829 talk_id(VOICE_ZERO, true);
830 return 0;
833 if (n<0)
835 talk_id(VOICE_MINUS, true);
836 n = -n;
839 while (n)
841 int segment = n / mil; /* extract in groups of 3 digits */
842 n -= segment * mil; /* remove the used digits from number */
843 mil /= 1000; /* digit place for next round */
845 if (segment)
847 int hundreds = segment / 100;
848 int ones = segment % 100;
850 if (hundreds)
852 talk_id(VOICE_ZERO + hundreds, true);
853 talk_id(VOICE_HUNDRED, true);
856 /* combination indexing */
857 if (ones > 20)
859 int tens = ones/10 + 18;
860 talk_id(VOICE_ZERO + tens, true);
861 ones %= 10;
864 /* direct indexing */
865 if (ones)
866 talk_id(VOICE_ZERO + ones, true);
868 /* add billion, million, thousand */
869 if (mil)
870 talk_id(VOICE_THOUSAND + level, true);
872 level--;
875 return 0;
878 /* Say time duration/interval. Input is time in seconds,
879 say hours,minutes,seconds. */
880 static int talk_time_unit(long secs, bool exact, bool enqueue)
882 int hours, mins;
883 if (!enqueue)
884 talk_shutup();
885 if((hours = secs/3600)) {
886 secs %= 3600;
887 talk_value(hours, UNIT_HOUR, true);
889 if((mins = secs/60)) {
890 secs %= 60;
891 if(exact || !hours)
892 talk_value(mins, UNIT_MIN, true);
893 else talk_number(mins, true); /* don't say "minutes" */
895 if((exact && secs) || (!hours && !mins))
896 talk_value(secs, UNIT_SEC, true);
897 else if(!hours && secs)
898 talk_number(secs, true);
899 return 0;
902 void talk_fractional(char *tbuf, int value, int unit)
904 int i;
905 /* strip trailing zeros from the fraction */
906 for (i = strlen(tbuf) - 1; (i >= 0) && (tbuf[i] == '0'); i--)
907 tbuf[i] = '\0';
909 talk_number(value, true);
910 if (tbuf[0] != 0)
912 talk_id(LANG_POINT, true);
913 talk_spell(tbuf, true);
915 talk_id(unit, true);
918 int talk_value(long n, int unit, bool enqueue)
920 return talk_value_decimal(n, unit, 0, enqueue);
923 /* singular/plural aware saying of a value */
924 int talk_value_decimal(long n, int unit, int decimals, bool enqueue)
926 int unit_id;
927 static const int unit_voiced[] =
928 { /* lookup table for the voice ID of the units */
929 [0 ... UNIT_LAST-1] = -1, /* regular ID, int, signed */
930 [UNIT_MS]
931 = VOICE_MILLISECONDS, /* here come the "real" units */
932 [UNIT_SEC]
933 = VOICE_SECONDS,
934 [UNIT_MIN]
935 = VOICE_MINUTES,
936 [UNIT_HOUR]
937 = VOICE_HOURS,
938 [UNIT_KHZ]
939 = VOICE_KHZ,
940 [UNIT_DB]
941 = VOICE_DB,
942 [UNIT_PERCENT]
943 = VOICE_PERCENT,
944 [UNIT_MAH]
945 = VOICE_MILLIAMPHOURS,
946 [UNIT_PIXEL]
947 = VOICE_PIXEL,
948 [UNIT_PER_SEC]
949 = VOICE_PER_SEC,
950 [UNIT_HERTZ]
951 = VOICE_HERTZ,
952 [UNIT_MB]
953 = LANG_MEGABYTE,
954 [UNIT_KBIT]
955 = VOICE_KBIT_PER_SEC,
956 [UNIT_PM_TICK]
957 = VOICE_PM_UNITS_PER_TICK,
960 static const int pow10[] = { /* 10^0 - 10^7 */
961 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000
964 char tbuf[8];
965 char fmt[] = "%0nd";
967 if (talk_temp_disable_count > 0)
968 return -1; /* talking has been disabled */
969 #if CONFIG_CODEC != SWCODEC
970 if (audio_status()) /* busy, buffer in use */
971 return -1;
972 #endif
974 /* special case for time duration */
975 if (unit == UNIT_TIME || unit == UNIT_TIME_EXACT)
976 return talk_time_unit(n, unit == UNIT_TIME_EXACT, enqueue);
978 if (unit < 0 || unit >= UNIT_LAST)
979 unit_id = -1;
980 else
981 unit_id = unit_voiced[unit];
983 if ((n==1 || n==-1) /* singular? */
984 && unit_id >= VOICE_SECONDS && unit_id <= VOICE_HOURS)
986 unit_id--; /* use the singular for those units which have */
989 /* special case with a "plus" before */
990 if (n > 0 && (unit == UNIT_SIGNED || unit == UNIT_DB))
992 talk_id(VOICE_PLUS, enqueue);
993 enqueue = true;
996 if (decimals)
998 /* needed for the "-0.5" corner case */
999 if (n < 0)
1001 talk_id(VOICE_MINUS, enqueue);
1002 n = -n;
1005 fmt[2] = '0' + decimals;
1007 snprintf(tbuf, sizeof(tbuf), fmt, n % pow10[decimals]);
1008 talk_fractional(tbuf, n / pow10[decimals], unit_id);
1010 return 0;
1013 talk_number(n, enqueue); /* say the number */
1014 talk_id(unit_id, true); /* say the unit, if any */
1016 return 0;
1019 /* spell a string */
1020 int talk_spell(const char* spell, bool enqueue)
1022 char c; /* currently processed char */
1024 if (talk_temp_disable_count > 0)
1025 return -1; /* talking has been disabled */
1026 #if CONFIG_CODEC != SWCODEC
1027 if (audio_status()) /* busy, buffer in use */
1028 return -1;
1029 #endif
1031 if (!enqueue)
1032 talk_shutup(); /* cut off all the pending stuff */
1034 while ((c = *spell++) != '\0')
1036 /* if this grows into too many cases, I should use a table */
1037 if (c >= 'A' && c <= 'Z')
1038 talk_id(VOICE_CHAR_A + c - 'A', true);
1039 else if (c >= 'a' && c <= 'z')
1040 talk_id(VOICE_CHAR_A + c - 'a', true);
1041 else if (c >= '0' && c <= '9')
1042 talk_id(VOICE_ZERO + c - '0', true);
1043 else if (c == '-')
1044 talk_id(VOICE_MINUS, true);
1045 else if (c == '+')
1046 talk_id(VOICE_PLUS, true);
1047 else if (c == '.')
1048 talk_id(VOICE_DOT, true);
1049 else if (c == ' ')
1050 talk_id(VOICE_PAUSE, true);
1051 else if (c == '/')
1052 talk_id(VOICE_CHAR_SLASH, true);
1055 return 0;
1058 void talk_disable(bool disable)
1060 if (disable)
1061 talk_temp_disable_count++;
1062 else
1063 talk_temp_disable_count--;
1066 void talk_setting(const void *global_settings_variable)
1068 const struct settings_list *setting;
1069 if (!global_settings.talk_menu)
1070 return;
1071 setting = find_setting(global_settings_variable, NULL);
1072 if (setting == NULL)
1073 return;
1074 if (setting->lang_id)
1075 talk_id(setting->lang_id,false);
1079 #if CONFIG_RTC
1080 void talk_date(const struct tm *tm, bool enqueue)
1082 talk_id(LANG_MONTH_JANUARY + tm->tm_mon, enqueue);
1083 talk_number(tm->tm_mday, true);
1084 talk_number(1900 + tm->tm_year, true);
1087 void talk_time(const struct tm *tm, bool enqueue)
1089 if (global_settings.timeformat == 1)
1091 /* Voice the hour */
1092 long am_pm_id = VOICE_AM;
1093 int hour = tm->tm_hour;
1094 if (hour >= 12)
1096 am_pm_id = VOICE_PM;
1097 hour -= 12;
1099 if (hour == 0)
1100 hour = 12;
1101 talk_number(hour, enqueue);
1103 /* Voice the minutes */
1104 if (tm->tm_min == 0)
1106 /* Say o'clock if the minute is 0. */
1107 talk_id(VOICE_OCLOCK, true);
1109 else
1111 /* Pronounce the leading 0 */
1112 if(tm->tm_min < 10)
1113 talk_id(VOICE_OH, true);
1114 talk_number(tm->tm_min, true);
1116 talk_id(am_pm_id, true);
1118 else
1120 /* Voice the time in 24 hour format */
1121 talk_number(tm->tm_hour, enqueue);
1122 if (tm->tm_min == 0)
1124 talk_id(VOICE_HUNDRED, true);
1125 talk_id(VOICE_HOUR, true);
1127 else
1129 /* Pronounce the leading 0 */
1130 if(tm->tm_min < 10)
1131 talk_id(VOICE_OH, true);
1132 talk_number(tm->tm_min, true);
1137 #endif