GSoC/Buflib: Add buflib memory alocator to the core.
[kugel-rb.git] / apps / talk.c
blob30d95efc7b45921bfdbda185cff0a25f462b29e7
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 "core_alloc.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 voicebuf-----------+-----------+------------
53 audio | voice | thumbnail
54 |-----------|------------
55 | thumbnail | voice
56 | |------------
57 | | filebuf
58 | |------------
59 | | audio
60 voicebufend----------+-----------+------------
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 && MEMORYSIZE <= 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 char* voicebuf; /* root pointer to our buffer */
132 static unsigned char* p_thumbnail = NULL; /* buffer for thumbnails */
133 /* Multiple thumbnails can be loaded back-to-back in this buffer. */
134 static volatile int thumbnail_buf_used SHAREDBSS_ATTR; /* length of data in
135 thumbnail buffer */
136 static long size_for_thumbnail; /* total thumbnail buffer size */
137 static struct voicefile* p_voicefile; /* loaded voicefile */
138 static bool has_voicefile; /* a voicefile file is present */
139 static bool need_shutup; /* is there possibly any voice playing to be shutup */
140 static struct queue_entry queue[QUEUE_SIZE]; /* queue of scheduled clips */
141 static bool force_enqueue_next; /* enqueue next utterance even if enqueue is false */
142 static int queue_write; /* write index of queue, by application */
143 static int queue_read; /* read index of queue, by ISR context */
144 #if CONFIG_CODEC == SWCODEC
145 /* protects queue_read, queue_write and thumbnail_buf_used */
146 static struct mutex queue_mutex SHAREDBSS_ATTR;
147 #define talk_queue_lock() ({ mutex_lock(&queue_mutex); })
148 #define talk_queue_unlock() ({ mutex_unlock(&queue_mutex); })
149 #else
150 #define talk_queue_lock() ({ })
151 #define talk_queue_unlock() ({ })
152 #endif /* CONFIG_CODEC */
153 static int sent; /* how many bytes handed over to playback, owned by ISR */
154 static unsigned char curr_hd[3]; /* current frame header, for re-sync */
155 static int filehandle = -1; /* global, so we can keep the file open if needed */
156 static unsigned char* p_silence; /* VOICE_PAUSE clip, used for termination */
157 static long silence_len; /* length of the VOICE_PAUSE clip */
158 static unsigned char* p_lastclip; /* address of latest clip, for silence add */
159 static unsigned long voicefile_size = 0; /* size of the loaded voice file */
160 static unsigned char last_lang[MAX_FILENAME+1]; /* name of last used lang file (in talk_init) */
161 static bool talk_initialized; /* true if talk_init has been called */
162 static int talk_temp_disable_count; /* if positive, temporarily disable voice UI (not saved) */
165 /***************** Private implementation *****************/
167 static int open_voicefile(void)
169 char buf[64];
170 char* p_lang = "english"; /* default */
172 if ( global_settings.lang_file[0] &&
173 global_settings.lang_file[0] != 0xff )
174 { /* try to open the voice file of the selected language */
175 p_lang = (char *)global_settings.lang_file;
178 snprintf(buf, sizeof(buf), LANG_DIR "/%s.voice", p_lang);
180 return open(buf, O_RDONLY);
184 /* fetch a clip from the voice file */
185 static unsigned char* get_clip(long id, long* p_size)
187 long clipsize;
188 unsigned char* clipbuf;
190 if (id > VOICEONLY_DELIMITER)
191 { /* voice-only entries use the second part of the table */
192 id -= VOICEONLY_DELIMITER + 1;
193 if (id >= p_voicefile->id2_max)
194 return NULL; /* must be newer than we have */
195 id += p_voicefile->id1_max; /* table 2 is behind table 1 */
197 else
198 { /* normal use of the first table */
199 if (id >= p_voicefile->id1_max)
200 return NULL; /* must be newer than we have */
203 clipsize = p_voicefile->index[id].size;
204 if (clipsize == 0) /* clip not included in voicefile */
205 return NULL;
207 #ifndef TALK_PARTIAL_LOAD
208 clipbuf = (unsigned char *) p_voicefile + p_voicefile->index[id].offset;
209 #endif
211 #if defined(TALK_PROGRESSIVE_LOAD) || defined(TALK_PARTIAL_LOAD)
212 if (!(clipsize & LOADED_MASK))
213 { /* clip needs loading */
214 #ifdef TALK_PARTIAL_LOAD
215 int idx = 0;
216 if (id == VOICE_PAUSE) {
217 idx = QUEUE_SIZE; /* we keep VOICE_PAUSE loaded */
218 } else {
219 int oldest = 0, i;
220 for(i=0; i<QUEUE_SIZE; i++) {
221 if (buffered_id[i] < 0) {
222 /* found a free entry, that means the buffer isn't
223 * full yet. */
224 idx = i;
225 break;
228 /* find the oldest clip */
229 if(clip_age[i] > oldest) {
230 idx = i;
231 oldest = clip_age[i];
234 /* increment age of each loaded clip */
235 clip_age[i]++;
237 clip_age[idx] = 0; /* reset clip's age */
239 clipbuf = clip_buffer + idx * max_clipsize;
240 #endif
242 lseek(filehandle, p_voicefile->index[id].offset, SEEK_SET);
243 if (read(filehandle, clipbuf, clipsize) != clipsize)
244 return NULL; /* read error */
246 p_voicefile->index[id].size |= LOADED_MASK; /* mark as loaded */
248 #ifdef TALK_PARTIAL_LOAD
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;
256 #endif
258 else
259 { /* clip is in memory already */
260 #ifdef TALK_PARTIAL_LOAD
261 /* Find where it was loaded */
262 clipbuf = clip_buffer;
263 if (id == VOICE_PAUSE) {
264 clipbuf += QUEUE_SIZE * max_clipsize;
265 } else {
266 int idx;
267 for (idx=0; idx<QUEUE_SIZE; idx++)
268 if (buffered_id[idx] == id) {
269 clipbuf += idx * max_clipsize;
270 clip_age[idx] = 0; /* reset clip's age */
271 break;
274 #endif
275 clipsize &= ~LOADED_MASK; /* without the extra bit gives true size */
277 #endif /* defined(TALK_PROGRESSIVE_LOAD) || defined(TALK_PARTIAL_LOAD) */
279 *p_size = clipsize;
280 return clipbuf;
284 /* load the voice file into the mp3 buffer */
285 static void load_voicefile(bool probe, char* buf, size_t bufsize)
287 union voicebuf {
288 unsigned char* buf;
289 struct voicefile* file;
291 union voicebuf voicebuf;
293 int load_size, alloc_size;
294 int got_size;
295 #ifndef TALK_PARTIAL_LOAD
296 size_t file_size;
297 #endif
298 #ifdef ROCKBOX_LITTLE_ENDIAN
299 int i;
300 #endif
302 if (!probe)
303 filehandle = open_voicefile();
304 if (filehandle < 0) /* failed to open */
305 goto load_err;
307 voicebuf.buf = buf;
308 if (!voicebuf.buf)
309 goto load_err;
311 #ifndef TALK_PARTIAL_LOAD
312 file_size = filesize(filehandle);
313 if (file_size > bufsize) /* won't fit? */
314 goto load_err;
315 #endif
317 #if defined(TALK_PROGRESSIVE_LOAD) || defined(TALK_PARTIAL_LOAD)
318 /* load only the header for now */
319 load_size = sizeof(struct voicefile);
320 #else /* load the full file */
321 load_size = file_size;
322 #endif
324 #ifdef TALK_PARTIAL_LOAD
325 if (load_size > bufsize) /* won't fit? */
326 goto load_err;
327 #endif
329 got_size = read(filehandle, voicebuf.buf, load_size);
330 if (got_size != load_size /* failure */)
331 goto load_err;
333 alloc_size = load_size;
335 #ifdef ROCKBOX_LITTLE_ENDIAN
336 logf("Byte swapping voice file");
337 structec_convert(voicebuf.buf, "lllll", 1, true);
338 #endif
340 /* format check */
341 if (voicebuf.file->table == sizeof(struct voicefile))
343 p_voicefile = voicebuf.file;
345 if (p_voicefile->version != VOICE_VERSION ||
346 p_voicefile->target_id != TARGET_ID)
348 logf("Incompatible voice file");
349 goto load_err;
351 #if CONFIG_CODEC != SWCODEC
352 /* MASCODEC: now use audiobuf for voice then thumbnail */
353 p_thumbnail = voicebuf.buf + file_size;
354 p_thumbnail += (long)p_thumbnail % 2; /* 16-bit align */
355 size_for_thumbnail = voicebuf.buf + bufsize - p_thumbnail;
356 #endif
358 else
359 goto load_err;
361 #if defined(TALK_PROGRESSIVE_LOAD) || defined(TALK_PARTIAL_LOAD)
362 /* load the index table, now that we know its size from the header */
363 load_size = (p_voicefile->id1_max + p_voicefile->id2_max)
364 * sizeof(struct clip_entry);
366 #ifdef TALK_PARTIAL_LOAD
367 if (load_size > bufsize) /* won't fit? */
368 goto load_err;
369 #endif
371 got_size = read(filehandle, &p_voicefile->index[0], load_size);
372 if (got_size != load_size) /* read error */
373 goto load_err;
375 alloc_size += load_size;
376 #else
377 close(filehandle);
378 filehandle = -1;
379 #endif /* defined(TALK_PROGRESSIVE_LOAD) || defined(TALK_PARTIAL_LOAD) */
381 #ifdef ROCKBOX_LITTLE_ENDIAN
382 for (i = 0; i < p_voicefile->id1_max + p_voicefile->id2_max; i++)
383 structec_convert(&p_voicefile->index[i], "ll", 1, true);
384 #endif
386 #ifdef TALK_PARTIAL_LOAD
387 clip_buffer = (unsigned char *) p_voicefile + p_voicefile->table;
388 unsigned clips = p_voicefile->id1_max + p_voicefile->id2_max;
389 clip_buffer += clips * sizeof(struct clip_entry); /* skip index */
390 #endif
391 if (!probe) {
392 /* make sure to have the silence clip, if available */
393 p_silence = get_clip(VOICE_PAUSE, &silence_len);
396 #ifdef TALK_PARTIAL_LOAD
397 alloc_size += silence_len + QUEUE_SIZE;
398 #endif
399 if ((size_t)alloc_size > bufsize)
400 goto load_err;
401 return;
403 load_err:
404 p_voicefile = NULL;
405 has_voicefile = false; /* don't try again */
406 if (filehandle >= 0)
408 close(filehandle);
409 filehandle = -1;
411 return;
415 /* called in ISR context if mp3 data got consumed */
416 static void mp3_callback(unsigned char** start, size_t* size)
418 queue[queue_read].len -= sent; /* we completed this */
419 queue[queue_read].buf += sent;
421 if (queue[queue_read].len > 0) /* current clip not finished? */
422 { /* feed the next 64K-1 chunk */
423 #if CONFIG_CODEC != SWCODEC
424 sent = MIN(queue[queue_read].len, 0xFFFF);
425 #else
426 sent = queue[queue_read].len;
427 #endif
428 *start = queue[queue_read].buf;
429 *size = sent;
430 return;
432 talk_queue_lock();
433 if(p_thumbnail
434 && queue[queue_read].buf == p_thumbnail +thumbnail_buf_used)
435 thumbnail_buf_used = 0;
436 if (sent > 0) /* go to next entry */
438 queue_read = (queue_read + 1) & QUEUE_MASK;
441 re_check:
443 if (QUEUE_LEVEL != 0) /* queue is not empty? */
444 { /* start next clip */
445 #if CONFIG_CODEC != SWCODEC
446 sent = MIN(queue[queue_read].len, 0xFFFF);
447 #else
448 sent = queue[queue_read].len;
449 #endif
450 *start = p_lastclip = queue[queue_read].buf;
451 *size = sent;
452 curr_hd[0] = p_lastclip[1];
453 curr_hd[1] = p_lastclip[2];
454 curr_hd[2] = p_lastclip[3];
456 else if (p_silence != NULL /* silence clip available */
457 && p_lastclip != p_silence /* previous clip wasn't silence */
458 && !(p_lastclip >= p_thumbnail /* ..or thumbnail */
459 && p_lastclip < p_thumbnail +size_for_thumbnail))
460 { /* add silence clip when queue runs empty playing a voice clip */
461 queue[queue_write].buf = p_silence;
462 queue[queue_write].len = silence_len;
463 queue_write = (queue_write + 1) & QUEUE_MASK;
465 goto re_check;
467 else
469 *size = 0; /* end of data */
471 talk_queue_unlock();
474 /***************** Public routines *****************/
476 /* stop the playback and the pending clips */
477 void talk_force_shutup(void)
479 /* Most of this is MAS only */
480 #if CONFIG_CODEC != SWCODEC
481 #ifdef SIMULATOR
482 return;
483 #endif
484 unsigned char* pos;
485 unsigned char* search;
486 unsigned char* end;
487 if (QUEUE_LEVEL == 0) /* has ended anyway */
488 return;
490 #if CONFIG_CPU == SH7034
491 CHCR3 &= ~0x0001; /* disable the DMA (and therefore the interrupt also) */
492 #endif /* CONFIG_CPU == SH7034 */
493 /* search next frame boundary and continue up to there */
494 pos = search = mp3_get_pos();
495 end = queue[queue_read].buf + queue[queue_read].len;
497 if (pos >= queue[queue_read].buf
498 && pos <= end) /* really our clip? */
499 { /* (for strange reasons this isn't nesessarily the case) */
500 /* find the next frame boundary */
501 while (search < end) /* search the remaining data */
503 if (*search++ != 0xFF) /* quick search for frame sync byte */
504 continue; /* (this does the majority of the job) */
506 /* look at the (bitswapped) rest of header candidate */
507 if (search[0] == curr_hd[0] /* do the quicker checks first */
508 && search[2] == curr_hd[2]
509 && (search[1] & 0x30) == (curr_hd[1] & 0x30)) /* sample rate */
511 search--; /* back to the sync byte */
512 break; /* From looking at it, this is our header. */
516 if (search-pos)
517 { /* play old data until the frame end, to keep the MAS in sync */
518 sent = search-pos;
520 queue_write = (queue_read + 1) & QUEUE_MASK; /* will be empty after next callback */
521 queue[queue_read].len = sent; /* current one ends after this */
523 #if CONFIG_CPU == SH7034
524 DTCR3 = sent; /* let the DMA finish this frame */
525 CHCR3 |= 0x0001; /* re-enable DMA */
526 #endif /* CONFIG_CPU == SH7034 */
527 thumbnail_buf_used = 0;
528 return;
531 #endif /* CONFIG_CODEC != SWCODEC */
533 /* Either SWCODEC, or MAS had nothing to do (was frame boundary or not our clip) */
534 mp3_play_stop();
535 talk_queue_lock();
536 queue_write = queue_read = 0; /* reset the queue */
537 thumbnail_buf_used = 0;
538 talk_queue_unlock();
539 need_shutup = false;
542 /* Shutup the voice, except if force_enqueue_next is set. */
543 void talk_shutup(void)
545 if (need_shutup && !force_enqueue_next)
546 talk_force_shutup();
549 /* schedule a clip, at the end or discard the existing queue */
550 static void queue_clip(unsigned char* buf, long size, bool enqueue)
552 int queue_level;
554 if (!enqueue)
555 talk_shutup(); /* cut off all the pending stuff */
556 /* Something is being enqueued, force_enqueue_next override is no
557 longer in effect. */
558 force_enqueue_next = false;
560 if (!size)
561 return; /* safety check */
562 #if CONFIG_CPU == SH7034
563 /* disable the DMA temporarily, to be safe of race condition */
564 CHCR3 &= ~0x0001;
565 #endif
566 talk_queue_lock();
567 queue_level = QUEUE_LEVEL; /* check old level */
569 if (queue_level < QUEUE_SIZE - 1) /* space left? */
571 queue[queue_write].buf = buf; /* populate an entry */
572 queue[queue_write].len = size;
573 queue_write = (queue_write + 1) & QUEUE_MASK;
575 talk_queue_unlock();
577 if (queue_level == 0)
578 { /* queue was empty, we have to do the initial start */
579 p_lastclip = buf;
580 #if CONFIG_CODEC != SWCODEC
581 sent = MIN(size, 0xFFFF); /* DMA can do no more */
582 #else
583 sent = size;
584 #endif
585 mp3_play_data(buf, sent, mp3_callback);
586 curr_hd[0] = buf[1];
587 curr_hd[1] = buf[2];
588 curr_hd[2] = buf[3];
589 mp3_play_pause(true); /* kickoff audio */
591 else
593 #if CONFIG_CPU == SH7034
594 CHCR3 |= 0x0001; /* re-enable DMA */
595 #endif
598 need_shutup = true;
600 return;
604 static void alloc_thumbnail_buf(void)
606 #if CONFIG_CODEC == SWCODEC
607 /* Allocate a dedicated thumbnail buffer - once */
608 if (p_thumbnail == NULL)
610 size_for_thumbnail = core_available();
611 if (size_for_thumbnail > MAX_THUMBNAIL_BUFSIZE)
612 size_for_thumbnail = MAX_THUMBNAIL_BUFSIZE;
613 int handle = core_alloc("thumbnail", size_for_thumbnail);
614 p_thumbnail = core_get_data(handle);
616 #else
617 /* use the audio buffer now, need to release before loading a voice */
618 p_thumbnail = voicebuf;
619 #endif
620 thumbnail_buf_used = 0;
623 /* common code for talk_init() and talk_buffer_steal() */
624 static void reset_state(void)
626 queue_write = queue_read = 0; /* reset the queue */
627 p_voicefile = NULL; /* indicate no voicefile (trashed) */
628 p_thumbnail = NULL;
630 #ifdef TALK_PARTIAL_LOAD
631 int i;
632 for(i=0; i<QUEUE_SIZE; i++)
633 buffered_id[i] = -1;
634 #endif
636 p_silence = NULL; /* pause clip not accessible */
637 voicebuf = NULL;
641 /***************** Public implementation *****************/
643 void talk_init(void)
645 talk_temp_disable_count = 0;
646 if (talk_initialized && !strcasecmp(last_lang, global_settings.lang_file))
648 /* not a new file, nothing to do */
649 return;
652 #if defined(TALK_PROGRESSIVE_LOAD) || defined(TALK_PARTIAL_LOAD)
653 if (filehandle >= 0)
655 close(filehandle);
656 filehandle = -1;
658 #endif
660 #if CONFIG_CODEC == SWCODEC
661 if(!talk_initialized)
662 mutex_init(&queue_mutex);
663 #endif /* CONFIG_CODEC == SWCODEC */
665 talk_initialized = true;
666 strlcpy((char *)last_lang, (char *)global_settings.lang_file,
667 MAX_FILENAME);
669 filehandle = open_voicefile();
670 if (filehandle < 0) {
671 has_voicefile = false;
672 voicefile_size = 0;
673 return;
676 voicefile_size = filesize(filehandle);
678 #if CONFIG_CODEC == SWCODEC
679 audio_get_buffer(false, NULL); /* Must tell audio to reinitialize */
680 #endif
681 reset_state(); /* use this for most of our inits */
683 #ifdef TALK_PARTIAL_LOAD
684 size_t bufsize;
685 char* buf = plugin_get_buffer(&bufsize);
686 /* we won't load the full file, we only need the index */
687 load_voicefile(true, buf, bufsize);
688 if (!p_voicefile)
689 return;
691 unsigned clips = p_voicefile->id1_max + p_voicefile->id2_max;
692 unsigned i;
693 int silence_size = 0;
695 for(i=0; i<clips; i++) {
696 int size = p_voicefile->index[i].size;
697 if (size > max_clipsize)
698 max_clipsize = size;
699 if (i == VOICE_PAUSE)
700 silence_size = size;
703 voicefile_size = p_voicefile->table + clips * sizeof(struct clip_entry);
704 voicefile_size += max_clipsize * QUEUE_SIZE + silence_size;
705 p_voicefile = NULL; /* Don't pretend we can load talk clips just yet */
706 #endif
709 /* test if we can open and if it fits in the audiobuffer */
710 size_t audiobufsz = core_available();
711 if (voicefile_size <= audiobufsz) {
712 has_voicefile = true;
713 } else {
714 has_voicefile = false;
715 voicefile_size = 0;
718 alloc_thumbnail_buf();
719 close(filehandle); /* close again, this was just to detect presence */
720 filehandle = -1;
723 #if CONFIG_CODEC == SWCODEC
724 /* return if a voice codec is required or not */
725 bool talk_voice_required(void)
727 return (voicefile_size != 0) /* Voice file is available */
728 || (global_settings.talk_dir_clip) /* Thumbnail clips are required */
729 || (global_settings.talk_file_clip);
731 #endif
733 /* return size of voice file */
734 int talk_get_buffer(void)
736 return voicefile_size;
739 size_t talkbuf_init(char *bufstart)
741 if (bufstart)
742 voicebuf = bufstart;
743 else
744 reset_state();
746 return voicefile_size;
749 /* somebody else claims the mp3 buffer, e.g. for regular play/record */
750 void talk_buffer_steal(void)
752 #if CONFIG_CODEC != SWCODEC
753 mp3_play_stop();
754 #endif
755 #if defined(TALK_PROGRESSIVE_LOAD) || defined(TALK_PARTIAL_LOAD)
756 if (filehandle >= 0)
758 close(filehandle);
759 filehandle = -1;
761 #endif
762 reset_state();
766 /* play a voice ID from voicefile */
767 int talk_id(int32_t id, bool enqueue)
769 long clipsize;
770 unsigned char* clipbuf;
771 int32_t unit;
772 int decimals;
774 if (talk_temp_disable_count > 0)
775 return -1; /* talking has been disabled */
776 #if CONFIG_CODEC != SWCODEC
777 if (audio_status()) /* busy, buffer in use */
778 return -1;
779 #endif
781 if (p_voicefile == NULL && has_voicefile)
782 load_voicefile(false, voicebuf, voicefile_size); /* reload needed */
784 if (p_voicefile == NULL) /* still no voices? */
785 return -1;
787 if (id == -1) /* -1 is an indication for silence */
788 return -1;
790 decimals = (((uint32_t)id) >> DECIMAL_SHIFT) & 0x7;
792 /* check if this is a special ID, with a value */
793 unit = ((uint32_t)id) >> UNIT_SHIFT;
794 if (unit || decimals)
795 { /* sign-extend the value */
796 id = (uint32_t)id << (32-DECIMAL_SHIFT);
797 id >>= (32-DECIMAL_SHIFT);
799 talk_value_decimal(id, unit, decimals, enqueue); /* speak it */
800 return 0; /* and stop, end of special case */
803 clipbuf = get_clip(id, &clipsize);
804 if (clipbuf == NULL)
805 return -1; /* not present */
807 #ifdef LOGF_ENABLE
808 if (id > VOICEONLY_DELIMITER)
809 logf("\ntalk_id: Say voice clip 0x%x\n", id);
810 else
811 logf("\ntalk_id: Say '%s'\n", str(id));
812 #endif
814 queue_clip(clipbuf, clipsize, enqueue);
816 return 0;
818 /* Speaks zero or more IDs (from an array). */
819 int talk_idarray(const long *ids, bool enqueue)
821 int r;
822 if(!ids)
823 return 0;
824 while(*ids != TALK_FINAL_ID)
826 if((r = talk_id(*ids++, enqueue)) <0)
827 return r;
828 enqueue = true;
830 return 0;
833 /* Make sure the current utterance is not interrupted by the next one. */
834 void talk_force_enqueue_next(void)
836 force_enqueue_next = true;
839 /* play a thumbnail from file */
840 /* Returns size of spoken thumbnail, so >0 means something is spoken,
841 <=0 means something went wrong. */
842 static int _talk_file(const char* filename,
843 const long *prefix_ids, bool enqueue)
845 int fd;
846 int size;
847 int thumb_used;
848 #if CONFIG_CODEC != SWCODEC
849 struct mp3entry info;
850 #endif
852 if (talk_temp_disable_count > 0)
853 return -1; /* talking has been disabled */
854 #if CONFIG_CODEC != SWCODEC
855 if (audio_status()) /* busy, buffer in use */
856 return -1;
857 #endif
859 if (p_thumbnail == NULL || size_for_thumbnail <= 0)
860 alloc_thumbnail_buf();
862 #if CONFIG_CODEC != SWCODEC
863 if(mp3info(&info, filename)) /* use this to find real start */
865 return 0; /* failed to open, or invalid */
867 #endif
869 if (!enqueue)
870 /* shutup now to free the thumbnail buffer */
871 talk_shutup();
873 fd = open(filename, O_RDONLY);
874 if (fd < 0) /* failed to open */
876 return 0;
879 thumb_used = thumbnail_buf_used;
880 if(filesize(fd) > size_for_thumbnail -thumb_used)
881 { /* Don't play truncated clips */
882 close(fd);
883 return 0;
886 #if CONFIG_CODEC != SWCODEC
887 lseek(fd, info.first_frame_offset, SEEK_SET); /* behind ID data */
888 #endif
890 size = read(fd, p_thumbnail +thumb_used,
891 size_for_thumbnail -thumb_used);
892 close(fd);
894 /* ToDo: find audio, skip ID headers and trailers */
896 if (size > 0) /* Don't play missing clips */
898 #if CONFIG_CODEC != SWCODEC && !defined(SIMULATOR)
899 bitswap(p_thumbnail, size);
900 #endif
901 if(prefix_ids)
902 /* prefix thumbnail by speaking these ids, but only now
903 that we know there's actually a thumbnail to be
904 spoken. */
905 talk_idarray(prefix_ids, true);
906 talk_queue_lock();
907 thumbnail_buf_used = thumb_used +size;
908 talk_queue_unlock();
909 queue_clip(p_thumbnail +thumb_used, size, true);
912 return size;
915 int talk_file(const char *root, const char *dir, const char *file,
916 const char *ext, const long *prefix_ids, bool enqueue)
917 /* Play a thumbnail file */
919 char buf[MAX_PATH];
920 /* Does root end with a slash */
921 char *slash = (root && root[0]
922 && root[strlen(root)-1] != '/') ? "/" : "";
923 snprintf(buf, MAX_PATH, "%s%s%s%s%s%s",
924 root ? root : "", slash,
925 dir ? dir : "", dir ? "/" : "",
926 file ? file : "",
927 ext ? ext : "");
928 return _talk_file(buf, prefix_ids, enqueue);
931 static int talk_spell_basename(const char *path,
932 const long *prefix_ids, bool enqueue)
934 if(prefix_ids)
936 talk_idarray(prefix_ids, enqueue);
937 enqueue = true;
939 char buf[MAX_PATH];
940 /* Spell only the path component after the last slash */
941 strlcpy(buf, path, sizeof(buf));
942 if(strlen(buf) >1 && buf[strlen(buf)-1] == '/')
943 /* strip trailing slash */
944 buf[strlen(buf)-1] = '\0';
945 char *ptr = strrchr(buf, '/');
946 if(ptr && strlen(buf) >1)
947 ++ptr;
948 else ptr = buf;
949 return talk_spell(ptr, enqueue);
952 /* Play a file's .talk thumbnail, fallback to spelling the filename, or
953 go straight to spelling depending on settings. */
954 int talk_file_or_spell(const char *dirname, const char *filename,
955 const long *prefix_ids, bool enqueue)
957 if (global_settings.talk_file_clip)
958 { /* .talk clips enabled */
959 if(talk_file(dirname, NULL, filename, file_thumbnail_ext,
960 prefix_ids, enqueue) >0)
961 return 0;
963 if (global_settings.talk_file == 2)
964 /* Either .talk clips are disabled, or as a fallback */
965 return talk_spell_basename(filename, prefix_ids, enqueue);
966 return 0;
969 /* Play a directory's .talk thumbnail, fallback to spelling the filename, or
970 go straight to spelling depending on settings. */
971 int talk_dir_or_spell(const char* dirname,
972 const long *prefix_ids, bool enqueue)
974 if (global_settings.talk_dir_clip)
975 { /* .talk clips enabled */
976 if(talk_file(dirname, NULL, dir_thumbnail_name, NULL,
977 prefix_ids, enqueue) >0)
978 return 0;
980 if (global_settings.talk_dir == 2)
981 /* Either .talk clips disabled or as a fallback */
982 return talk_spell_basename(dirname, prefix_ids, enqueue);
983 return 0;
986 /* say a numeric value, this word ordering works for english,
987 but not necessarily for other languages (e.g. german) */
988 int talk_number(long n, bool enqueue)
990 int level = 2; /* mille count */
991 long mil = 1000000000; /* highest possible "-illion" */
993 if (talk_temp_disable_count > 0)
994 return -1; /* talking has been disabled */
995 #if CONFIG_CODEC != SWCODEC
996 if (audio_status()) /* busy, buffer in use */
997 return -1;
998 #endif
1000 if (!enqueue)
1001 talk_shutup(); /* cut off all the pending stuff */
1003 if (n==0)
1004 { /* special case */
1005 talk_id(VOICE_ZERO, true);
1006 return 0;
1009 if (n<0)
1011 talk_id(VOICE_MINUS, true);
1012 n = -n;
1015 while (n)
1017 int segment = n / mil; /* extract in groups of 3 digits */
1018 n -= segment * mil; /* remove the used digits from number */
1019 mil /= 1000; /* digit place for next round */
1021 if (segment)
1023 int hundreds = segment / 100;
1024 int ones = segment % 100;
1026 if (hundreds)
1028 talk_id(VOICE_ZERO + hundreds, true);
1029 talk_id(VOICE_HUNDRED, true);
1032 /* combination indexing */
1033 if (ones > 20)
1035 int tens = ones/10 + 18;
1036 talk_id(VOICE_ZERO + tens, true);
1037 ones %= 10;
1040 /* direct indexing */
1041 if (ones)
1042 talk_id(VOICE_ZERO + ones, true);
1044 /* add billion, million, thousand */
1045 if (mil)
1046 talk_id(VOICE_THOUSAND + level, true);
1048 level--;
1051 return 0;
1054 /* Say time duration/interval. Input is time in seconds,
1055 say hours,minutes,seconds. */
1056 static int talk_time_unit(long secs, bool enqueue)
1058 int hours, mins;
1059 if (!enqueue)
1060 talk_shutup();
1061 if((hours = secs/3600)) {
1062 secs %= 3600;
1063 talk_value(hours, UNIT_HOUR, true);
1065 if((mins = secs/60)) {
1066 secs %= 60;
1067 talk_value(mins, UNIT_MIN, true);
1069 if((secs) || (!hours && !mins))
1070 talk_value(secs, UNIT_SEC, true);
1071 else if(!hours && secs)
1072 talk_number(secs, true);
1073 return 0;
1076 void talk_fractional(char *tbuf, int value, int unit)
1078 int i;
1079 /* strip trailing zeros from the fraction */
1080 for (i = strlen(tbuf) - 1; (i >= 0) && (tbuf[i] == '0'); i--)
1081 tbuf[i] = '\0';
1083 talk_number(value, true);
1084 if (tbuf[0] != 0)
1086 talk_id(LANG_POINT, true);
1087 talk_spell(tbuf, true);
1089 talk_id(unit, true);
1092 int talk_value(long n, int unit, bool enqueue)
1094 return talk_value_decimal(n, unit, 0, enqueue);
1097 /* singular/plural aware saying of a value */
1098 int talk_value_decimal(long n, int unit, int decimals, bool enqueue)
1100 int unit_id;
1101 static const int unit_voiced[] =
1102 { /* lookup table for the voice ID of the units */
1103 [0 ... UNIT_LAST-1] = -1, /* regular ID, int, signed */
1104 [UNIT_MS]
1105 = VOICE_MILLISECONDS, /* here come the "real" units */
1106 [UNIT_SEC]
1107 = VOICE_SECONDS,
1108 [UNIT_MIN]
1109 = VOICE_MINUTES,
1110 [UNIT_HOUR]
1111 = VOICE_HOURS,
1112 [UNIT_KHZ]
1113 = VOICE_KHZ,
1114 [UNIT_DB]
1115 = VOICE_DB,
1116 [UNIT_PERCENT]
1117 = VOICE_PERCENT,
1118 [UNIT_MAH]
1119 = VOICE_MILLIAMPHOURS,
1120 [UNIT_PIXEL]
1121 = VOICE_PIXEL,
1122 [UNIT_PER_SEC]
1123 = VOICE_PER_SEC,
1124 [UNIT_HERTZ]
1125 = VOICE_HERTZ,
1126 [UNIT_MB]
1127 = LANG_MEGABYTE,
1128 [UNIT_KBIT]
1129 = VOICE_KBIT_PER_SEC,
1130 [UNIT_PM_TICK]
1131 = VOICE_PM_UNITS_PER_TICK,
1134 static const int pow10[] = { /* 10^0 - 10^7 */
1135 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000
1138 char tbuf[8];
1139 char fmt[] = "%0nd";
1141 if (talk_temp_disable_count > 0)
1142 return -1; /* talking has been disabled */
1143 #if CONFIG_CODEC != SWCODEC
1144 if (audio_status()) /* busy, buffer in use */
1145 return -1;
1146 #endif
1148 /* special case for time duration */
1149 if (unit == UNIT_TIME)
1150 return talk_time_unit(n, enqueue);
1152 if (unit < 0 || unit >= UNIT_LAST)
1153 unit_id = -1;
1154 else
1155 unit_id = unit_voiced[unit];
1157 if ((n==1 || n==-1) /* singular? */
1158 && unit_id >= VOICE_SECONDS && unit_id <= VOICE_HOURS)
1160 unit_id--; /* use the singular for those units which have */
1163 /* special case with a "plus" before */
1164 if (n > 0 && (unit == UNIT_SIGNED || unit == UNIT_DB))
1166 talk_id(VOICE_PLUS, enqueue);
1167 enqueue = true;
1170 if (decimals)
1172 /* needed for the "-0.5" corner case */
1173 if (n < 0)
1175 talk_id(VOICE_MINUS, enqueue);
1176 n = -n;
1179 fmt[2] = '0' + decimals;
1181 snprintf(tbuf, sizeof(tbuf), fmt, n % pow10[decimals]);
1182 talk_fractional(tbuf, n / pow10[decimals], unit_id);
1184 return 0;
1187 talk_number(n, enqueue); /* say the number */
1188 talk_id(unit_id, true); /* say the unit, if any */
1190 return 0;
1193 /* spell a string */
1194 int talk_spell(const char* spell, bool enqueue)
1196 char c; /* currently processed char */
1198 if (talk_temp_disable_count > 0)
1199 return -1; /* talking has been disabled */
1200 #if CONFIG_CODEC != SWCODEC
1201 if (audio_status()) /* busy, buffer in use */
1202 return -1;
1203 #endif
1205 if (!enqueue)
1206 talk_shutup(); /* cut off all the pending stuff */
1208 while ((c = *spell++) != '\0')
1210 /* if this grows into too many cases, I should use a table */
1211 if (c >= 'A' && c <= 'Z')
1212 talk_id(VOICE_CHAR_A + c - 'A', true);
1213 else if (c >= 'a' && c <= 'z')
1214 talk_id(VOICE_CHAR_A + c - 'a', true);
1215 else if (c >= '0' && c <= '9')
1216 talk_id(VOICE_ZERO + c - '0', true);
1217 else if (c == '-')
1218 talk_id(VOICE_MINUS, true);
1219 else if (c == '+')
1220 talk_id(VOICE_PLUS, true);
1221 else if (c == '.')
1222 talk_id(VOICE_DOT, true);
1223 else if (c == ' ')
1224 talk_id(VOICE_PAUSE, true);
1225 else if (c == '/')
1226 talk_id(VOICE_CHAR_SLASH, true);
1229 return 0;
1232 void talk_disable(bool disable)
1234 if (disable)
1235 talk_temp_disable_count++;
1236 else
1237 talk_temp_disable_count--;
1240 void talk_setting(const void *global_settings_variable)
1242 const struct settings_list *setting;
1243 if (!global_settings.talk_menu)
1244 return;
1245 setting = find_setting(global_settings_variable, NULL);
1246 if (setting == NULL)
1247 return;
1248 if (setting->lang_id)
1249 talk_id(setting->lang_id,false);
1253 #if CONFIG_RTC
1254 void talk_date(const struct tm *tm, bool enqueue)
1256 talk_id(LANG_MONTH_JANUARY + tm->tm_mon, enqueue);
1257 talk_number(tm->tm_mday, true);
1258 talk_number(1900 + tm->tm_year, true);
1261 void talk_time(const struct tm *tm, bool enqueue)
1263 if (global_settings.timeformat == 1)
1265 /* Voice the hour */
1266 long am_pm_id = VOICE_AM;
1267 int hour = tm->tm_hour;
1268 if (hour >= 12)
1270 am_pm_id = VOICE_PM;
1271 hour -= 12;
1273 if (hour == 0)
1274 hour = 12;
1275 talk_number(hour, enqueue);
1277 /* Voice the minutes */
1278 if (tm->tm_min == 0)
1280 /* Say o'clock if the minute is 0. */
1281 talk_id(VOICE_OCLOCK, true);
1283 else
1285 /* Pronounce the leading 0 */
1286 if(tm->tm_min < 10)
1287 talk_id(VOICE_OH, true);
1288 talk_number(tm->tm_min, true);
1290 talk_id(am_pm_id, true);
1292 else
1294 /* Voice the time in 24 hour format */
1295 talk_number(tm->tm_hour, enqueue);
1296 if (tm->tm_min == 0)
1298 talk_id(VOICE_HUNDRED, true);
1299 talk_id(VOICE_HOUR, true);
1301 else
1303 /* Pronounce the leading 0 */
1304 if(tm->tm_min < 10)
1305 talk_id(VOICE_OH, true);
1306 talk_number(tm->tm_min, true);
1311 #endif /* CONFIG_RTC */