Android: Rework notification and change icon sizes to better meet the systems' standard.
[maemo-rb.git] / apps / talk.c
blob7dbfb2ef775ee5752ac6d06627faef26d77fa44f
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 #if CONFIG_STORAGE & STORAGE_MMC
112 /* The MMC storage on the Ondios is slow enough that we want to buffer the
113 * talk clips only when they are needed */
114 # define TALK_PROGRESSIVE_LOAD
115 #elif CONFIG_CODEC == SWCODEC && MEM <= 2
116 /* The entire voice file wouldn't fit in memory together with codecs, so we
117 * load clips each time they are accessed */
118 # define TALK_PARTIAL_LOAD
119 #endif
121 #ifdef TALK_PARTIAL_LOAD
122 static unsigned char *clip_buffer;
123 static long max_clipsize; /* size of the biggest clip */
124 static long buffered_id[QUEUE_SIZE]; /* IDs of the talk clips */
125 static uint8_t clip_age[QUEUE_SIZE];
126 #if QUEUE_SIZE > 255
127 # error clip_age[] type too small
128 #endif
129 #endif
131 static unsigned char* p_thumbnail = NULL; /* buffer for thumbnails */
132 /* Multiple thumbnails can be loaded back-to-back in this buffer. */
133 static volatile int thumbnail_buf_used SHAREDBSS_ATTR; /* length of data in
134 thumbnail buffer */
135 static long size_for_thumbnail; /* total thumbnail buffer size */
136 static struct voicefile* p_voicefile; /* loaded voicefile */
137 static bool has_voicefile; /* a voicefile file is present */
138 static bool need_shutup; /* is there possibly any voice playing to be shutup */
139 static struct queue_entry queue[QUEUE_SIZE]; /* queue of scheduled clips */
140 static bool force_enqueue_next; /* enqueue next utterance even if enqueue is false */
141 static int queue_write; /* write index of queue, by application */
142 static int queue_read; /* read index of queue, by ISR context */
143 #if CONFIG_CODEC == SWCODEC
144 /* protects queue_read, queue_write and thumbnail_buf_used */
145 static struct mutex queue_mutex SHAREDBSS_ATTR;
146 #define talk_queue_lock() ({ mutex_lock(&queue_mutex); })
147 #define talk_queue_unlock() ({ mutex_unlock(&queue_mutex); })
148 #else
149 #define talk_queue_lock() ({ })
150 #define talk_queue_unlock() ({ })
151 #endif /* CONFIG_CODEC */
152 static int sent; /* how many bytes handed over to playback, owned by ISR */
153 static unsigned char curr_hd[3]; /* current frame header, for re-sync */
154 static int filehandle = -1; /* global, so we can keep the file open if needed */
155 static unsigned char* p_silence; /* VOICE_PAUSE clip, used for termination */
156 static long silence_len; /* length of the VOICE_PAUSE clip */
157 static unsigned char* p_lastclip; /* address of latest clip, for silence add */
158 static unsigned long voicefile_size = 0; /* size of the loaded voice file */
159 static unsigned char last_lang[MAX_FILENAME+1]; /* name of last used lang file (in talk_init) */
160 static bool talk_initialized; /* true if talk_init has been called */
161 static int talk_temp_disable_count; /* if positive, temporarily disable voice UI (not saved) */
164 /***************** Private implementation *****************/
166 static int open_voicefile(void)
168 char buf[64];
169 char* p_lang = "english"; /* default */
171 if ( global_settings.lang_file[0] &&
172 global_settings.lang_file[0] != 0xff )
173 { /* try to open the voice file of the selected language */
174 p_lang = (char *)global_settings.lang_file;
177 snprintf(buf, sizeof(buf), LANG_DIR "/%s.voice", p_lang);
179 return open(buf, O_RDONLY);
183 /* fetch a clip from the voice file */
184 static unsigned char* get_clip(long id, long* p_size)
186 long clipsize;
187 unsigned char* clipbuf;
189 if (id > VOICEONLY_DELIMITER)
190 { /* voice-only entries use the second part of the table */
191 id -= VOICEONLY_DELIMITER + 1;
192 if (id >= p_voicefile->id2_max)
193 return NULL; /* must be newer than we have */
194 id += p_voicefile->id1_max; /* table 2 is behind table 1 */
196 else
197 { /* normal use of the first table */
198 if (id >= p_voicefile->id1_max)
199 return NULL; /* must be newer than we have */
202 clipsize = p_voicefile->index[id].size;
203 if (clipsize == 0) /* clip not included in voicefile */
204 return NULL;
206 #ifndef TALK_PARTIAL_LOAD
207 clipbuf = (unsigned char *) p_voicefile + p_voicefile->index[id].offset;
208 #endif
210 #if defined(TALK_PROGRESSIVE_LOAD) || defined(TALK_PARTIAL_LOAD)
211 if (!(clipsize & LOADED_MASK))
212 { /* clip needs loading */
213 #ifdef TALK_PARTIAL_LOAD
214 int idx = 0;
215 if (id == VOICE_PAUSE) {
216 idx = QUEUE_SIZE; /* we keep VOICE_PAUSE loaded */
217 } else {
218 int oldest = 0, i;
219 for(i=0; i<QUEUE_SIZE; i++) {
220 if (buffered_id[i] < 0) {
221 /* found a free entry, that means the buffer isn't
222 * full yet. */
223 idx = i;
224 break;
227 /* find the oldest clip */
228 if(clip_age[i] > oldest) {
229 idx = i;
230 oldest = clip_age[i];
233 /* increment age of each loaded clip */
234 clip_age[i]++;
236 clip_age[idx] = 0; /* reset clip's age */
238 clipbuf = clip_buffer + idx * max_clipsize;
239 #endif
241 lseek(filehandle, p_voicefile->index[id].offset, SEEK_SET);
242 if (read(filehandle, clipbuf, clipsize) != clipsize)
243 return NULL; /* read error */
245 p_voicefile->index[id].size |= LOADED_MASK; /* mark as loaded */
247 #ifdef TALK_PARTIAL_LOAD
248 if (id != VOICE_PAUSE) {
249 if (buffered_id[idx] >= 0) {
250 /* mark previously loaded clip as unloaded */
251 p_voicefile->index[buffered_id[idx]].size &= ~LOADED_MASK;
253 buffered_id[idx] = id;
255 #endif
257 else
258 { /* clip is in memory already */
259 #ifdef TALK_PARTIAL_LOAD
260 /* Find where it was loaded */
261 clipbuf = clip_buffer;
262 if (id == VOICE_PAUSE) {
263 clipbuf += QUEUE_SIZE * max_clipsize;
264 } else {
265 int idx;
266 for (idx=0; idx<QUEUE_SIZE; idx++)
267 if (buffered_id[idx] == id) {
268 clipbuf += idx * max_clipsize;
269 clip_age[idx] = 0; /* reset clip's age */
270 break;
273 #endif
274 clipsize &= ~LOADED_MASK; /* without the extra bit gives true size */
276 #endif /* defined(TALK_PROGRESSIVE_LOAD) || defined(TALK_PARTIAL_LOAD) */
278 *p_size = clipsize;
279 return clipbuf;
283 /* load the voice file into the mp3 buffer */
284 static void load_voicefile(bool probe)
286 int load_size;
287 int got_size;
288 #ifndef TALK_PARTIAL_LOAD
289 int file_size;
290 #endif
291 #ifdef ROCKBOX_LITTLE_ENDIAN
292 int i;
293 #endif
295 if (!probe)
296 filehandle = open_voicefile();
297 if (filehandle < 0) /* failed to open */
298 goto load_err;
300 #ifndef TALK_PARTIAL_LOAD
301 file_size = filesize(filehandle);
302 if (file_size > audiobufend - audiobuf) /* won't fit? */
303 goto load_err;
304 #endif
306 #if defined(TALK_PROGRESSIVE_LOAD) || defined(TALK_PARTIAL_LOAD)
307 /* load only the header for now */
308 load_size = offsetof(struct voicefile, index);
309 #else /* load the full file */
310 load_size = file_size;
311 #endif
313 #ifdef TALK_PARTIAL_LOAD
314 if (load_size > audiobufend - audiobuf) /* won't fit? */
315 goto load_err;
316 #endif
318 got_size = read(filehandle, audiobuf, load_size);
319 if (got_size != load_size /* failure */)
320 goto load_err;
322 #ifdef ROCKBOX_LITTLE_ENDIAN
323 logf("Byte swapping voice file");
324 structec_convert(audiobuf, "lllll", 1, true);
325 #endif
327 if (((struct voicefile*)audiobuf)->table /* format check */
328 == offsetof(struct voicefile, index))
330 p_voicefile = (struct voicefile*)audiobuf;
332 if (p_voicefile->version != VOICE_VERSION ||
333 p_voicefile->target_id != TARGET_ID)
335 logf("Incompatible voice file");
336 goto load_err;
338 #if CONFIG_CODEC != SWCODEC
339 /* MASCODEC: now use audiobuf for voice then thumbnail */
340 p_thumbnail = audiobuf + file_size;
341 p_thumbnail += (long)p_thumbnail % 2; /* 16-bit align */
342 size_for_thumbnail = audiobufend - p_thumbnail;
343 #endif
345 else
346 goto load_err;
348 #if defined(TALK_PROGRESSIVE_LOAD) || defined(TALK_PARTIAL_LOAD)
349 /* load the index table, now that we know its size from the header */
350 load_size = (p_voicefile->id1_max + p_voicefile->id2_max)
351 * sizeof(struct clip_entry);
353 #ifdef TALK_PARTIAL_LOAD
354 if (load_size > audiobufend - audiobuf) /* won't fit? */
355 goto load_err;
356 #endif
358 got_size = read(filehandle,
359 (unsigned char *) p_voicefile + offsetof(struct voicefile, index), load_size);
360 if (got_size != load_size) /* read error */
361 goto load_err;
362 #else
363 close(filehandle);
364 filehandle = -1;
365 #endif /* defined(TALK_PROGRESSIVE_LOAD) || defined(TALK_PARTIAL_LOAD) */
367 #ifdef ROCKBOX_LITTLE_ENDIAN
368 for (i = 0; i < p_voicefile->id1_max + p_voicefile->id2_max; i++)
369 structec_convert(&p_voicefile->index[i], "ll", 1, true);
370 #endif
372 #ifdef TALK_PARTIAL_LOAD
373 clip_buffer = (unsigned char *) p_voicefile + p_voicefile->table;
374 unsigned clips = p_voicefile->id1_max + p_voicefile->id2_max;
375 clip_buffer += clips * sizeof(struct clip_entry); /* skip index */
376 #endif
377 if (!probe) {
378 /* make sure to have the silence clip, if available */
379 p_silence = get_clip(VOICE_PAUSE, &silence_len);
382 return;
384 load_err:
385 p_voicefile = NULL;
386 has_voicefile = false; /* don't try again */
387 if (filehandle >= 0)
389 close(filehandle);
390 filehandle = -1;
392 return;
396 /* called in ISR context if mp3 data got consumed */
397 static void mp3_callback(unsigned char** start, size_t* size)
399 queue[queue_read].len -= sent; /* we completed this */
400 queue[queue_read].buf += sent;
402 if (queue[queue_read].len > 0) /* current clip not finished? */
403 { /* feed the next 64K-1 chunk */
404 #if CONFIG_CODEC != SWCODEC
405 sent = MIN(queue[queue_read].len, 0xFFFF);
406 #else
407 sent = queue[queue_read].len;
408 #endif
409 *start = queue[queue_read].buf;
410 *size = sent;
411 return;
413 talk_queue_lock();
414 if(p_thumbnail
415 && queue[queue_read].buf == p_thumbnail +thumbnail_buf_used)
416 thumbnail_buf_used = 0;
417 if (sent > 0) /* go to next entry */
419 queue_read = (queue_read + 1) & QUEUE_MASK;
422 re_check:
424 if (QUEUE_LEVEL != 0) /* queue is not empty? */
425 { /* start next clip */
426 #if CONFIG_CODEC != SWCODEC
427 sent = MIN(queue[queue_read].len, 0xFFFF);
428 #else
429 sent = queue[queue_read].len;
430 #endif
431 *start = p_lastclip = queue[queue_read].buf;
432 *size = sent;
433 curr_hd[0] = p_lastclip[1];
434 curr_hd[1] = p_lastclip[2];
435 curr_hd[2] = p_lastclip[3];
437 else if (p_silence != NULL /* silence clip available */
438 && p_lastclip != p_silence /* previous clip wasn't silence */
439 && !(p_lastclip >= p_thumbnail /* ..or thumbnail */
440 && p_lastclip < p_thumbnail +size_for_thumbnail))
441 { /* add silence clip when queue runs empty playing a voice clip */
442 queue[queue_write].buf = p_silence;
443 queue[queue_write].len = silence_len;
444 queue_write = (queue_write + 1) & QUEUE_MASK;
446 goto re_check;
448 else
450 *size = 0; /* end of data */
452 talk_queue_unlock();
455 /***************** Public routines *****************/
457 /* stop the playback and the pending clips */
458 void talk_force_shutup(void)
460 /* Most of this is MAS only */
461 #if CONFIG_CODEC != SWCODEC
462 #ifdef SIMULATOR
463 return;
464 #endif
465 unsigned char* pos;
466 unsigned char* search;
467 unsigned char* end;
468 if (QUEUE_LEVEL == 0) /* has ended anyway */
469 return;
471 #if CONFIG_CPU == SH7034
472 CHCR3 &= ~0x0001; /* disable the DMA (and therefore the interrupt also) */
473 #endif /* CONFIG_CPU == SH7034 */
474 /* search next frame boundary and continue up to there */
475 pos = search = mp3_get_pos();
476 end = queue[queue_read].buf + queue[queue_read].len;
478 if (pos >= queue[queue_read].buf
479 && pos <= end) /* really our clip? */
480 { /* (for strange reasons this isn't nesessarily the case) */
481 /* find the next frame boundary */
482 while (search < end) /* search the remaining data */
484 if (*search++ != 0xFF) /* quick search for frame sync byte */
485 continue; /* (this does the majority of the job) */
487 /* look at the (bitswapped) rest of header candidate */
488 if (search[0] == curr_hd[0] /* do the quicker checks first */
489 && search[2] == curr_hd[2]
490 && (search[1] & 0x30) == (curr_hd[1] & 0x30)) /* sample rate */
492 search--; /* back to the sync byte */
493 break; /* From looking at it, this is our header. */
497 if (search-pos)
498 { /* play old data until the frame end, to keep the MAS in sync */
499 sent = search-pos;
501 queue_write = (queue_read + 1) & QUEUE_MASK; /* will be empty after next callback */
502 queue[queue_read].len = sent; /* current one ends after this */
504 #if CONFIG_CPU == SH7034
505 DTCR3 = sent; /* let the DMA finish this frame */
506 CHCR3 |= 0x0001; /* re-enable DMA */
507 #endif /* CONFIG_CPU == SH7034 */
508 thumbnail_buf_used = 0;
509 return;
512 #endif /* CONFIG_CODEC != SWCODEC */
514 /* Either SWCODEC, or MAS had nothing to do (was frame boundary or not our clip) */
515 mp3_play_stop();
516 talk_queue_lock();
517 queue_write = queue_read = 0; /* reset the queue */
518 thumbnail_buf_used = 0;
519 talk_queue_unlock();
520 need_shutup = false;
523 /* Shutup the voice, except if force_enqueue_next is set. */
524 void talk_shutup(void)
526 if (need_shutup && !force_enqueue_next)
527 talk_force_shutup();
530 /* schedule a clip, at the end or discard the existing queue */
531 static void queue_clip(unsigned char* buf, long size, bool enqueue)
533 int queue_level;
535 if (!enqueue)
536 talk_shutup(); /* cut off all the pending stuff */
537 /* Something is being enqueued, force_enqueue_next override is no
538 longer in effect. */
539 force_enqueue_next = false;
541 if (!size)
542 return; /* safety check */
543 #if CONFIG_CPU == SH7034
544 /* disable the DMA temporarily, to be safe of race condition */
545 CHCR3 &= ~0x0001;
546 #endif
547 talk_queue_lock();
548 queue_level = QUEUE_LEVEL; /* check old level */
550 if (queue_level < QUEUE_SIZE - 1) /* space left? */
552 queue[queue_write].buf = buf; /* populate an entry */
553 queue[queue_write].len = size;
554 queue_write = (queue_write + 1) & QUEUE_MASK;
556 talk_queue_unlock();
558 if (queue_level == 0)
559 { /* queue was empty, we have to do the initial start */
560 p_lastclip = buf;
561 #if CONFIG_CODEC != SWCODEC
562 sent = MIN(size, 0xFFFF); /* DMA can do no more */
563 #else
564 sent = size;
565 #endif
566 mp3_play_data(buf, sent, mp3_callback);
567 curr_hd[0] = buf[1];
568 curr_hd[1] = buf[2];
569 curr_hd[2] = buf[3];
570 mp3_play_pause(true); /* kickoff audio */
572 else
574 #if CONFIG_CPU == SH7034
575 CHCR3 |= 0x0001; /* re-enable DMA */
576 #endif
579 need_shutup = true;
581 return;
585 /* common code for talk_init() and talk_buffer_steal() */
586 static void reset_state(void)
588 queue_write = queue_read = 0; /* reset the queue */
589 p_voicefile = NULL; /* indicate no voicefile (trashed) */
590 #if CONFIG_CODEC == SWCODEC
591 /* Allocate a dedicated thumbnail buffer - once */
592 if (p_thumbnail == NULL)
594 size_for_thumbnail = audiobufend - audiobuf;
595 if (size_for_thumbnail > MAX_THUMBNAIL_BUFSIZE)
596 size_for_thumbnail = MAX_THUMBNAIL_BUFSIZE;
597 p_thumbnail = buffer_alloc(size_for_thumbnail);
599 #else
600 /* Just use the audiobuf, without allocating anything */
601 p_thumbnail = audiobuf;
602 size_for_thumbnail = audiobufend - audiobuf;
603 #endif
605 #ifdef TALK_PARTIAL_LOAD
606 int i;
607 for(i=0; i<QUEUE_SIZE; i++)
608 buffered_id[i] = -1;
609 #endif
611 thumbnail_buf_used = 0;
612 p_silence = NULL; /* pause clip not accessible */
616 /***************** Public implementation *****************/
618 void talk_init(void)
620 talk_temp_disable_count = 0;
621 if (talk_initialized && !strcasecmp(last_lang, global_settings.lang_file))
623 /* not a new file, nothing to do */
624 return;
627 #if defined(TALK_PROGRESSIVE_LOAD) || defined(TALK_PARTIAL_LOAD)
628 if (filehandle >= 0)
630 close(filehandle);
631 filehandle = -1;
633 #endif
635 #if CONFIG_CODEC == SWCODEC
636 if(!talk_initialized)
637 mutex_init(&queue_mutex);
638 #endif /* CONFIG_CODEC == SWCODEC */
640 talk_initialized = true;
641 strlcpy((char *)last_lang, (char *)global_settings.lang_file,
642 MAX_FILENAME);
644 #if CONFIG_CODEC == SWCODEC
645 audio_get_buffer(false, NULL); /* Must tell audio to reinitialize */
646 #endif
647 reset_state(); /* use this for most of our inits */
649 filehandle = open_voicefile();
650 if (filehandle < 0) {
651 has_voicefile = false;
652 voicefile_size = 0;
653 return;
656 voicefile_size = filesize(filehandle);
658 /* test if we can open and if it fits in the audiobuffer */
659 size_t audiobufsz = audiobufend - audiobuf;
661 #ifdef TALK_PARTIAL_LOAD
662 /* we won't load the full file, we only need the index */
663 load_voicefile(true);
664 if (!p_voicefile)
665 return;
667 unsigned clips = p_voicefile->id1_max + p_voicefile->id2_max;
668 unsigned i;
669 int silence_size = 0;
671 for(i=0; i<clips; i++) {
672 int size = p_voicefile->index[i].size;
673 if (size > max_clipsize)
674 max_clipsize = size;
675 if (i == VOICE_PAUSE)
676 silence_size = size;
679 voicefile_size = p_voicefile->table + clips * sizeof(struct clip_entry);
680 voicefile_size += max_clipsize * QUEUE_SIZE + silence_size;
681 p_voicefile = NULL; /* Don't pretend we can load talk clips just yet */
682 #endif
684 if (voicefile_size <= audiobufsz) {
685 has_voicefile = true;
686 } else {
687 has_voicefile = false;
688 voicefile_size = 0;
691 close(filehandle); /* close again, this was just to detect presence */
692 filehandle = -1;
695 #if CONFIG_CODEC == SWCODEC
696 /* return if a voice codec is required or not */
697 bool talk_voice_required(void)
699 return (voicefile_size != 0) /* Voice file is available */
700 || (global_settings.talk_dir_clip) /* Thumbnail clips are required */
701 || (global_settings.talk_file_clip);
703 #endif
705 /* return size of voice file */
706 int talk_get_bufsize(void)
708 return voicefile_size;
711 /* somebody else claims the mp3 buffer, e.g. for regular play/record */
712 void talk_buffer_steal(void)
714 #if CONFIG_CODEC != SWCODEC
715 mp3_play_stop();
716 #endif
717 #if defined(TALK_PROGRESSIVE_LOAD) || defined(TALK_PARTIAL_LOAD)
718 if (filehandle >= 0)
720 close(filehandle);
721 filehandle = -1;
723 #endif
724 reset_state();
728 /* play a voice ID from voicefile */
729 int talk_id(int32_t id, bool enqueue)
731 long clipsize;
732 unsigned char* clipbuf;
733 int32_t unit;
734 int decimals;
736 if (talk_temp_disable_count > 0)
737 return -1; /* talking has been disabled */
738 #if CONFIG_CODEC != SWCODEC
739 if (audio_status()) /* busy, buffer in use */
740 return -1;
741 #endif
743 if (p_voicefile == NULL && has_voicefile)
744 load_voicefile(false); /* reload needed */
746 if (p_voicefile == NULL) /* still no voices? */
747 return -1;
749 if (id == -1) /* -1 is an indication for silence */
750 return -1;
752 decimals = (((uint32_t)id) >> DECIMAL_SHIFT) & 0x7;
754 /* check if this is a special ID, with a value */
755 unit = ((uint32_t)id) >> UNIT_SHIFT;
756 if (unit || decimals)
757 { /* sign-extend the value */
758 id = (uint32_t)id << (32-DECIMAL_SHIFT);
759 id >>= (32-DECIMAL_SHIFT);
761 talk_value_decimal(id, unit, decimals, enqueue); /* speak it */
762 return 0; /* and stop, end of special case */
765 clipbuf = get_clip(id, &clipsize);
766 if (clipbuf == NULL)
767 return -1; /* not present */
769 #ifdef LOGF_ENABLE
770 if (id > VOICEONLY_DELIMITER)
771 logf("\ntalk_id: Say voice clip 0x%x\n", id);
772 else
773 logf("\ntalk_id: Say '%s'\n", str(id));
774 #endif
776 queue_clip(clipbuf, clipsize, enqueue);
778 return 0;
780 /* Speaks zero or more IDs (from an array). */
781 int talk_idarray(const long *ids, bool enqueue)
783 int r;
784 if(!ids)
785 return 0;
786 while(*ids != TALK_FINAL_ID)
788 if((r = talk_id(*ids++, enqueue)) <0)
789 return r;
790 enqueue = true;
792 return 0;
795 /* Make sure the current utterance is not interrupted by the next one. */
796 void talk_force_enqueue_next(void)
798 force_enqueue_next = true;
801 /* play a thumbnail from file */
802 /* Returns size of spoken thumbnail, so >0 means something is spoken,
803 <=0 means something went wrong. */
804 static int _talk_file(const char* filename,
805 const long *prefix_ids, bool enqueue)
807 int fd;
808 int size;
809 int thumb_used;
810 #if CONFIG_CODEC != SWCODEC
811 struct mp3entry info;
812 #endif
814 if (talk_temp_disable_count > 0)
815 return -1; /* talking has been disabled */
816 #if CONFIG_CODEC != SWCODEC
817 if (audio_status()) /* busy, buffer in use */
818 return -1;
819 #endif
821 if (p_thumbnail == NULL || size_for_thumbnail <= 0)
822 return -1;
824 #if CONFIG_CODEC != SWCODEC
825 if(mp3info(&info, filename)) /* use this to find real start */
827 return 0; /* failed to open, or invalid */
829 #endif
831 if (!enqueue)
832 /* shutup now to free the thumbnail buffer */
833 talk_shutup();
835 fd = open(filename, O_RDONLY);
836 if (fd < 0) /* failed to open */
838 return 0;
841 thumb_used = thumbnail_buf_used;
842 if(filesize(fd) > size_for_thumbnail -thumb_used)
843 { /* Don't play truncated clips */
844 close(fd);
845 return 0;
848 #if CONFIG_CODEC != SWCODEC
849 lseek(fd, info.first_frame_offset, SEEK_SET); /* behind ID data */
850 #endif
852 size = read(fd, p_thumbnail +thumb_used,
853 size_for_thumbnail -thumb_used);
854 close(fd);
856 /* ToDo: find audio, skip ID headers and trailers */
858 if (size > 0) /* Don't play missing clips */
860 #if CONFIG_CODEC != SWCODEC && !defined(SIMULATOR)
861 bitswap(p_thumbnail, size);
862 #endif
863 if(prefix_ids)
864 /* prefix thumbnail by speaking these ids, but only now
865 that we know there's actually a thumbnail to be
866 spoken. */
867 talk_idarray(prefix_ids, true);
868 talk_queue_lock();
869 thumbnail_buf_used = thumb_used +size;
870 talk_queue_unlock();
871 queue_clip(p_thumbnail +thumb_used, size, true);
874 return size;
877 int talk_file(const char *root, const char *dir, const char *file,
878 const char *ext, const long *prefix_ids, bool enqueue)
879 /* Play a thumbnail file */
881 char buf[MAX_PATH];
882 /* Does root end with a slash */
883 char *slash = (root && root[0]
884 && root[strlen(root)-1] != '/') ? "/" : "";
885 snprintf(buf, MAX_PATH, "%s%s%s%s%s%s",
886 root ? root : "", slash,
887 dir ? dir : "", dir ? "/" : "",
888 file ? file : "",
889 ext ? ext : "");
890 return _talk_file(buf, prefix_ids, enqueue);
893 static int talk_spell_basename(const char *path,
894 const long *prefix_ids, bool enqueue)
896 if(prefix_ids)
898 talk_idarray(prefix_ids, enqueue);
899 enqueue = true;
901 char buf[MAX_PATH];
902 /* Spell only the path component after the last slash */
903 strlcpy(buf, path, sizeof(buf));
904 if(strlen(buf) >1 && buf[strlen(buf)-1] == '/')
905 /* strip trailing slash */
906 buf[strlen(buf)-1] = '\0';
907 char *ptr = strrchr(buf, '/');
908 if(ptr && strlen(buf) >1)
909 ++ptr;
910 else ptr = buf;
911 return talk_spell(ptr, enqueue);
914 /* Play a file's .talk thumbnail, fallback to spelling the filename, or
915 go straight to spelling depending on settings. */
916 int talk_file_or_spell(const char *dirname, const char *filename,
917 const long *prefix_ids, bool enqueue)
919 if (global_settings.talk_file_clip)
920 { /* .talk clips enabled */
921 if(talk_file(dirname, NULL, filename, file_thumbnail_ext,
922 prefix_ids, enqueue) >0)
923 return 0;
925 if (global_settings.talk_file == 2)
926 /* Either .talk clips are disabled, or as a fallback */
927 return talk_spell_basename(filename, prefix_ids, enqueue);
928 return 0;
931 /* Play a directory's .talk thumbnail, fallback to spelling the filename, or
932 go straight to spelling depending on settings. */
933 int talk_dir_or_spell(const char* dirname,
934 const long *prefix_ids, bool enqueue)
936 if (global_settings.talk_dir_clip)
937 { /* .talk clips enabled */
938 if(talk_file(dirname, NULL, dir_thumbnail_name, NULL,
939 prefix_ids, enqueue) >0)
940 return 0;
942 if (global_settings.talk_dir == 2)
943 /* Either .talk clips disabled or as a fallback */
944 return talk_spell_basename(dirname, prefix_ids, enqueue);
945 return 0;
948 /* say a numeric value, this word ordering works for english,
949 but not necessarily for other languages (e.g. german) */
950 int talk_number(long n, bool enqueue)
952 int level = 2; /* mille count */
953 long mil = 1000000000; /* highest possible "-illion" */
955 if (talk_temp_disable_count > 0)
956 return -1; /* talking has been disabled */
957 #if CONFIG_CODEC != SWCODEC
958 if (audio_status()) /* busy, buffer in use */
959 return -1;
960 #endif
962 if (!enqueue)
963 talk_shutup(); /* cut off all the pending stuff */
965 if (n==0)
966 { /* special case */
967 talk_id(VOICE_ZERO, true);
968 return 0;
971 if (n<0)
973 talk_id(VOICE_MINUS, true);
974 n = -n;
977 while (n)
979 int segment = n / mil; /* extract in groups of 3 digits */
980 n -= segment * mil; /* remove the used digits from number */
981 mil /= 1000; /* digit place for next round */
983 if (segment)
985 int hundreds = segment / 100;
986 int ones = segment % 100;
988 if (hundreds)
990 talk_id(VOICE_ZERO + hundreds, true);
991 talk_id(VOICE_HUNDRED, true);
994 /* combination indexing */
995 if (ones > 20)
997 int tens = ones/10 + 18;
998 talk_id(VOICE_ZERO + tens, true);
999 ones %= 10;
1002 /* direct indexing */
1003 if (ones)
1004 talk_id(VOICE_ZERO + ones, true);
1006 /* add billion, million, thousand */
1007 if (mil)
1008 talk_id(VOICE_THOUSAND + level, true);
1010 level--;
1013 return 0;
1016 /* Say time duration/interval. Input is time in seconds,
1017 say hours,minutes,seconds. */
1018 static int talk_time_unit(long secs, bool exact, bool enqueue)
1020 int hours, mins;
1021 if (!enqueue)
1022 talk_shutup();
1023 if((hours = secs/3600)) {
1024 secs %= 3600;
1025 talk_value(hours, UNIT_HOUR, true);
1027 if((mins = secs/60)) {
1028 secs %= 60;
1029 if(exact || !hours)
1030 talk_value(mins, UNIT_MIN, true);
1031 else talk_number(mins, true); /* don't say "minutes" */
1033 if((exact && secs) || (!hours && !mins))
1034 talk_value(secs, UNIT_SEC, true);
1035 else if(!hours && secs)
1036 talk_number(secs, true);
1037 return 0;
1040 void talk_fractional(char *tbuf, int value, int unit)
1042 int i;
1043 /* strip trailing zeros from the fraction */
1044 for (i = strlen(tbuf) - 1; (i >= 0) && (tbuf[i] == '0'); i--)
1045 tbuf[i] = '\0';
1047 talk_number(value, true);
1048 if (tbuf[0] != 0)
1050 talk_id(LANG_POINT, true);
1051 talk_spell(tbuf, true);
1053 talk_id(unit, true);
1056 int talk_value(long n, int unit, bool enqueue)
1058 return talk_value_decimal(n, unit, 0, enqueue);
1061 /* singular/plural aware saying of a value */
1062 int talk_value_decimal(long n, int unit, int decimals, bool enqueue)
1064 int unit_id;
1065 static const int unit_voiced[] =
1066 { /* lookup table for the voice ID of the units */
1067 [0 ... UNIT_LAST-1] = -1, /* regular ID, int, signed */
1068 [UNIT_MS]
1069 = VOICE_MILLISECONDS, /* here come the "real" units */
1070 [UNIT_SEC]
1071 = VOICE_SECONDS,
1072 [UNIT_MIN]
1073 = VOICE_MINUTES,
1074 [UNIT_HOUR]
1075 = VOICE_HOURS,
1076 [UNIT_KHZ]
1077 = VOICE_KHZ,
1078 [UNIT_DB]
1079 = VOICE_DB,
1080 [UNIT_PERCENT]
1081 = VOICE_PERCENT,
1082 [UNIT_MAH]
1083 = VOICE_MILLIAMPHOURS,
1084 [UNIT_PIXEL]
1085 = VOICE_PIXEL,
1086 [UNIT_PER_SEC]
1087 = VOICE_PER_SEC,
1088 [UNIT_HERTZ]
1089 = VOICE_HERTZ,
1090 [UNIT_MB]
1091 = LANG_MEGABYTE,
1092 [UNIT_KBIT]
1093 = VOICE_KBIT_PER_SEC,
1094 [UNIT_PM_TICK]
1095 = VOICE_PM_UNITS_PER_TICK,
1098 static const int pow10[] = { /* 10^0 - 10^7 */
1099 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000
1102 char tbuf[8];
1103 char fmt[] = "%0nd";
1105 if (talk_temp_disable_count > 0)
1106 return -1; /* talking has been disabled */
1107 #if CONFIG_CODEC != SWCODEC
1108 if (audio_status()) /* busy, buffer in use */
1109 return -1;
1110 #endif
1112 /* special case for time duration */
1113 if (unit == UNIT_TIME || unit == UNIT_TIME_EXACT)
1114 return talk_time_unit(n, unit == UNIT_TIME_EXACT, enqueue);
1116 if (unit < 0 || unit >= UNIT_LAST)
1117 unit_id = -1;
1118 else
1119 unit_id = unit_voiced[unit];
1121 if ((n==1 || n==-1) /* singular? */
1122 && unit_id >= VOICE_SECONDS && unit_id <= VOICE_HOURS)
1124 unit_id--; /* use the singular for those units which have */
1127 /* special case with a "plus" before */
1128 if (n > 0 && (unit == UNIT_SIGNED || unit == UNIT_DB))
1130 talk_id(VOICE_PLUS, enqueue);
1131 enqueue = true;
1134 if (decimals)
1136 /* needed for the "-0.5" corner case */
1137 if (n < 0)
1139 talk_id(VOICE_MINUS, enqueue);
1140 n = -n;
1143 fmt[2] = '0' + decimals;
1145 snprintf(tbuf, sizeof(tbuf), fmt, n % pow10[decimals]);
1146 talk_fractional(tbuf, n / pow10[decimals], unit_id);
1148 return 0;
1151 talk_number(n, enqueue); /* say the number */
1152 talk_id(unit_id, true); /* say the unit, if any */
1154 return 0;
1157 /* spell a string */
1158 int talk_spell(const char* spell, bool enqueue)
1160 char c; /* currently processed char */
1162 if (talk_temp_disable_count > 0)
1163 return -1; /* talking has been disabled */
1164 #if CONFIG_CODEC != SWCODEC
1165 if (audio_status()) /* busy, buffer in use */
1166 return -1;
1167 #endif
1169 if (!enqueue)
1170 talk_shutup(); /* cut off all the pending stuff */
1172 while ((c = *spell++) != '\0')
1174 /* if this grows into too many cases, I should use a table */
1175 if (c >= 'A' && c <= 'Z')
1176 talk_id(VOICE_CHAR_A + c - 'A', true);
1177 else if (c >= 'a' && c <= 'z')
1178 talk_id(VOICE_CHAR_A + c - 'a', true);
1179 else if (c >= '0' && c <= '9')
1180 talk_id(VOICE_ZERO + c - '0', true);
1181 else if (c == '-')
1182 talk_id(VOICE_MINUS, true);
1183 else if (c == '+')
1184 talk_id(VOICE_PLUS, true);
1185 else if (c == '.')
1186 talk_id(VOICE_DOT, true);
1187 else if (c == ' ')
1188 talk_id(VOICE_PAUSE, true);
1189 else if (c == '/')
1190 talk_id(VOICE_CHAR_SLASH, true);
1193 return 0;
1196 void talk_disable(bool disable)
1198 if (disable)
1199 talk_temp_disable_count++;
1200 else
1201 talk_temp_disable_count--;
1204 void talk_setting(const void *global_settings_variable)
1206 const struct settings_list *setting;
1207 if (!global_settings.talk_menu)
1208 return;
1209 setting = find_setting(global_settings_variable, NULL);
1210 if (setting == NULL)
1211 return;
1212 if (setting->lang_id)
1213 talk_id(setting->lang_id,false);
1217 #if CONFIG_RTC
1218 void talk_date(const struct tm *tm, bool enqueue)
1220 talk_id(LANG_MONTH_JANUARY + tm->tm_mon, enqueue);
1221 talk_number(tm->tm_mday, true);
1222 talk_number(1900 + tm->tm_year, true);
1225 void talk_time(const struct tm *tm, bool enqueue)
1227 if (global_settings.timeformat == 1)
1229 /* Voice the hour */
1230 long am_pm_id = VOICE_AM;
1231 int hour = tm->tm_hour;
1232 if (hour >= 12)
1234 am_pm_id = VOICE_PM;
1235 hour -= 12;
1237 if (hour == 0)
1238 hour = 12;
1239 talk_number(hour, enqueue);
1241 /* Voice the minutes */
1242 if (tm->tm_min == 0)
1244 /* Say o'clock if the minute is 0. */
1245 talk_id(VOICE_OCLOCK, true);
1247 else
1249 /* Pronounce the leading 0 */
1250 if(tm->tm_min < 10)
1251 talk_id(VOICE_OH, true);
1252 talk_number(tm->tm_min, true);
1254 talk_id(am_pm_id, true);
1256 else
1258 /* Voice the time in 24 hour format */
1259 talk_number(tm->tm_hour, enqueue);
1260 if (tm->tm_min == 0)
1262 talk_id(VOICE_HUNDRED, true);
1263 talk_id(VOICE_HOUR, true);
1265 else
1267 /* Pronounce the leading 0 */
1268 if(tm->tm_min < 10)
1269 talk_id(VOICE_OH, true);
1270 talk_number(tm->tm_min, true);
1275 #endif /* CONFIG_RTC */