Replace all direct accesses to audiobuf with buffer API functions.
[kugel-rb.git] / apps / talk.c
bloba5fbd13c30f5310549b691cb811438f2c60ff662
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 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 = buffer_available();
611 if (size_for_thumbnail > MAX_THUMBNAIL_BUFSIZE)
612 size_for_thumbnail = MAX_THUMBNAIL_BUFSIZE;
613 p_thumbnail = buffer_alloc(size_for_thumbnail);
615 #else
616 /* use the audio buffer now, need to release before loading a voice */
617 p_thumbnail = voicebuf;
618 #endif
619 thumbnail_buf_used = 0;
622 /* common code for talk_init() and talk_buffer_steal() */
623 static void reset_state(void)
625 queue_write = queue_read = 0; /* reset the queue */
626 p_voicefile = NULL; /* indicate no voicefile (trashed) */
627 p_thumbnail = NULL;
629 #ifdef TALK_PARTIAL_LOAD
630 int i;
631 for(i=0; i<QUEUE_SIZE; i++)
632 buffered_id[i] = -1;
633 #endif
635 p_silence = NULL; /* pause clip not accessible */
636 voicebuf = NULL;
640 /***************** Public implementation *****************/
642 void talk_init(void)
644 talk_temp_disable_count = 0;
645 if (talk_initialized && !strcasecmp(last_lang, global_settings.lang_file))
647 /* not a new file, nothing to do */
648 return;
651 #if defined(TALK_PROGRESSIVE_LOAD) || defined(TALK_PARTIAL_LOAD)
652 if (filehandle >= 0)
654 close(filehandle);
655 filehandle = -1;
657 #endif
659 #if CONFIG_CODEC == SWCODEC
660 if(!talk_initialized)
661 mutex_init(&queue_mutex);
662 #endif /* CONFIG_CODEC == SWCODEC */
664 talk_initialized = true;
665 strlcpy((char *)last_lang, (char *)global_settings.lang_file,
666 MAX_FILENAME);
668 filehandle = open_voicefile();
669 if (filehandle < 0) {
670 has_voicefile = false;
671 voicefile_size = 0;
672 return;
675 voicefile_size = filesize(filehandle);
677 #if CONFIG_CODEC == SWCODEC
678 audio_get_buffer(false, NULL); /* Must tell audio to reinitialize */
679 #endif
680 reset_state(); /* use this for most of our inits */
682 #ifdef TALK_PARTIAL_LOAD
683 size_t bufsize;
684 char* buf = plugin_get_buffer(&bufsize);
685 /* we won't load the full file, we only need the index */
686 load_voicefile(true, buf, bufsize);
687 if (!p_voicefile)
688 return;
690 unsigned clips = p_voicefile->id1_max + p_voicefile->id2_max;
691 unsigned i;
692 int silence_size = 0;
694 for(i=0; i<clips; i++) {
695 int size = p_voicefile->index[i].size;
696 if (size > max_clipsize)
697 max_clipsize = size;
698 if (i == VOICE_PAUSE)
699 silence_size = size;
702 voicefile_size = p_voicefile->table + clips * sizeof(struct clip_entry);
703 voicefile_size += max_clipsize * QUEUE_SIZE + silence_size;
704 p_voicefile = NULL; /* Don't pretend we can load talk clips just yet */
705 #endif
708 /* test if we can open and if it fits in the audiobuffer */
709 size_t audiobufsz = buffer_available();
710 if (voicefile_size <= audiobufsz) {
711 has_voicefile = true;
712 } else {
713 has_voicefile = false;
714 voicefile_size = 0;
717 alloc_thumbnail_buf();
718 close(filehandle); /* close again, this was just to detect presence */
719 filehandle = -1;
722 #if CONFIG_CODEC == SWCODEC
723 /* return if a voice codec is required or not */
724 bool talk_voice_required(void)
726 return (voicefile_size != 0) /* Voice file is available */
727 || (global_settings.talk_dir_clip) /* Thumbnail clips are required */
728 || (global_settings.talk_file_clip);
730 #endif
732 /* return size of voice file */
733 int talk_get_buffer(void)
735 return voicefile_size;
738 size_t talkbuf_init(char *bufstart)
740 if (bufstart)
741 voicebuf = bufstart;
742 else
743 reset_state();
745 return voicefile_size;
748 /* somebody else claims the mp3 buffer, e.g. for regular play/record */
749 void talk_buffer_steal(void)
751 #if CONFIG_CODEC != SWCODEC
752 mp3_play_stop();
753 #endif
754 #if defined(TALK_PROGRESSIVE_LOAD) || defined(TALK_PARTIAL_LOAD)
755 if (filehandle >= 0)
757 close(filehandle);
758 filehandle = -1;
760 #endif
761 reset_state();
765 /* play a voice ID from voicefile */
766 int talk_id(int32_t id, bool enqueue)
768 long clipsize;
769 unsigned char* clipbuf;
770 int32_t unit;
771 int decimals;
773 if (talk_temp_disable_count > 0)
774 return -1; /* talking has been disabled */
775 #if CONFIG_CODEC != SWCODEC
776 if (audio_status()) /* busy, buffer in use */
777 return -1;
778 #endif
780 if (p_voicefile == NULL && has_voicefile)
781 load_voicefile(false, voicebuf, voicefile_size); /* reload needed */
783 if (p_voicefile == NULL) /* still no voices? */
784 return -1;
786 if (id == -1) /* -1 is an indication for silence */
787 return -1;
789 decimals = (((uint32_t)id) >> DECIMAL_SHIFT) & 0x7;
791 /* check if this is a special ID, with a value */
792 unit = ((uint32_t)id) >> UNIT_SHIFT;
793 if (unit || decimals)
794 { /* sign-extend the value */
795 id = (uint32_t)id << (32-DECIMAL_SHIFT);
796 id >>= (32-DECIMAL_SHIFT);
798 talk_value_decimal(id, unit, decimals, enqueue); /* speak it */
799 return 0; /* and stop, end of special case */
802 clipbuf = get_clip(id, &clipsize);
803 if (clipbuf == NULL)
804 return -1; /* not present */
806 #ifdef LOGF_ENABLE
807 if (id > VOICEONLY_DELIMITER)
808 logf("\ntalk_id: Say voice clip 0x%x\n", id);
809 else
810 logf("\ntalk_id: Say '%s'\n", str(id));
811 #endif
813 queue_clip(clipbuf, clipsize, enqueue);
815 return 0;
817 /* Speaks zero or more IDs (from an array). */
818 int talk_idarray(const long *ids, bool enqueue)
820 int r;
821 if(!ids)
822 return 0;
823 while(*ids != TALK_FINAL_ID)
825 if((r = talk_id(*ids++, enqueue)) <0)
826 return r;
827 enqueue = true;
829 return 0;
832 /* Make sure the current utterance is not interrupted by the next one. */
833 void talk_force_enqueue_next(void)
835 force_enqueue_next = true;
838 /* play a thumbnail from file */
839 /* Returns size of spoken thumbnail, so >0 means something is spoken,
840 <=0 means something went wrong. */
841 static int _talk_file(const char* filename,
842 const long *prefix_ids, bool enqueue)
844 int fd;
845 int size;
846 int thumb_used;
847 #if CONFIG_CODEC != SWCODEC
848 struct mp3entry info;
849 #endif
851 if (talk_temp_disable_count > 0)
852 return -1; /* talking has been disabled */
853 #if CONFIG_CODEC != SWCODEC
854 if (audio_status()) /* busy, buffer in use */
855 return -1;
856 #endif
858 if (p_thumbnail == NULL || size_for_thumbnail <= 0)
859 alloc_thumbnail_buf();
861 #if CONFIG_CODEC != SWCODEC
862 if(mp3info(&info, filename)) /* use this to find real start */
864 return 0; /* failed to open, or invalid */
866 #endif
868 if (!enqueue)
869 /* shutup now to free the thumbnail buffer */
870 talk_shutup();
872 fd = open(filename, O_RDONLY);
873 if (fd < 0) /* failed to open */
875 return 0;
878 thumb_used = thumbnail_buf_used;
879 if(filesize(fd) > size_for_thumbnail -thumb_used)
880 { /* Don't play truncated clips */
881 close(fd);
882 return 0;
885 #if CONFIG_CODEC != SWCODEC
886 lseek(fd, info.first_frame_offset, SEEK_SET); /* behind ID data */
887 #endif
889 size = read(fd, p_thumbnail +thumb_used,
890 size_for_thumbnail -thumb_used);
891 close(fd);
893 /* ToDo: find audio, skip ID headers and trailers */
895 if (size > 0) /* Don't play missing clips */
897 #if CONFIG_CODEC != SWCODEC && !defined(SIMULATOR)
898 bitswap(p_thumbnail, size);
899 #endif
900 if(prefix_ids)
901 /* prefix thumbnail by speaking these ids, but only now
902 that we know there's actually a thumbnail to be
903 spoken. */
904 talk_idarray(prefix_ids, true);
905 talk_queue_lock();
906 thumbnail_buf_used = thumb_used +size;
907 talk_queue_unlock();
908 queue_clip(p_thumbnail +thumb_used, size, true);
911 return size;
914 int talk_file(const char *root, const char *dir, const char *file,
915 const char *ext, const long *prefix_ids, bool enqueue)
916 /* Play a thumbnail file */
918 char buf[MAX_PATH];
919 /* Does root end with a slash */
920 char *slash = (root && root[0]
921 && root[strlen(root)-1] != '/') ? "/" : "";
922 snprintf(buf, MAX_PATH, "%s%s%s%s%s%s",
923 root ? root : "", slash,
924 dir ? dir : "", dir ? "/" : "",
925 file ? file : "",
926 ext ? ext : "");
927 return _talk_file(buf, prefix_ids, enqueue);
930 static int talk_spell_basename(const char *path,
931 const long *prefix_ids, bool enqueue)
933 if(prefix_ids)
935 talk_idarray(prefix_ids, enqueue);
936 enqueue = true;
938 char buf[MAX_PATH];
939 /* Spell only the path component after the last slash */
940 strlcpy(buf, path, sizeof(buf));
941 if(strlen(buf) >1 && buf[strlen(buf)-1] == '/')
942 /* strip trailing slash */
943 buf[strlen(buf)-1] = '\0';
944 char *ptr = strrchr(buf, '/');
945 if(ptr && strlen(buf) >1)
946 ++ptr;
947 else ptr = buf;
948 return talk_spell(ptr, enqueue);
951 /* Play a file's .talk thumbnail, fallback to spelling the filename, or
952 go straight to spelling depending on settings. */
953 int talk_file_or_spell(const char *dirname, const char *filename,
954 const long *prefix_ids, bool enqueue)
956 if (global_settings.talk_file_clip)
957 { /* .talk clips enabled */
958 if(talk_file(dirname, NULL, filename, file_thumbnail_ext,
959 prefix_ids, enqueue) >0)
960 return 0;
962 if (global_settings.talk_file == 2)
963 /* Either .talk clips are disabled, or as a fallback */
964 return talk_spell_basename(filename, prefix_ids, enqueue);
965 return 0;
968 /* Play a directory's .talk thumbnail, fallback to spelling the filename, or
969 go straight to spelling depending on settings. */
970 int talk_dir_or_spell(const char* dirname,
971 const long *prefix_ids, bool enqueue)
973 if (global_settings.talk_dir_clip)
974 { /* .talk clips enabled */
975 if(talk_file(dirname, NULL, dir_thumbnail_name, NULL,
976 prefix_ids, enqueue) >0)
977 return 0;
979 if (global_settings.talk_dir == 2)
980 /* Either .talk clips disabled or as a fallback */
981 return talk_spell_basename(dirname, prefix_ids, enqueue);
982 return 0;
985 /* say a numeric value, this word ordering works for english,
986 but not necessarily for other languages (e.g. german) */
987 int talk_number(long n, bool enqueue)
989 int level = 2; /* mille count */
990 long mil = 1000000000; /* highest possible "-illion" */
992 if (talk_temp_disable_count > 0)
993 return -1; /* talking has been disabled */
994 #if CONFIG_CODEC != SWCODEC
995 if (audio_status()) /* busy, buffer in use */
996 return -1;
997 #endif
999 if (!enqueue)
1000 talk_shutup(); /* cut off all the pending stuff */
1002 if (n==0)
1003 { /* special case */
1004 talk_id(VOICE_ZERO, true);
1005 return 0;
1008 if (n<0)
1010 talk_id(VOICE_MINUS, true);
1011 n = -n;
1014 while (n)
1016 int segment = n / mil; /* extract in groups of 3 digits */
1017 n -= segment * mil; /* remove the used digits from number */
1018 mil /= 1000; /* digit place for next round */
1020 if (segment)
1022 int hundreds = segment / 100;
1023 int ones = segment % 100;
1025 if (hundreds)
1027 talk_id(VOICE_ZERO + hundreds, true);
1028 talk_id(VOICE_HUNDRED, true);
1031 /* combination indexing */
1032 if (ones > 20)
1034 int tens = ones/10 + 18;
1035 talk_id(VOICE_ZERO + tens, true);
1036 ones %= 10;
1039 /* direct indexing */
1040 if (ones)
1041 talk_id(VOICE_ZERO + ones, true);
1043 /* add billion, million, thousand */
1044 if (mil)
1045 talk_id(VOICE_THOUSAND + level, true);
1047 level--;
1050 return 0;
1053 /* Say time duration/interval. Input is time in seconds,
1054 say hours,minutes,seconds. */
1055 static int talk_time_unit(long secs, bool enqueue)
1057 int hours, mins;
1058 if (!enqueue)
1059 talk_shutup();
1060 if((hours = secs/3600)) {
1061 secs %= 3600;
1062 talk_value(hours, UNIT_HOUR, true);
1064 if((mins = secs/60)) {
1065 secs %= 60;
1066 talk_value(mins, UNIT_MIN, true);
1068 if((secs) || (!hours && !mins))
1069 talk_value(secs, UNIT_SEC, true);
1070 else if(!hours && secs)
1071 talk_number(secs, true);
1072 return 0;
1075 void talk_fractional(char *tbuf, int value, int unit)
1077 int i;
1078 /* strip trailing zeros from the fraction */
1079 for (i = strlen(tbuf) - 1; (i >= 0) && (tbuf[i] == '0'); i--)
1080 tbuf[i] = '\0';
1082 talk_number(value, true);
1083 if (tbuf[0] != 0)
1085 talk_id(LANG_POINT, true);
1086 talk_spell(tbuf, true);
1088 talk_id(unit, true);
1091 int talk_value(long n, int unit, bool enqueue)
1093 return talk_value_decimal(n, unit, 0, enqueue);
1096 /* singular/plural aware saying of a value */
1097 int talk_value_decimal(long n, int unit, int decimals, bool enqueue)
1099 int unit_id;
1100 static const int unit_voiced[] =
1101 { /* lookup table for the voice ID of the units */
1102 [0 ... UNIT_LAST-1] = -1, /* regular ID, int, signed */
1103 [UNIT_MS]
1104 = VOICE_MILLISECONDS, /* here come the "real" units */
1105 [UNIT_SEC]
1106 = VOICE_SECONDS,
1107 [UNIT_MIN]
1108 = VOICE_MINUTES,
1109 [UNIT_HOUR]
1110 = VOICE_HOURS,
1111 [UNIT_KHZ]
1112 = VOICE_KHZ,
1113 [UNIT_DB]
1114 = VOICE_DB,
1115 [UNIT_PERCENT]
1116 = VOICE_PERCENT,
1117 [UNIT_MAH]
1118 = VOICE_MILLIAMPHOURS,
1119 [UNIT_PIXEL]
1120 = VOICE_PIXEL,
1121 [UNIT_PER_SEC]
1122 = VOICE_PER_SEC,
1123 [UNIT_HERTZ]
1124 = VOICE_HERTZ,
1125 [UNIT_MB]
1126 = LANG_MEGABYTE,
1127 [UNIT_KBIT]
1128 = VOICE_KBIT_PER_SEC,
1129 [UNIT_PM_TICK]
1130 = VOICE_PM_UNITS_PER_TICK,
1133 static const int pow10[] = { /* 10^0 - 10^7 */
1134 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000
1137 char tbuf[8];
1138 char fmt[] = "%0nd";
1140 if (talk_temp_disable_count > 0)
1141 return -1; /* talking has been disabled */
1142 #if CONFIG_CODEC != SWCODEC
1143 if (audio_status()) /* busy, buffer in use */
1144 return -1;
1145 #endif
1147 /* special case for time duration */
1148 if (unit == UNIT_TIME)
1149 return talk_time_unit(n, enqueue);
1151 if (unit < 0 || unit >= UNIT_LAST)
1152 unit_id = -1;
1153 else
1154 unit_id = unit_voiced[unit];
1156 if ((n==1 || n==-1) /* singular? */
1157 && unit_id >= VOICE_SECONDS && unit_id <= VOICE_HOURS)
1159 unit_id--; /* use the singular for those units which have */
1162 /* special case with a "plus" before */
1163 if (n > 0 && (unit == UNIT_SIGNED || unit == UNIT_DB))
1165 talk_id(VOICE_PLUS, enqueue);
1166 enqueue = true;
1169 if (decimals)
1171 /* needed for the "-0.5" corner case */
1172 if (n < 0)
1174 talk_id(VOICE_MINUS, enqueue);
1175 n = -n;
1178 fmt[2] = '0' + decimals;
1180 snprintf(tbuf, sizeof(tbuf), fmt, n % pow10[decimals]);
1181 talk_fractional(tbuf, n / pow10[decimals], unit_id);
1183 return 0;
1186 talk_number(n, enqueue); /* say the number */
1187 talk_id(unit_id, true); /* say the unit, if any */
1189 return 0;
1192 /* spell a string */
1193 int talk_spell(const char* spell, bool enqueue)
1195 char c; /* currently processed char */
1197 if (talk_temp_disable_count > 0)
1198 return -1; /* talking has been disabled */
1199 #if CONFIG_CODEC != SWCODEC
1200 if (audio_status()) /* busy, buffer in use */
1201 return -1;
1202 #endif
1204 if (!enqueue)
1205 talk_shutup(); /* cut off all the pending stuff */
1207 while ((c = *spell++) != '\0')
1209 /* if this grows into too many cases, I should use a table */
1210 if (c >= 'A' && c <= 'Z')
1211 talk_id(VOICE_CHAR_A + c - 'A', true);
1212 else if (c >= 'a' && c <= 'z')
1213 talk_id(VOICE_CHAR_A + c - 'a', true);
1214 else if (c >= '0' && c <= '9')
1215 talk_id(VOICE_ZERO + c - '0', true);
1216 else if (c == '-')
1217 talk_id(VOICE_MINUS, true);
1218 else if (c == '+')
1219 talk_id(VOICE_PLUS, true);
1220 else if (c == '.')
1221 talk_id(VOICE_DOT, true);
1222 else if (c == ' ')
1223 talk_id(VOICE_PAUSE, true);
1224 else if (c == '/')
1225 talk_id(VOICE_CHAR_SLASH, true);
1228 return 0;
1231 void talk_disable(bool disable)
1233 if (disable)
1234 talk_temp_disable_count++;
1235 else
1236 talk_temp_disable_count--;
1239 void talk_setting(const void *global_settings_variable)
1241 const struct settings_list *setting;
1242 if (!global_settings.talk_menu)
1243 return;
1244 setting = find_setting(global_settings_variable, NULL);
1245 if (setting == NULL)
1246 return;
1247 if (setting->lang_id)
1248 talk_id(setting->lang_id,false);
1252 #if CONFIG_RTC
1253 void talk_date(const struct tm *tm, bool enqueue)
1255 talk_id(LANG_MONTH_JANUARY + tm->tm_mon, enqueue);
1256 talk_number(tm->tm_mday, true);
1257 talk_number(1900 + tm->tm_year, true);
1260 void talk_time(const struct tm *tm, bool enqueue)
1262 if (global_settings.timeformat == 1)
1264 /* Voice the hour */
1265 long am_pm_id = VOICE_AM;
1266 int hour = tm->tm_hour;
1267 if (hour >= 12)
1269 am_pm_id = VOICE_PM;
1270 hour -= 12;
1272 if (hour == 0)
1273 hour = 12;
1274 talk_number(hour, enqueue);
1276 /* Voice the minutes */
1277 if (tm->tm_min == 0)
1279 /* Say o'clock if the minute is 0. */
1280 talk_id(VOICE_OCLOCK, true);
1282 else
1284 /* Pronounce the leading 0 */
1285 if(tm->tm_min < 10)
1286 talk_id(VOICE_OH, true);
1287 talk_number(tm->tm_min, true);
1289 talk_id(am_pm_id, true);
1291 else
1293 /* Voice the time in 24 hour format */
1294 talk_number(tm->tm_hour, enqueue);
1295 if (tm->tm_min == 0)
1297 talk_id(VOICE_HUNDRED, true);
1298 talk_id(VOICE_HOUR, true);
1300 else
1302 /* Pronounce the leading 0 */
1303 if(tm->tm_min < 10)
1304 talk_id(VOICE_OH, true);
1305 talk_number(tm->tm_min, true);
1310 #endif /* CONFIG_RTC */