gitscraper: Provide way to get timestamps for files.
[maemo-rb.git] / apps / talk.c
blob4b0975083dc6f32e129fc4399127df1fe1ab8940
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 "system.h"
31 #include "kernel.h"
32 #include "settings.h"
33 #include "settings_list.h"
34 #include "mp3_playback.h"
35 #include "audio.h"
36 #include "lang.h"
37 #include "talk.h"
38 #include "metadata.h"
39 /*#define LOGF_ENABLE*/
40 #include "logf.h"
41 #include "bitswap.h"
42 #include "structec.h"
43 #include "plugin.h" /* plugin_get_buffer() */
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 voicebuf-----------+-----------+------------
53 audio | voice | voice
54 |-----------|------------
55 | thumbnail | thumbnail
56 | |------------
57 | | filebuf
58 | |------------
59 | | audio
60 voicebufend----------+-----------+------------
62 SWCODEC allocates dedicated buffers (except voice and thumbnail are together
63 in the talkbuf), MASCODEC reuses audiobuf. */
66 /***************** Constants *****************/
68 #define QUEUE_SIZE 64 /* must be a power of two */
69 #define QUEUE_MASK (QUEUE_SIZE-1)
70 const char* const dir_thumbnail_name = "_dirname.talk";
71 const char* const file_thumbnail_ext = ".talk";
73 /***************** Functional Macros *****************/
75 #define QUEUE_LEVEL ((queue_write - queue_read) & QUEUE_MASK)
77 #define LOADED_MASK 0x80000000 /* MSB */
79 /* swcodec: cap p_thumnail to MAX_THUMNAIL_BUFSIZE since audio keeps playing
80 * while voice
81 * hwcodec: just use whatever is left in the audiobuffer, music
82 * playback is impossible => no cap */
83 #if CONFIG_CODEC == SWCODEC
84 #define MAX_THUMBNAIL_BUFSIZE 0x10000
85 #endif
87 /***************** Data types *****************/
89 struct clip_entry /* one entry of the index table */
91 int offset; /* offset from start of voicefile file */
92 int size; /* size of the clip */
95 struct voicefile /* file format of our voice file */
97 int version; /* version of the voicefile */
98 int target_id; /* the rockbox target the file was made for */
99 int table; /* offset to index table, (=header size) */
100 int id1_max; /* number of "normal" clips contained in above index */
101 int id2_max; /* number of "voice only" clips contained in above index */
102 struct clip_entry index[]; /* followed by the index tables */
103 /* and finally the mp3 clips, not visible here, bitswapped
104 for SH based players */
107 struct queue_entry /* one entry of the internal queue */
109 unsigned char* buf;
110 long len;
114 /***************** Globals *****************/
116 #if (CONFIG_CODEC == SWCODEC && MEMORYSIZE <= 2) || defined(ONDIO_SERIES)
117 /* On low memory swcodec targets the entire voice file wouldn't fit in memory
118 * together with codecs, so we load clips each time they are accessed.
119 * The Ondios have slow storage access and loading the entire voice file would
120 * take several seconds, so we use the same mechanism. */
121 #define TALK_PARTIAL_LOAD
122 #endif
124 #ifdef TALK_PARTIAL_LOAD
125 static unsigned char *clip_buffer;
126 static long max_clipsize; /* size of the biggest clip */
127 static long buffered_id[QUEUE_SIZE]; /* IDs of the talk clips */
128 static uint8_t clip_age[QUEUE_SIZE];
129 #if QUEUE_SIZE > 255
130 # error clip_age[] type too small
131 #endif
132 #endif
134 static char* voicebuf; /* root pointer to our buffer */
135 static unsigned char* p_thumbnail = NULL; /* buffer for thumbnails */
136 /* Multiple thumbnails can be loaded back-to-back in this buffer. */
137 static volatile int thumbnail_buf_used SHAREDBSS_ATTR; /* length of data in
138 thumbnail buffer */
139 static long size_for_thumbnail; /* total thumbnail buffer size */
140 static struct voicefile* p_voicefile; /* loaded voicefile */
141 static bool has_voicefile; /* a voicefile file is present */
142 static bool need_shutup; /* is there possibly any voice playing to be shutup */
143 static struct queue_entry queue[QUEUE_SIZE]; /* queue of scheduled clips */
144 static bool force_enqueue_next; /* enqueue next utterance even if enqueue is false */
145 static int queue_write; /* write index of queue, by application */
146 static int queue_read; /* read index of queue, by ISR context */
147 #if CONFIG_CODEC == SWCODEC
148 /* protects queue_read, queue_write and thumbnail_buf_used */
149 static struct mutex queue_mutex SHAREDBSS_ATTR;
150 #define talk_queue_lock() ({ mutex_lock(&queue_mutex); })
151 #define talk_queue_unlock() ({ mutex_unlock(&queue_mutex); })
152 #else
153 #define talk_queue_lock() ({ })
154 #define talk_queue_unlock() ({ })
155 #endif /* CONFIG_CODEC */
156 static int sent; /* how many bytes handed over to playback, owned by ISR */
157 static unsigned char curr_hd[3]; /* current frame header, for re-sync */
158 static int filehandle = -1; /* global, so we can keep the file open if needed */
159 static unsigned char* p_silence; /* VOICE_PAUSE clip, used for termination */
160 static long silence_len; /* length of the VOICE_PAUSE clip */
161 static unsigned char* p_lastclip; /* address of latest clip, for silence add */
162 static unsigned long voicefile_size = 0; /* size of the loaded voice file */
163 static unsigned char last_lang[MAX_FILENAME+1]; /* name of last used lang file (in talk_init) */
164 static bool talk_initialized; /* true if talk_init has been called */
165 static int talk_temp_disable_count; /* if positive, temporarily disable voice UI (not saved) */
168 /***************** Private implementation *****************/
170 static int open_voicefile(void)
172 char buf[64];
173 char* p_lang = "english"; /* default */
175 if ( global_settings.lang_file[0] &&
176 global_settings.lang_file[0] != 0xff )
177 { /* try to open the voice file of the selected language */
178 p_lang = (char *)global_settings.lang_file;
181 snprintf(buf, sizeof(buf), LANG_DIR "/%s.voice", p_lang);
183 return open(buf, O_RDONLY);
187 /* fetch a clip from the voice file */
188 static unsigned char* get_clip(long id, long* p_size)
190 long clipsize;
191 unsigned char* clipbuf;
193 if (id > VOICEONLY_DELIMITER)
194 { /* voice-only entries use the second part of the table */
195 id -= VOICEONLY_DELIMITER + 1;
196 if (id >= p_voicefile->id2_max)
197 return NULL; /* must be newer than we have */
198 id += p_voicefile->id1_max; /* table 2 is behind table 1 */
200 else
201 { /* normal use of the first table */
202 if (id >= p_voicefile->id1_max)
203 return NULL; /* must be newer than we have */
206 clipsize = p_voicefile->index[id].size;
207 if (clipsize == 0) /* clip not included in voicefile */
208 return NULL;
210 #ifndef TALK_PARTIAL_LOAD
211 clipbuf = (unsigned char *) p_voicefile + p_voicefile->index[id].offset;
212 #endif
214 #ifdef TALK_PARTIAL_LOAD
215 if (!(clipsize & LOADED_MASK))
216 { /* clip needs loading */
217 int idx = 0;
218 if (id == VOICE_PAUSE) {
219 idx = QUEUE_SIZE; /* we keep VOICE_PAUSE loaded */
220 } else {
221 int oldest = 0, i;
222 for(i=0; i<QUEUE_SIZE; i++) {
223 if (buffered_id[i] < 0) {
224 /* found a free entry, that means the buffer isn't
225 * full yet. */
226 idx = i;
227 break;
230 /* find the oldest clip */
231 if(clip_age[i] > oldest) {
232 idx = i;
233 oldest = clip_age[i];
236 /* increment age of each loaded clip */
237 clip_age[i]++;
239 clip_age[idx] = 0; /* reset clip's age */
241 clipbuf = clip_buffer + idx * max_clipsize;
243 lseek(filehandle, p_voicefile->index[id].offset, SEEK_SET);
244 if (read(filehandle, clipbuf, clipsize) != clipsize)
245 return NULL; /* read error */
247 p_voicefile->index[id].size |= LOADED_MASK; /* mark as loaded */
249 if (id != VOICE_PAUSE) {
250 if (buffered_id[idx] >= 0) {
251 /* mark previously loaded clip as unloaded */
252 p_voicefile->index[buffered_id[idx]].size &= ~LOADED_MASK;
254 buffered_id[idx] = id;
257 else
258 { /* clip is in memory already */
259 /* Find where it was loaded */
260 clipbuf = clip_buffer;
261 if (id == VOICE_PAUSE) {
262 clipbuf += QUEUE_SIZE * max_clipsize;
263 } else {
264 int idx;
265 for (idx=0; idx<QUEUE_SIZE; idx++)
266 if (buffered_id[idx] == id) {
267 clipbuf += idx * max_clipsize;
268 clip_age[idx] = 0; /* reset clip's age */
269 break;
272 clipsize &= ~LOADED_MASK; /* without the extra bit gives true size */
274 #endif /* TALK_PARTIAL_LOAD */
276 *p_size = clipsize;
277 return clipbuf;
281 /* load the voice file into the mp3 buffer */
282 static void load_voicefile(bool probe, char* buf, size_t bufsize)
284 union voicebuf {
285 unsigned char* buf;
286 struct voicefile* file;
288 union voicebuf voicebuf;
290 size_t load_size, alloc_size;
291 ssize_t got_size;
292 #ifdef ROCKBOX_LITTLE_ENDIAN
293 int i;
294 #endif
296 if (!probe)
297 filehandle = open_voicefile();
298 if (filehandle < 0) /* failed to open */
299 goto load_err;
301 voicebuf.buf = buf;
302 if (!voicebuf.buf)
303 goto load_err;
305 #ifdef TALK_PARTIAL_LOAD
306 /* load only the header for now */
307 load_size = sizeof(struct voicefile);
308 #else
309 /* load the entire file */
310 load_size = filesize(filehandle);
311 #endif
312 if (load_size > bufsize) /* won't fit? */
313 goto load_err;
315 got_size = read(filehandle, voicebuf.buf, load_size);
316 if (got_size != (ssize_t)load_size /* failure */)
317 goto load_err;
319 alloc_size = load_size;
321 #ifdef ROCKBOX_LITTLE_ENDIAN
322 logf("Byte swapping voice file");
323 structec_convert(voicebuf.buf, "lllll", 1, true);
324 #endif
326 /* format check */
327 if (voicebuf.file->table == sizeof(struct voicefile))
329 p_voicefile = voicebuf.file;
331 if (p_voicefile->version != VOICE_VERSION ||
332 p_voicefile->target_id != TARGET_ID)
334 logf("Incompatible voice file");
335 goto load_err;
338 else
339 goto load_err;
341 #ifdef TALK_PARTIAL_LOAD
342 /* load the index table, now that we know its size from the header */
343 load_size = (p_voicefile->id1_max + p_voicefile->id2_max)
344 * sizeof(struct clip_entry);
346 if (load_size > bufsize) /* won't fit? */
347 goto load_err;
349 got_size = read(filehandle, &p_voicefile->index[0], load_size);
350 if (got_size != (ssize_t)load_size) /* read error */
351 goto load_err;
353 alloc_size += load_size;
354 #else
355 close(filehandle);
356 filehandle = -1;
357 #endif /* TALK_PARTIAL_LOAD */
359 #ifdef ROCKBOX_LITTLE_ENDIAN
360 for (i = 0; i < p_voicefile->id1_max + p_voicefile->id2_max; i++)
361 structec_convert(&p_voicefile->index[i], "ll", 1, true);
362 #endif
364 #ifdef TALK_PARTIAL_LOAD
365 clip_buffer = (unsigned char *) p_voicefile + p_voicefile->table;
366 unsigned clips = p_voicefile->id1_max + p_voicefile->id2_max;
367 clip_buffer += clips * sizeof(struct clip_entry); /* skip index */
368 #endif
369 if (!probe) {
370 /* make sure to have the silence clip, if available */
371 p_silence = get_clip(VOICE_PAUSE, &silence_len);
374 #ifdef TALK_PARTIAL_LOAD
375 alloc_size += silence_len + QUEUE_SIZE;
376 #endif
378 if (alloc_size > bufsize)
379 goto load_err;
381 /* now move p_thumbnail behind the voice clip buffer */
382 p_thumbnail = voicebuf.buf + alloc_size;
383 p_thumbnail += (long)p_thumbnail % 2; /* 16-bit align */
384 size_for_thumbnail = voicebuf.buf + bufsize - p_thumbnail;
385 #if CONFIG_CODEC == SWCODEC
386 size_for_thumbnail = MIN(size_for_thumbnail, MAX_THUMBNAIL_BUFSIZE);
387 #endif
388 if (size_for_thumbnail <= 0)
389 p_thumbnail = NULL;
391 return;
392 load_err:
393 p_voicefile = NULL;
394 has_voicefile = false; /* don't try again */
395 if (filehandle >= 0)
397 close(filehandle);
398 filehandle = -1;
400 return;
404 /* called in ISR context (on HWCODEC) if mp3 data got consumed */
405 static void mp3_callback(const void** start, size_t* size)
407 queue[queue_read].len -= sent; /* we completed this */
408 queue[queue_read].buf += sent;
410 if (queue[queue_read].len > 0) /* current clip not finished? */
411 { /* feed the next 64K-1 chunk */
412 #if CONFIG_CODEC != SWCODEC
413 sent = MIN(queue[queue_read].len, 0xFFFF);
414 #else
415 sent = queue[queue_read].len;
416 #endif
417 *start = queue[queue_read].buf;
418 *size = sent;
419 return;
421 talk_queue_lock();
422 if(p_thumbnail
423 && queue[queue_read].buf == p_thumbnail +thumbnail_buf_used)
424 thumbnail_buf_used = 0;
425 if (sent > 0) /* go to next entry */
427 queue_read = (queue_read + 1) & QUEUE_MASK;
430 re_check:
432 if (QUEUE_LEVEL != 0) /* queue is not empty? */
433 { /* start next clip */
434 #if CONFIG_CODEC != SWCODEC
435 sent = MIN(queue[queue_read].len, 0xFFFF);
436 #else
437 sent = queue[queue_read].len;
438 #endif
439 *start = p_lastclip = queue[queue_read].buf;
440 *size = sent;
441 curr_hd[0] = p_lastclip[1];
442 curr_hd[1] = p_lastclip[2];
443 curr_hd[2] = p_lastclip[3];
445 else if (p_silence != NULL /* silence clip available */
446 && p_lastclip != p_silence /* previous clip wasn't silence */
447 && !(p_lastclip >= p_thumbnail /* ..or thumbnail */
448 && p_lastclip < p_thumbnail +size_for_thumbnail))
449 { /* add silence clip when queue runs empty playing a voice clip */
450 queue[queue_write].buf = p_silence;
451 queue[queue_write].len = silence_len;
452 queue_write = (queue_write + 1) & QUEUE_MASK;
454 goto re_check;
456 else
458 *size = 0; /* end of data */
460 talk_queue_unlock();
463 /***************** Public routines *****************/
465 /* stop the playback and the pending clips */
466 void talk_force_shutup(void)
468 /* Most of this is MAS only */
469 #if CONFIG_CODEC != SWCODEC
470 #ifdef SIMULATOR
471 return;
472 #endif
473 unsigned char* pos;
474 unsigned char* search;
475 unsigned char* end;
476 if (QUEUE_LEVEL == 0) /* has ended anyway */
477 return;
479 #if CONFIG_CPU == SH7034
480 CHCR3 &= ~0x0001; /* disable the DMA (and therefore the interrupt also) */
481 #endif /* CONFIG_CPU == SH7034 */
482 /* search next frame boundary and continue up to there */
483 pos = search = mp3_get_pos();
484 end = queue[queue_read].buf + queue[queue_read].len;
486 if (pos >= queue[queue_read].buf
487 && pos <= end) /* really our clip? */
488 { /* (for strange reasons this isn't nesessarily the case) */
489 /* find the next frame boundary */
490 while (search < end) /* search the remaining data */
492 if (*search++ != 0xFF) /* quick search for frame sync byte */
493 continue; /* (this does the majority of the job) */
495 /* look at the (bitswapped) rest of header candidate */
496 if (search[0] == curr_hd[0] /* do the quicker checks first */
497 && search[2] == curr_hd[2]
498 && (search[1] & 0x30) == (curr_hd[1] & 0x30)) /* sample rate */
500 search--; /* back to the sync byte */
501 break; /* From looking at it, this is our header. */
505 if (search-pos)
506 { /* play old data until the frame end, to keep the MAS in sync */
507 sent = search-pos;
509 queue_write = (queue_read + 1) & QUEUE_MASK; /* will be empty after next callback */
510 queue[queue_read].len = sent; /* current one ends after this */
512 #if CONFIG_CPU == SH7034
513 DTCR3 = sent; /* let the DMA finish this frame */
514 CHCR3 |= 0x0001; /* re-enable DMA */
515 #endif /* CONFIG_CPU == SH7034 */
516 thumbnail_buf_used = 0;
517 return;
520 #endif /* CONFIG_CODEC != SWCODEC */
522 /* Either SWCODEC, or MAS had nothing to do (was frame boundary or not our clip) */
523 mp3_play_stop();
524 talk_queue_lock();
525 queue_write = queue_read = 0; /* reset the queue */
526 thumbnail_buf_used = 0;
527 talk_queue_unlock();
528 need_shutup = false;
531 /* Shutup the voice, except if force_enqueue_next is set. */
532 void talk_shutup(void)
534 if (need_shutup && !force_enqueue_next)
535 talk_force_shutup();
538 /* schedule a clip, at the end or discard the existing queue */
539 static void queue_clip(unsigned char* buf, long size, bool enqueue)
541 int queue_level;
543 if (!enqueue)
544 talk_shutup(); /* cut off all the pending stuff */
545 /* Something is being enqueued, force_enqueue_next override is no
546 longer in effect. */
547 force_enqueue_next = false;
549 if (!size)
550 return; /* safety check */
551 #if CONFIG_CPU == SH7034
552 /* disable the DMA temporarily, to be safe of race condition */
553 CHCR3 &= ~0x0001;
554 #endif
555 talk_queue_lock();
556 queue_level = QUEUE_LEVEL; /* check old level */
558 if (queue_level < QUEUE_SIZE - 1) /* space left? */
560 queue[queue_write].buf = buf; /* populate an entry */
561 queue[queue_write].len = size;
562 queue_write = (queue_write + 1) & QUEUE_MASK;
564 talk_queue_unlock();
566 if (queue_level == 0)
567 { /* queue was empty, we have to do the initial start */
568 p_lastclip = buf;
569 #if CONFIG_CODEC != SWCODEC
570 sent = MIN(size, 0xFFFF); /* DMA can do no more */
571 #else
572 sent = size;
573 #endif
574 mp3_play_data(buf, sent, mp3_callback);
575 curr_hd[0] = buf[1];
576 curr_hd[1] = buf[2];
577 curr_hd[2] = buf[3];
578 mp3_play_pause(true); /* kickoff audio */
580 else
582 #if CONFIG_CPU == SH7034
583 CHCR3 |= 0x0001; /* re-enable DMA */
584 #endif
587 need_shutup = true;
589 return;
593 static void alloc_thumbnail_buf(void)
595 /* use the audio buffer now, need to release before loading a voice */
596 p_thumbnail = voicebuf;
597 #if CONFIG_CODEC == SWCODEC
598 size_for_thumbnail = MAX_THUMBNAIL_BUFSIZE;
599 #endif
600 thumbnail_buf_used = 0;
603 /* common code for talk_init() and talk_buffer_steal() */
604 static void reset_state(void)
606 queue_write = queue_read = 0; /* reset the queue */
607 p_voicefile = NULL; /* indicate no voicefile (trashed) */
608 p_thumbnail = NULL; /* no thumbnails either */
610 #ifdef TALK_PARTIAL_LOAD
611 int i;
612 for(i=0; i<QUEUE_SIZE; i++)
613 buffered_id[i] = -1;
614 #endif
616 p_silence = NULL; /* pause clip not accessible */
617 voicebuf = NULL;
621 /***************** Public implementation *****************/
623 void talk_init(void)
625 talk_temp_disable_count = 0;
626 if (talk_initialized && !strcasecmp(last_lang, global_settings.lang_file))
628 /* not a new file, nothing to do */
629 return;
632 #if defined(TALK_PROGRESSIVE_LOAD) || defined(TALK_PARTIAL_LOAD)
633 if (filehandle >= 0)
635 close(filehandle);
636 filehandle = -1;
638 #endif
640 #if CONFIG_CODEC == SWCODEC
641 if(!talk_initialized)
642 mutex_init(&queue_mutex);
643 #endif /* CONFIG_CODEC == SWCODEC */
645 talk_initialized = true;
646 strlcpy((char *)last_lang, (char *)global_settings.lang_file,
647 MAX_FILENAME);
649 filehandle = open_voicefile();
650 if (filehandle < 0) {
651 has_voicefile = false;
652 voicefile_size = 0;
653 return;
656 voicefile_size = filesize(filehandle);
658 audio_get_buffer(false, NULL); /* Must tell audio to reinitialize */
659 reset_state(); /* use this for most of our inits */
661 #ifdef TALK_PARTIAL_LOAD
662 size_t bufsize;
663 char* buf = plugin_get_buffer(&bufsize);
664 /* we won't load the full file, we only need the index */
665 load_voicefile(true, buf, bufsize);
666 if (!p_voicefile)
667 return;
669 unsigned clips = p_voicefile->id1_max + p_voicefile->id2_max;
670 unsigned i;
671 int silence_size = 0;
673 for(i=0; i<clips; i++) {
674 int size = p_voicefile->index[i].size;
675 if (size > max_clipsize)
676 max_clipsize = size;
677 if (i == VOICE_PAUSE)
678 silence_size = size;
681 voicefile_size = p_voicefile->table + clips * sizeof(struct clip_entry);
682 voicefile_size += max_clipsize * QUEUE_SIZE + silence_size;
683 p_voicefile = NULL; /* Don't pretend we can load talk clips just yet */
684 #endif
687 /* test if we can open and if it fits in the audiobuffer */
688 size_t audiobufsz = audio_buffer_available();
689 if (voicefile_size <= audiobufsz) {
690 has_voicefile = true;
691 } else {
692 has_voicefile = false;
693 voicefile_size = 0;
696 alloc_thumbnail_buf();
697 close(filehandle); /* close again, this was just to detect presence */
698 filehandle = -1;
701 #if CONFIG_CODEC == SWCODEC
702 /* return if a voice codec is required or not */
703 bool talk_voice_required(void)
705 return (voicefile_size != 0) /* Voice file is available */
706 || (global_settings.talk_dir_clip) /* Thumbnail clips are required */
707 || (global_settings.talk_file_clip);
709 #endif
711 /* return size of voice file */
712 static int talk_get_buffer(void)
714 #if CONFIG_CODEC == SWCODEC
715 return voicefile_size + MAX_THUMBNAIL_BUFSIZE;
716 #else
717 return audio_buffer_available();
718 #endif
721 /* Sets the buffer for the voicefile and returns how many bytes of this
722 * buffer we will use for the voicefile */
723 size_t talkbuf_init(char *bufstart)
725 bool changed = voicebuf != bufstart;
727 if (changed) /* must reload voice file */
728 reset_state();
729 if (bufstart)
730 voicebuf = bufstart;
732 return talk_get_buffer();
735 /* somebody else claims the mp3 buffer, e.g. for regular play/record */
736 void talk_buffer_steal(void)
738 #if CONFIG_CODEC != SWCODEC
739 mp3_play_stop();
740 #endif
741 #if defined(TALK_PROGRESSIVE_LOAD) || defined(TALK_PARTIAL_LOAD)
742 if (filehandle >= 0)
744 close(filehandle);
745 filehandle = -1;
747 #endif
748 reset_state();
752 /* play a voice ID from voicefile */
753 int talk_id(int32_t id, bool enqueue)
755 long clipsize;
756 int temp = talk_get_buffer();
757 unsigned char* clipbuf;
758 int32_t unit;
759 int decimals;
761 if (talk_temp_disable_count > 0)
762 return -1; /* talking has been disabled */
763 #if CONFIG_CODEC != SWCODEC
764 if (audio_status()) /* busy, buffer in use */
765 return -1;
766 #endif
768 /* try to get audio buffer until talkbuf_init() is called */
769 if (!voicebuf)
770 voicebuf = audio_get_buffer(true, (size_t*)&temp);
772 if (p_voicefile == NULL && has_voicefile)
773 load_voicefile(false, voicebuf, MIN(talk_get_buffer(),temp)); /* reload needed */
775 if (p_voicefile == NULL) /* still no voices? */
776 return -1;
778 if (id == -1) /* -1 is an indication for silence */
779 return -1;
781 decimals = (((uint32_t)id) >> DECIMAL_SHIFT) & 0x7;
783 /* check if this is a special ID, with a value */
784 unit = ((uint32_t)id) >> UNIT_SHIFT;
785 if (unit || decimals)
786 { /* sign-extend the value */
787 id = (uint32_t)id << (32-DECIMAL_SHIFT);
788 id >>= (32-DECIMAL_SHIFT);
790 talk_value_decimal(id, unit, decimals, enqueue); /* speak it */
791 return 0; /* and stop, end of special case */
794 clipbuf = get_clip(id, &clipsize);
795 if (clipbuf == NULL)
796 return -1; /* not present */
798 #ifdef LOGF_ENABLE
799 if (id > VOICEONLY_DELIMITER)
800 logf("\ntalk_id: Say voice clip 0x%x\n", id);
801 else
802 logf("\ntalk_id: Say '%s'\n", str(id));
803 #endif
805 queue_clip(clipbuf, clipsize, enqueue);
807 return 0;
809 /* Speaks zero or more IDs (from an array). */
810 int talk_idarray(const long *ids, bool enqueue)
812 int r;
813 if(!ids)
814 return 0;
815 while(*ids != TALK_FINAL_ID)
817 if((r = talk_id(*ids++, enqueue)) <0)
818 return r;
819 enqueue = true;
821 return 0;
824 /* Make sure the current utterance is not interrupted by the next one. */
825 void talk_force_enqueue_next(void)
827 force_enqueue_next = true;
830 /* play a thumbnail from file */
831 /* Returns size of spoken thumbnail, so >0 means something is spoken,
832 <=0 means something went wrong. */
833 static int _talk_file(const char* filename,
834 const long *prefix_ids, bool enqueue)
836 int fd;
837 int size;
838 int thumb_used;
839 #if CONFIG_CODEC != SWCODEC
840 struct mp3entry info;
841 #endif
843 if (talk_temp_disable_count > 0)
844 return -1; /* talking has been disabled */
845 #if CONFIG_CODEC != SWCODEC
846 if (audio_status()) /* busy, buffer in use */
847 return -1;
848 #endif
850 if (p_thumbnail == NULL || size_for_thumbnail <= 0)
851 alloc_thumbnail_buf();
853 #if CONFIG_CODEC != SWCODEC
854 if(mp3info(&info, filename)) /* use this to find real start */
856 return 0; /* failed to open, or invalid */
858 #endif
860 if (!enqueue)
861 /* shutup now to free the thumbnail buffer */
862 talk_shutup();
864 fd = open(filename, O_RDONLY);
865 if (fd < 0) /* failed to open */
867 return 0;
870 thumb_used = thumbnail_buf_used;
871 if(filesize(fd) > size_for_thumbnail -thumb_used)
872 { /* Don't play truncated clips */
873 close(fd);
874 return 0;
877 #if CONFIG_CODEC != SWCODEC
878 lseek(fd, info.first_frame_offset, SEEK_SET); /* behind ID data */
879 #endif
881 size = read(fd, p_thumbnail +thumb_used,
882 size_for_thumbnail -thumb_used);
883 close(fd);
885 /* ToDo: find audio, skip ID headers and trailers */
887 if (size > 0) /* Don't play missing clips */
889 #if CONFIG_CODEC != SWCODEC && !defined(SIMULATOR)
890 bitswap(p_thumbnail, size);
891 #endif
892 if(prefix_ids)
893 /* prefix thumbnail by speaking these ids, but only now
894 that we know there's actually a thumbnail to be
895 spoken. */
896 talk_idarray(prefix_ids, true);
897 talk_queue_lock();
898 thumbnail_buf_used = thumb_used +size;
899 talk_queue_unlock();
900 queue_clip(p_thumbnail +thumb_used, size, true);
903 return size;
906 int talk_file(const char *root, const char *dir, const char *file,
907 const char *ext, const long *prefix_ids, bool enqueue)
908 /* Play a thumbnail file */
910 char buf[MAX_PATH];
911 /* Does root end with a slash */
912 char *slash = (root && root[0]
913 && root[strlen(root)-1] != '/') ? "/" : "";
914 snprintf(buf, MAX_PATH, "%s%s%s%s%s%s",
915 root ? root : "", slash,
916 dir ? dir : "", dir ? "/" : "",
917 file ? file : "",
918 ext ? ext : "");
919 return _talk_file(buf, prefix_ids, enqueue);
922 static int talk_spell_basename(const char *path,
923 const long *prefix_ids, bool enqueue)
925 if(prefix_ids)
927 talk_idarray(prefix_ids, enqueue);
928 enqueue = true;
930 char buf[MAX_PATH];
931 /* Spell only the path component after the last slash */
932 strlcpy(buf, path, sizeof(buf));
933 if(strlen(buf) >1 && buf[strlen(buf)-1] == '/')
934 /* strip trailing slash */
935 buf[strlen(buf)-1] = '\0';
936 char *ptr = strrchr(buf, '/');
937 if(ptr && strlen(buf) >1)
938 ++ptr;
939 else ptr = buf;
940 return talk_spell(ptr, enqueue);
943 /* Play a file's .talk thumbnail, fallback to spelling the filename, or
944 go straight to spelling depending on settings. */
945 int talk_file_or_spell(const char *dirname, const char *filename,
946 const long *prefix_ids, bool enqueue)
948 if (global_settings.talk_file_clip)
949 { /* .talk clips enabled */
950 if(talk_file(dirname, NULL, filename, file_thumbnail_ext,
951 prefix_ids, enqueue) >0)
952 return 0;
954 if (global_settings.talk_file == 2)
955 /* Either .talk clips are disabled, or as a fallback */
956 return talk_spell_basename(filename, prefix_ids, enqueue);
957 return 0;
960 #if CONFIG_CODEC == SWCODEC
961 /* Play a directory's .talk thumbnail, fallback to spelling the filename, or
962 go straight to spelling depending on settings. */
963 int talk_dir_or_spell(const char* dirname,
964 const long *prefix_ids, bool enqueue)
966 if (global_settings.talk_dir_clip)
967 { /* .talk clips enabled */
968 if(talk_file(dirname, NULL, dir_thumbnail_name, NULL,
969 prefix_ids, enqueue) >0)
970 return 0;
972 if (global_settings.talk_dir == 2)
973 /* Either .talk clips disabled or as a fallback */
974 return talk_spell_basename(dirname, prefix_ids, enqueue);
975 return 0;
977 #endif
979 /* say a numeric value, this word ordering works for english,
980 but not necessarily for other languages (e.g. german) */
981 int talk_number(long n, bool enqueue)
983 int level = 2; /* mille count */
984 long mil = 1000000000; /* highest possible "-illion" */
986 if (talk_temp_disable_count > 0)
987 return -1; /* talking has been disabled */
988 #if CONFIG_CODEC != SWCODEC
989 if (audio_status()) /* busy, buffer in use */
990 return -1;
991 #endif
993 if (!enqueue)
994 talk_shutup(); /* cut off all the pending stuff */
996 if (n==0)
997 { /* special case */
998 talk_id(VOICE_ZERO, true);
999 return 0;
1002 if (n<0)
1004 talk_id(VOICE_MINUS, true);
1005 n = -n;
1008 while (n)
1010 int segment = n / mil; /* extract in groups of 3 digits */
1011 n -= segment * mil; /* remove the used digits from number */
1012 mil /= 1000; /* digit place for next round */
1014 if (segment)
1016 int hundreds = segment / 100;
1017 int ones = segment % 100;
1019 if (hundreds)
1021 talk_id(VOICE_ZERO + hundreds, true);
1022 talk_id(VOICE_HUNDRED, true);
1025 /* combination indexing */
1026 if (ones > 20)
1028 int tens = ones/10 + 18;
1029 talk_id(VOICE_ZERO + tens, true);
1030 ones %= 10;
1033 /* direct indexing */
1034 if (ones)
1035 talk_id(VOICE_ZERO + ones, true);
1037 /* add billion, million, thousand */
1038 if (mil)
1039 talk_id(VOICE_THOUSAND + level, true);
1041 level--;
1044 return 0;
1047 /* Say time duration/interval. Input is time in seconds,
1048 say hours,minutes,seconds. */
1049 static int talk_time_unit(long secs, bool enqueue)
1051 int hours, mins;
1052 if (!enqueue)
1053 talk_shutup();
1054 if((hours = secs/3600)) {
1055 secs %= 3600;
1056 talk_value(hours, UNIT_HOUR, true);
1058 if((mins = secs/60)) {
1059 secs %= 60;
1060 talk_value(mins, UNIT_MIN, true);
1062 if((secs) || (!hours && !mins))
1063 talk_value(secs, UNIT_SEC, true);
1064 else if(!hours && secs)
1065 talk_number(secs, true);
1066 return 0;
1069 void talk_fractional(char *tbuf, int value, int unit)
1071 int i;
1072 /* strip trailing zeros from the fraction */
1073 for (i = strlen(tbuf) - 1; (i >= 0) && (tbuf[i] == '0'); i--)
1074 tbuf[i] = '\0';
1076 talk_number(value, true);
1077 if (tbuf[0] != 0)
1079 talk_id(LANG_POINT, true);
1080 talk_spell(tbuf, true);
1082 talk_id(unit, true);
1085 int talk_value(long n, int unit, bool enqueue)
1087 return talk_value_decimal(n, unit, 0, enqueue);
1090 /* singular/plural aware saying of a value */
1091 int talk_value_decimal(long n, int unit, int decimals, bool enqueue)
1093 int unit_id;
1094 static const int unit_voiced[] =
1095 { /* lookup table for the voice ID of the units */
1096 [0 ... UNIT_LAST-1] = -1, /* regular ID, int, signed */
1097 [UNIT_MS]
1098 = VOICE_MILLISECONDS, /* here come the "real" units */
1099 [UNIT_SEC]
1100 = VOICE_SECONDS,
1101 [UNIT_MIN]
1102 = VOICE_MINUTES,
1103 [UNIT_HOUR]
1104 = VOICE_HOURS,
1105 [UNIT_KHZ]
1106 = VOICE_KHZ,
1107 [UNIT_DB]
1108 = VOICE_DB,
1109 [UNIT_PERCENT]
1110 = VOICE_PERCENT,
1111 [UNIT_MAH]
1112 = VOICE_MILLIAMPHOURS,
1113 [UNIT_PIXEL]
1114 = VOICE_PIXEL,
1115 [UNIT_PER_SEC]
1116 = VOICE_PER_SEC,
1117 [UNIT_HERTZ]
1118 = VOICE_HERTZ,
1119 [UNIT_MB]
1120 = LANG_MEGABYTE,
1121 [UNIT_KBIT]
1122 = VOICE_KBIT_PER_SEC,
1123 [UNIT_PM_TICK]
1124 = VOICE_PM_UNITS_PER_TICK,
1127 static const int pow10[] = { /* 10^0 - 10^7 */
1128 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000
1131 char tbuf[8];
1132 char fmt[] = "%0nd";
1134 if (talk_temp_disable_count > 0)
1135 return -1; /* talking has been disabled */
1136 #if CONFIG_CODEC != SWCODEC
1137 if (audio_status()) /* busy, buffer in use */
1138 return -1;
1139 #endif
1141 /* special case for time duration */
1142 if (unit == UNIT_TIME)
1143 return talk_time_unit(n, enqueue);
1145 if (unit < 0 || unit >= UNIT_LAST)
1146 unit_id = -1;
1147 else
1148 unit_id = unit_voiced[unit];
1150 if ((n==1 || n==-1) /* singular? */
1151 && unit_id >= VOICE_SECONDS && unit_id <= VOICE_HOURS)
1153 unit_id--; /* use the singular for those units which have */
1156 /* special case with a "plus" before */
1157 if (n > 0 && (unit == UNIT_SIGNED || unit == UNIT_DB))
1159 talk_id(VOICE_PLUS, enqueue);
1160 enqueue = true;
1163 if (decimals)
1165 /* needed for the "-0.5" corner case */
1166 if (n < 0)
1168 talk_id(VOICE_MINUS, enqueue);
1169 n = -n;
1172 fmt[2] = '0' + decimals;
1174 snprintf(tbuf, sizeof(tbuf), fmt, n % pow10[decimals]);
1175 talk_fractional(tbuf, n / pow10[decimals], unit_id);
1177 return 0;
1180 talk_number(n, enqueue); /* say the number */
1181 talk_id(unit_id, true); /* say the unit, if any */
1183 return 0;
1186 /* spell a string */
1187 int talk_spell(const char* spell, bool enqueue)
1189 char c; /* currently processed char */
1191 if (talk_temp_disable_count > 0)
1192 return -1; /* talking has been disabled */
1193 #if CONFIG_CODEC != SWCODEC
1194 if (audio_status()) /* busy, buffer in use */
1195 return -1;
1196 #endif
1198 if (!enqueue)
1199 talk_shutup(); /* cut off all the pending stuff */
1201 while ((c = *spell++) != '\0')
1203 /* if this grows into too many cases, I should use a table */
1204 if (c >= 'A' && c <= 'Z')
1205 talk_id(VOICE_CHAR_A + c - 'A', true);
1206 else if (c >= 'a' && c <= 'z')
1207 talk_id(VOICE_CHAR_A + c - 'a', true);
1208 else if (c >= '0' && c <= '9')
1209 talk_id(VOICE_ZERO + c - '0', true);
1210 else if (c == '-')
1211 talk_id(VOICE_MINUS, true);
1212 else if (c == '+')
1213 talk_id(VOICE_PLUS, true);
1214 else if (c == '.')
1215 talk_id(VOICE_DOT, true);
1216 else if (c == ' ')
1217 talk_id(VOICE_PAUSE, true);
1218 else if (c == '/')
1219 talk_id(VOICE_CHAR_SLASH, true);
1222 return 0;
1225 void talk_disable(bool disable)
1227 if (disable)
1228 talk_temp_disable_count++;
1229 else
1230 talk_temp_disable_count--;
1233 void talk_setting(const void *global_settings_variable)
1235 const struct settings_list *setting;
1236 if (!global_settings.talk_menu)
1237 return;
1238 setting = find_setting(global_settings_variable, NULL);
1239 if (setting == NULL)
1240 return;
1241 if (setting->lang_id)
1242 talk_id(setting->lang_id,false);
1246 #if CONFIG_RTC
1247 void talk_date(const struct tm *tm, bool enqueue)
1249 talk_id(LANG_MONTH_JANUARY + tm->tm_mon, enqueue);
1250 talk_number(tm->tm_mday, true);
1251 talk_number(1900 + tm->tm_year, true);
1254 void talk_time(const struct tm *tm, bool enqueue)
1256 if (global_settings.timeformat == 1)
1258 /* Voice the hour */
1259 long am_pm_id = VOICE_AM;
1260 int hour = tm->tm_hour;
1261 if (hour >= 12)
1263 am_pm_id = VOICE_PM;
1264 hour -= 12;
1266 if (hour == 0)
1267 hour = 12;
1268 talk_number(hour, enqueue);
1270 /* Voice the minutes */
1271 if (tm->tm_min == 0)
1273 /* Say o'clock if the minute is 0. */
1274 talk_id(VOICE_OCLOCK, true);
1276 else
1278 /* Pronounce the leading 0 */
1279 if(tm->tm_min < 10)
1280 talk_id(VOICE_OH, true);
1281 talk_number(tm->tm_min, true);
1283 talk_id(am_pm_id, true);
1285 else
1287 /* Voice the time in 24 hour format */
1288 talk_number(tm->tm_hour, enqueue);
1289 if (tm->tm_min == 0)
1291 talk_id(VOICE_HUNDRED, true);
1292 talk_id(VOICE_HOUR, true);
1294 else
1296 /* Pronounce the leading 0 */
1297 if(tm->tm_min < 10)
1298 talk_id(VOICE_OH, true);
1299 talk_number(tm->tm_min, true);
1304 #endif /* CONFIG_RTC */