Talk: Unify hwcodec and swcodec handling.
[maemo-rb.git] / apps / talk.c
blobed7d55d4559116d5eddff78ba8f9d365df3fb936
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 "plugin.h" /* plugin_get_buffer() */
45 #include "debug.h"
48 /* Memory layout varies between targets because the
49 Archos (MASCODEC) devices cannot mix voice and audio playback
51 MASCODEC | MASCODEC | SWCODEC
52 (playing) | (stopped) |
53 voicebuf-----------+-----------+------------
54 audio | voice | voice
55 |-----------|------------
56 | thumbnail | thumbnail
57 | |------------
58 | | filebuf
59 | |------------
60 | | audio
61 voicebufend----------+-----------+------------
63 SWCODEC allocates dedicated buffers (except voice and thumbnail are together
64 in the talkbuf), MASCODEC reuses audiobuf. */
67 /***************** Constants *****************/
69 #define QUEUE_SIZE 64 /* must be a power of two */
70 #define QUEUE_MASK (QUEUE_SIZE-1)
71 const char* const dir_thumbnail_name = "_dirname.talk";
72 const char* const file_thumbnail_ext = ".talk";
74 /***************** Functional Macros *****************/
76 #define QUEUE_LEVEL ((queue_write - queue_read) & QUEUE_MASK)
78 #define LOADED_MASK 0x80000000 /* MSB */
80 #if CONFIG_CODEC == SWCODEC
81 #define MAX_THUMBNAIL_BUFSIZE 0x10000
82 #endif
84 /***************** Data types *****************/
86 struct clip_entry /* one entry of the index table */
88 int offset; /* offset from start of voicefile file */
89 int size; /* size of the clip */
92 struct voicefile /* file format of our voice file */
94 int version; /* version of the voicefile */
95 int target_id; /* the rockbox target the file was made for */
96 int table; /* offset to index table, (=header size) */
97 int id1_max; /* number of "normal" clips contained in above index */
98 int id2_max; /* number of "voice only" clips contained in above index */
99 struct clip_entry index[]; /* followed by the index tables */
100 /* and finally the mp3 clips, not visible here, bitswapped
101 for SH based players */
104 struct queue_entry /* one entry of the internal queue */
106 unsigned char* buf;
107 long len;
111 /***************** Globals *****************/
113 #if CONFIG_STORAGE & STORAGE_MMC
114 /* The MMC storage on the Ondios is slow enough that we want to buffer the
115 * talk clips only when they are needed */
116 # define TALK_PROGRESSIVE_LOAD
117 #elif CONFIG_CODEC == SWCODEC && MEMORYSIZE <= 2
118 /* The entire voice file wouldn't fit in memory together with codecs, so we
119 * load clips each time they are accessed */
120 # define TALK_PARTIAL_LOAD
121 #endif
123 #ifdef TALK_PARTIAL_LOAD
124 static unsigned char *clip_buffer;
125 static long max_clipsize; /* size of the biggest clip */
126 static long buffered_id[QUEUE_SIZE]; /* IDs of the talk clips */
127 static uint8_t clip_age[QUEUE_SIZE];
128 #if QUEUE_SIZE > 255
129 # error clip_age[] type too small
130 #endif
131 #endif
133 static char* voicebuf; /* root pointer to our buffer */
134 static unsigned char* p_thumbnail = NULL; /* buffer for thumbnails */
135 /* Multiple thumbnails can be loaded back-to-back in this buffer. */
136 static volatile int thumbnail_buf_used SHAREDBSS_ATTR; /* length of data in
137 thumbnail buffer */
138 static long size_for_thumbnail; /* total thumbnail buffer size */
139 static struct voicefile* p_voicefile; /* loaded voicefile */
140 static bool has_voicefile; /* a voicefile file is present */
141 static bool need_shutup; /* is there possibly any voice playing to be shutup */
142 static struct queue_entry queue[QUEUE_SIZE]; /* queue of scheduled clips */
143 static bool force_enqueue_next; /* enqueue next utterance even if enqueue is false */
144 static int queue_write; /* write index of queue, by application */
145 static int queue_read; /* read index of queue, by ISR context */
146 #if CONFIG_CODEC == SWCODEC
147 /* protects queue_read, queue_write and thumbnail_buf_used */
148 static struct mutex queue_mutex SHAREDBSS_ATTR;
149 #define talk_queue_lock() ({ mutex_lock(&queue_mutex); })
150 #define talk_queue_unlock() ({ mutex_unlock(&queue_mutex); })
151 #else
152 #define talk_queue_lock() ({ })
153 #define talk_queue_unlock() ({ })
154 #endif /* CONFIG_CODEC */
155 static int sent; /* how many bytes handed over to playback, owned by ISR */
156 static unsigned char curr_hd[3]; /* current frame header, for re-sync */
157 static int filehandle = -1; /* global, so we can keep the file open if needed */
158 static unsigned char* p_silence; /* VOICE_PAUSE clip, used for termination */
159 static long silence_len; /* length of the VOICE_PAUSE clip */
160 static unsigned char* p_lastclip; /* address of latest clip, for silence add */
161 static unsigned long voicefile_size = 0; /* size of the loaded voice file */
162 static unsigned char last_lang[MAX_FILENAME+1]; /* name of last used lang file (in talk_init) */
163 static bool talk_initialized; /* true if talk_init has been called */
164 static int talk_temp_disable_count; /* if positive, temporarily disable voice UI (not saved) */
167 /***************** Private implementation *****************/
169 static int open_voicefile(void)
171 char buf[64];
172 char* p_lang = "english"; /* default */
174 if ( global_settings.lang_file[0] &&
175 global_settings.lang_file[0] != 0xff )
176 { /* try to open the voice file of the selected language */
177 p_lang = (char *)global_settings.lang_file;
180 snprintf(buf, sizeof(buf), LANG_DIR "/%s.voice", p_lang);
182 return open(buf, O_RDONLY);
186 /* fetch a clip from the voice file */
187 static unsigned char* get_clip(long id, long* p_size)
189 long clipsize;
190 unsigned char* clipbuf;
192 if (id > VOICEONLY_DELIMITER)
193 { /* voice-only entries use the second part of the table */
194 id -= VOICEONLY_DELIMITER + 1;
195 if (id >= p_voicefile->id2_max)
196 return NULL; /* must be newer than we have */
197 id += p_voicefile->id1_max; /* table 2 is behind table 1 */
199 else
200 { /* normal use of the first table */
201 if (id >= p_voicefile->id1_max)
202 return NULL; /* must be newer than we have */
205 clipsize = p_voicefile->index[id].size;
206 if (clipsize == 0) /* clip not included in voicefile */
207 return NULL;
209 #ifndef TALK_PARTIAL_LOAD
210 clipbuf = (unsigned char *) p_voicefile + p_voicefile->index[id].offset;
211 #endif
213 #if defined(TALK_PROGRESSIVE_LOAD) || defined(TALK_PARTIAL_LOAD)
214 if (!(clipsize & LOADED_MASK))
215 { /* clip needs loading */
216 #ifdef TALK_PARTIAL_LOAD
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;
242 #endif
244 lseek(filehandle, p_voicefile->index[id].offset, SEEK_SET);
245 if (read(filehandle, clipbuf, clipsize) != clipsize)
246 return NULL; /* read error */
248 p_voicefile->index[id].size |= LOADED_MASK; /* mark as loaded */
250 #ifdef TALK_PARTIAL_LOAD
251 if (id != VOICE_PAUSE) {
252 if (buffered_id[idx] >= 0) {
253 /* mark previously loaded clip as unloaded */
254 p_voicefile->index[buffered_id[idx]].size &= ~LOADED_MASK;
256 buffered_id[idx] = id;
258 #endif
260 else
261 { /* clip is in memory already */
262 #ifdef TALK_PARTIAL_LOAD
263 /* Find where it was loaded */
264 clipbuf = clip_buffer;
265 if (id == VOICE_PAUSE) {
266 clipbuf += QUEUE_SIZE * max_clipsize;
267 } else {
268 int idx;
269 for (idx=0; idx<QUEUE_SIZE; idx++)
270 if (buffered_id[idx] == id) {
271 clipbuf += idx * max_clipsize;
272 clip_age[idx] = 0; /* reset clip's age */
273 break;
276 #endif
277 clipsize &= ~LOADED_MASK; /* without the extra bit gives true size */
279 #endif /* defined(TALK_PROGRESSIVE_LOAD) || defined(TALK_PARTIAL_LOAD) */
281 *p_size = clipsize;
282 return clipbuf;
286 /* load the voice file into the mp3 buffer */
287 static void load_voicefile(bool probe, char* buf, size_t bufsize)
289 union voicebuf {
290 unsigned char* buf;
291 struct voicefile* file;
293 union voicebuf voicebuf;
295 size_t load_size, alloc_size;
296 ssize_t got_size;
297 #ifndef TALK_PARTIAL_LOAD
298 size_t file_size;
299 #endif
300 #ifdef ROCKBOX_LITTLE_ENDIAN
301 int i;
302 #endif
304 if (!probe)
305 filehandle = open_voicefile();
306 if (filehandle < 0) /* failed to open */
307 goto load_err;
309 voicebuf.buf = buf;
310 if (!voicebuf.buf)
311 goto load_err;
313 #ifndef TALK_PARTIAL_LOAD
314 file_size = filesize(filehandle);
315 if (file_size > bufsize) /* won't fit? */
316 goto load_err;
317 #endif
319 #if defined(TALK_PROGRESSIVE_LOAD) || defined(TALK_PARTIAL_LOAD)
320 /* load only the header for now */
321 load_size = sizeof(struct voicefile);
322 #else /* load the full file */
323 load_size = file_size;
324 #endif
326 #ifdef TALK_PARTIAL_LOAD
327 if (load_size > bufsize) /* won't fit? */
328 goto load_err;
329 #endif
331 got_size = read(filehandle, voicebuf.buf, load_size);
332 if (got_size != (ssize_t)load_size /* failure */)
333 goto load_err;
335 alloc_size = load_size;
337 #ifdef ROCKBOX_LITTLE_ENDIAN
338 logf("Byte swapping voice file");
339 structec_convert(voicebuf.buf, "lllll", 1, true);
340 #endif
342 /* format check */
343 if (voicebuf.file->table == sizeof(struct voicefile))
345 p_voicefile = voicebuf.file;
347 if (p_voicefile->version != VOICE_VERSION ||
348 p_voicefile->target_id != TARGET_ID)
350 logf("Incompatible voice file");
351 goto load_err;
353 p_thumbnail = voicebuf.buf + file_size;
354 p_thumbnail += (long)p_thumbnail % 2; /* 16-bit align */
355 size_for_thumbnail =
356 MIN(voicebuf.buf + bufsize - p_thumbnail, MAX_THUMBNAIL_BUFSIZE);
357 if (size_for_thumbnail <= 0)
358 p_thumbnail = NULL;
360 else
361 goto load_err;
363 #if defined(TALK_PROGRESSIVE_LOAD) || defined(TALK_PARTIAL_LOAD)
364 /* load the index table, now that we know its size from the header */
365 load_size = (p_voicefile->id1_max + p_voicefile->id2_max)
366 * sizeof(struct clip_entry);
368 #ifdef TALK_PARTIAL_LOAD
369 if (load_size > bufsize) /* won't fit? */
370 goto load_err;
371 #endif
373 got_size = read(filehandle, &p_voicefile->index[0], load_size);
374 if (got_size != (ssize_t)load_size) /* read error */
375 goto load_err;
377 alloc_size += load_size;
378 #else
379 close(filehandle);
380 filehandle = -1;
381 #endif /* defined(TALK_PROGRESSIVE_LOAD) || defined(TALK_PARTIAL_LOAD) */
383 #ifdef ROCKBOX_LITTLE_ENDIAN
384 for (i = 0; i < p_voicefile->id1_max + p_voicefile->id2_max; i++)
385 structec_convert(&p_voicefile->index[i], "ll", 1, true);
386 #endif
388 #ifdef TALK_PARTIAL_LOAD
389 clip_buffer = (unsigned char *) p_voicefile + p_voicefile->table;
390 unsigned clips = p_voicefile->id1_max + p_voicefile->id2_max;
391 clip_buffer += clips * sizeof(struct clip_entry); /* skip index */
392 #endif
393 if (!probe) {
394 /* make sure to have the silence clip, if available */
395 p_silence = get_clip(VOICE_PAUSE, &silence_len);
398 #ifdef TALK_PARTIAL_LOAD
399 alloc_size += silence_len + QUEUE_SIZE;
400 #endif
401 if (alloc_size > bufsize)
402 goto load_err;
403 return;
405 load_err:
406 p_voicefile = NULL;
407 has_voicefile = false; /* don't try again */
408 if (filehandle >= 0)
410 close(filehandle);
411 filehandle = -1;
413 return;
417 /* called in ISR context if mp3 data got consumed */
418 static void mp3_callback(unsigned char** start, size_t* size)
420 queue[queue_read].len -= sent; /* we completed this */
421 queue[queue_read].buf += sent;
423 if (queue[queue_read].len > 0) /* current clip not finished? */
424 { /* feed the next 64K-1 chunk */
425 #if CONFIG_CODEC != SWCODEC
426 sent = MIN(queue[queue_read].len, 0xFFFF);
427 #else
428 sent = queue[queue_read].len;
429 #endif
430 *start = queue[queue_read].buf;
431 *size = sent;
432 return;
434 talk_queue_lock();
435 if(p_thumbnail
436 && queue[queue_read].buf == p_thumbnail +thumbnail_buf_used)
437 thumbnail_buf_used = 0;
438 if (sent > 0) /* go to next entry */
440 queue_read = (queue_read + 1) & QUEUE_MASK;
443 re_check:
445 if (QUEUE_LEVEL != 0) /* queue is not empty? */
446 { /* start next clip */
447 #if CONFIG_CODEC != SWCODEC
448 sent = MIN(queue[queue_read].len, 0xFFFF);
449 #else
450 sent = queue[queue_read].len;
451 #endif
452 *start = p_lastclip = queue[queue_read].buf;
453 *size = sent;
454 curr_hd[0] = p_lastclip[1];
455 curr_hd[1] = p_lastclip[2];
456 curr_hd[2] = p_lastclip[3];
458 else if (p_silence != NULL /* silence clip available */
459 && p_lastclip != p_silence /* previous clip wasn't silence */
460 && !(p_lastclip >= p_thumbnail /* ..or thumbnail */
461 && p_lastclip < p_thumbnail +size_for_thumbnail))
462 { /* add silence clip when queue runs empty playing a voice clip */
463 queue[queue_write].buf = p_silence;
464 queue[queue_write].len = silence_len;
465 queue_write = (queue_write + 1) & QUEUE_MASK;
467 goto re_check;
469 else
471 *size = 0; /* end of data */
473 talk_queue_unlock();
476 /***************** Public routines *****************/
478 /* stop the playback and the pending clips */
479 void talk_force_shutup(void)
481 /* Most of this is MAS only */
482 #if CONFIG_CODEC != SWCODEC
483 #ifdef SIMULATOR
484 return;
485 #endif
486 unsigned char* pos;
487 unsigned char* search;
488 unsigned char* end;
489 if (QUEUE_LEVEL == 0) /* has ended anyway */
490 return;
492 #if CONFIG_CPU == SH7034
493 CHCR3 &= ~0x0001; /* disable the DMA (and therefore the interrupt also) */
494 #endif /* CONFIG_CPU == SH7034 */
495 /* search next frame boundary and continue up to there */
496 pos = search = mp3_get_pos();
497 end = queue[queue_read].buf + queue[queue_read].len;
499 if (pos >= queue[queue_read].buf
500 && pos <= end) /* really our clip? */
501 { /* (for strange reasons this isn't nesessarily the case) */
502 /* find the next frame boundary */
503 while (search < end) /* search the remaining data */
505 if (*search++ != 0xFF) /* quick search for frame sync byte */
506 continue; /* (this does the majority of the job) */
508 /* look at the (bitswapped) rest of header candidate */
509 if (search[0] == curr_hd[0] /* do the quicker checks first */
510 && search[2] == curr_hd[2]
511 && (search[1] & 0x30) == (curr_hd[1] & 0x30)) /* sample rate */
513 search--; /* back to the sync byte */
514 break; /* From looking at it, this is our header. */
518 if (search-pos)
519 { /* play old data until the frame end, to keep the MAS in sync */
520 sent = search-pos;
522 queue_write = (queue_read + 1) & QUEUE_MASK; /* will be empty after next callback */
523 queue[queue_read].len = sent; /* current one ends after this */
525 #if CONFIG_CPU == SH7034
526 DTCR3 = sent; /* let the DMA finish this frame */
527 CHCR3 |= 0x0001; /* re-enable DMA */
528 #endif /* CONFIG_CPU == SH7034 */
529 thumbnail_buf_used = 0;
530 return;
533 #endif /* CONFIG_CODEC != SWCODEC */
535 /* Either SWCODEC, or MAS had nothing to do (was frame boundary or not our clip) */
536 mp3_play_stop();
537 talk_queue_lock();
538 queue_write = queue_read = 0; /* reset the queue */
539 thumbnail_buf_used = 0;
540 talk_queue_unlock();
541 need_shutup = false;
544 /* Shutup the voice, except if force_enqueue_next is set. */
545 void talk_shutup(void)
547 if (need_shutup && !force_enqueue_next)
548 talk_force_shutup();
551 /* schedule a clip, at the end or discard the existing queue */
552 static void queue_clip(unsigned char* buf, long size, bool enqueue)
554 int queue_level;
556 if (!enqueue)
557 talk_shutup(); /* cut off all the pending stuff */
558 /* Something is being enqueued, force_enqueue_next override is no
559 longer in effect. */
560 force_enqueue_next = false;
562 if (!size)
563 return; /* safety check */
564 #if CONFIG_CPU == SH7034
565 /* disable the DMA temporarily, to be safe of race condition */
566 CHCR3 &= ~0x0001;
567 #endif
568 talk_queue_lock();
569 queue_level = QUEUE_LEVEL; /* check old level */
571 if (queue_level < QUEUE_SIZE - 1) /* space left? */
573 queue[queue_write].buf = buf; /* populate an entry */
574 queue[queue_write].len = size;
575 queue_write = (queue_write + 1) & QUEUE_MASK;
577 talk_queue_unlock();
579 if (queue_level == 0)
580 { /* queue was empty, we have to do the initial start */
581 p_lastclip = buf;
582 #if CONFIG_CODEC != SWCODEC
583 sent = MIN(size, 0xFFFF); /* DMA can do no more */
584 #else
585 sent = size;
586 #endif
587 mp3_play_data(buf, sent, mp3_callback);
588 curr_hd[0] = buf[1];
589 curr_hd[1] = buf[2];
590 curr_hd[2] = buf[3];
591 mp3_play_pause(true); /* kickoff audio */
593 else
595 #if CONFIG_CPU == SH7034
596 CHCR3 |= 0x0001; /* re-enable DMA */
597 #endif
600 need_shutup = true;
602 return;
606 static void alloc_thumbnail_buf(void)
608 /* use the audio buffer now, need to release before loading a voice */
609 p_thumbnail = voicebuf;
610 size_for_thumbnail = MAX_THUMBNAIL_BUFSIZE;
611 thumbnail_buf_used = 0;
614 /* common code for talk_init() and talk_buffer_steal() */
615 static void reset_state(void)
617 queue_write = queue_read = 0; /* reset the queue */
618 p_voicefile = NULL; /* indicate no voicefile (trashed) */
619 p_thumbnail = NULL; /* no thumbnails either */
621 #ifdef TALK_PARTIAL_LOAD
622 int i;
623 for(i=0; i<QUEUE_SIZE; i++)
624 buffered_id[i] = -1;
625 #endif
627 p_silence = NULL; /* pause clip not accessible */
628 voicebuf = NULL;
632 /***************** Public implementation *****************/
634 void talk_init(void)
636 talk_temp_disable_count = 0;
637 if (talk_initialized && !strcasecmp(last_lang, global_settings.lang_file))
639 /* not a new file, nothing to do */
640 return;
643 #if defined(TALK_PROGRESSIVE_LOAD) || defined(TALK_PARTIAL_LOAD)
644 if (filehandle >= 0)
646 close(filehandle);
647 filehandle = -1;
649 #endif
651 #if CONFIG_CODEC == SWCODEC
652 if(!talk_initialized)
653 mutex_init(&queue_mutex);
654 #endif /* CONFIG_CODEC == SWCODEC */
656 talk_initialized = true;
657 strlcpy((char *)last_lang, (char *)global_settings.lang_file,
658 MAX_FILENAME);
660 filehandle = open_voicefile();
661 if (filehandle < 0) {
662 has_voicefile = false;
663 voicefile_size = 0;
664 return;
667 voicefile_size = filesize(filehandle);
669 audio_get_buffer(false, NULL); /* Must tell audio to reinitialize */
670 reset_state(); /* use this for most of our inits */
672 #ifdef TALK_PARTIAL_LOAD
673 size_t bufsize;
674 char* buf = plugin_get_buffer(&bufsize);
675 /* we won't load the full file, we only need the index */
676 load_voicefile(true, buf, bufsize);
677 if (!p_voicefile)
678 return;
680 unsigned clips = p_voicefile->id1_max + p_voicefile->id2_max;
681 unsigned i;
682 int silence_size = 0;
684 for(i=0; i<clips; i++) {
685 int size = p_voicefile->index[i].size;
686 if (size > max_clipsize)
687 max_clipsize = size;
688 if (i == VOICE_PAUSE)
689 silence_size = size;
692 voicefile_size = p_voicefile->table + clips * sizeof(struct clip_entry);
693 voicefile_size += max_clipsize * QUEUE_SIZE + silence_size;
694 p_voicefile = NULL; /* Don't pretend we can load talk clips just yet */
695 #endif
698 /* test if we can open and if it fits in the audiobuffer */
699 size_t audiobufsz = buffer_available();
700 if (voicefile_size <= audiobufsz) {
701 has_voicefile = true;
702 } else {
703 has_voicefile = false;
704 voicefile_size = 0;
707 alloc_thumbnail_buf();
708 close(filehandle); /* close again, this was just to detect presence */
709 filehandle = -1;
712 #if CONFIG_CODEC == SWCODEC
713 /* return if a voice codec is required or not */
714 bool talk_voice_required(void)
716 return (voicefile_size != 0) /* Voice file is available */
717 || (global_settings.talk_dir_clip) /* Thumbnail clips are required */
718 || (global_settings.talk_file_clip);
720 #endif
722 /* return size of voice file */
723 int talk_get_buffer(void)
725 int ret = voicefile_size;
726 #if CONFIG_CODEC == SWCODEC
727 ret += MAX_THUMBNAIL_BUFSIZE;
728 #endif
729 return ret;
732 /* Sets the buffer for the voicefile and returns how many bytes of this
733 * buffer we will use for the voicefile */
734 size_t talkbuf_init(char *bufstart)
736 bool changed = voicebuf != bufstart;
738 if (changed) /* must reload voice file */
739 reset_state();
740 if (bufstart)
741 voicebuf = bufstart;
743 return talk_get_buffer();
746 /* somebody else claims the mp3 buffer, e.g. for regular play/record */
747 void talk_buffer_steal(void)
749 #if CONFIG_CODEC != SWCODEC
750 mp3_play_stop();
751 #endif
752 #if defined(TALK_PROGRESSIVE_LOAD) || defined(TALK_PARTIAL_LOAD)
753 if (filehandle >= 0)
755 close(filehandle);
756 filehandle = -1;
758 #endif
759 reset_state();
763 /* play a voice ID from voicefile */
764 int talk_id(int32_t id, bool enqueue)
766 long clipsize;
767 unsigned char* clipbuf;
768 int32_t unit;
769 int decimals;
771 if (talk_temp_disable_count > 0)
772 return -1; /* talking has been disabled */
773 #if CONFIG_CODEC != SWCODEC
774 if (audio_status()) /* busy, buffer in use */
775 return -1;
776 #endif
778 if (p_voicefile == NULL && has_voicefile)
779 load_voicefile(false, voicebuf, voicefile_size); /* reload needed */
781 if (p_voicefile == NULL) /* still no voices? */
782 return -1;
784 if (id == -1) /* -1 is an indication for silence */
785 return -1;
787 decimals = (((uint32_t)id) >> DECIMAL_SHIFT) & 0x7;
789 /* check if this is a special ID, with a value */
790 unit = ((uint32_t)id) >> UNIT_SHIFT;
791 if (unit || decimals)
792 { /* sign-extend the value */
793 id = (uint32_t)id << (32-DECIMAL_SHIFT);
794 id >>= (32-DECIMAL_SHIFT);
796 talk_value_decimal(id, unit, decimals, enqueue); /* speak it */
797 return 0; /* and stop, end of special case */
800 clipbuf = get_clip(id, &clipsize);
801 if (clipbuf == NULL)
802 return -1; /* not present */
804 #ifdef LOGF_ENABLE
805 if (id > VOICEONLY_DELIMITER)
806 logf("\ntalk_id: Say voice clip 0x%x\n", id);
807 else
808 logf("\ntalk_id: Say '%s'\n", str(id));
809 #endif
811 queue_clip(clipbuf, clipsize, enqueue);
813 return 0;
815 /* Speaks zero or more IDs (from an array). */
816 int talk_idarray(const long *ids, bool enqueue)
818 int r;
819 if(!ids)
820 return 0;
821 while(*ids != TALK_FINAL_ID)
823 if((r = talk_id(*ids++, enqueue)) <0)
824 return r;
825 enqueue = true;
827 return 0;
830 /* Make sure the current utterance is not interrupted by the next one. */
831 void talk_force_enqueue_next(void)
833 force_enqueue_next = true;
836 /* play a thumbnail from file */
837 /* Returns size of spoken thumbnail, so >0 means something is spoken,
838 <=0 means something went wrong. */
839 static int _talk_file(const char* filename,
840 const long *prefix_ids, bool enqueue)
842 int fd;
843 int size;
844 int thumb_used;
845 #if CONFIG_CODEC != SWCODEC
846 struct mp3entry info;
847 #endif
849 if (talk_temp_disable_count > 0)
850 return -1; /* talking has been disabled */
851 #if CONFIG_CODEC != SWCODEC
852 if (audio_status()) /* busy, buffer in use */
853 return -1;
854 #endif
856 if (p_thumbnail == NULL || size_for_thumbnail <= 0)
857 alloc_thumbnail_buf();
859 #if CONFIG_CODEC != SWCODEC
860 if(mp3info(&info, filename)) /* use this to find real start */
862 return 0; /* failed to open, or invalid */
864 #endif
866 if (!enqueue)
867 /* shutup now to free the thumbnail buffer */
868 talk_shutup();
870 fd = open(filename, O_RDONLY);
871 if (fd < 0) /* failed to open */
873 return 0;
876 thumb_used = thumbnail_buf_used;
877 if(filesize(fd) > size_for_thumbnail -thumb_used)
878 { /* Don't play truncated clips */
879 close(fd);
880 return 0;
883 #if CONFIG_CODEC != SWCODEC
884 lseek(fd, info.first_frame_offset, SEEK_SET); /* behind ID data */
885 #endif
887 size = read(fd, p_thumbnail +thumb_used,
888 size_for_thumbnail -thumb_used);
889 close(fd);
891 /* ToDo: find audio, skip ID headers and trailers */
893 if (size > 0) /* Don't play missing clips */
895 #if CONFIG_CODEC != SWCODEC && !defined(SIMULATOR)
896 bitswap(p_thumbnail, size);
897 #endif
898 if(prefix_ids)
899 /* prefix thumbnail by speaking these ids, but only now
900 that we know there's actually a thumbnail to be
901 spoken. */
902 talk_idarray(prefix_ids, true);
903 talk_queue_lock();
904 thumbnail_buf_used = thumb_used +size;
905 talk_queue_unlock();
906 queue_clip(p_thumbnail +thumb_used, size, true);
909 return size;
912 int talk_file(const char *root, const char *dir, const char *file,
913 const char *ext, const long *prefix_ids, bool enqueue)
914 /* Play a thumbnail file */
916 char buf[MAX_PATH];
917 /* Does root end with a slash */
918 char *slash = (root && root[0]
919 && root[strlen(root)-1] != '/') ? "/" : "";
920 snprintf(buf, MAX_PATH, "%s%s%s%s%s%s",
921 root ? root : "", slash,
922 dir ? dir : "", dir ? "/" : "",
923 file ? file : "",
924 ext ? ext : "");
925 return _talk_file(buf, prefix_ids, enqueue);
928 static int talk_spell_basename(const char *path,
929 const long *prefix_ids, bool enqueue)
931 if(prefix_ids)
933 talk_idarray(prefix_ids, enqueue);
934 enqueue = true;
936 char buf[MAX_PATH];
937 /* Spell only the path component after the last slash */
938 strlcpy(buf, path, sizeof(buf));
939 if(strlen(buf) >1 && buf[strlen(buf)-1] == '/')
940 /* strip trailing slash */
941 buf[strlen(buf)-1] = '\0';
942 char *ptr = strrchr(buf, '/');
943 if(ptr && strlen(buf) >1)
944 ++ptr;
945 else ptr = buf;
946 return talk_spell(ptr, enqueue);
949 /* Play a file's .talk thumbnail, fallback to spelling the filename, or
950 go straight to spelling depending on settings. */
951 int talk_file_or_spell(const char *dirname, const char *filename,
952 const long *prefix_ids, bool enqueue)
954 if (global_settings.talk_file_clip)
955 { /* .talk clips enabled */
956 if(talk_file(dirname, NULL, filename, file_thumbnail_ext,
957 prefix_ids, enqueue) >0)
958 return 0;
960 if (global_settings.talk_file == 2)
961 /* Either .talk clips are disabled, or as a fallback */
962 return talk_spell_basename(filename, prefix_ids, enqueue);
963 return 0;
966 /* Play a directory's .talk thumbnail, fallback to spelling the filename, or
967 go straight to spelling depending on settings. */
968 int talk_dir_or_spell(const char* dirname,
969 const long *prefix_ids, bool enqueue)
971 if (global_settings.talk_dir_clip)
972 { /* .talk clips enabled */
973 if(talk_file(dirname, NULL, dir_thumbnail_name, NULL,
974 prefix_ids, enqueue) >0)
975 return 0;
977 if (global_settings.talk_dir == 2)
978 /* Either .talk clips disabled or as a fallback */
979 return talk_spell_basename(dirname, prefix_ids, enqueue);
980 return 0;
983 /* say a numeric value, this word ordering works for english,
984 but not necessarily for other languages (e.g. german) */
985 int talk_number(long n, bool enqueue)
987 int level = 2; /* mille count */
988 long mil = 1000000000; /* highest possible "-illion" */
990 if (talk_temp_disable_count > 0)
991 return -1; /* talking has been disabled */
992 #if CONFIG_CODEC != SWCODEC
993 if (audio_status()) /* busy, buffer in use */
994 return -1;
995 #endif
997 if (!enqueue)
998 talk_shutup(); /* cut off all the pending stuff */
1000 if (n==0)
1001 { /* special case */
1002 talk_id(VOICE_ZERO, true);
1003 return 0;
1006 if (n<0)
1008 talk_id(VOICE_MINUS, true);
1009 n = -n;
1012 while (n)
1014 int segment = n / mil; /* extract in groups of 3 digits */
1015 n -= segment * mil; /* remove the used digits from number */
1016 mil /= 1000; /* digit place for next round */
1018 if (segment)
1020 int hundreds = segment / 100;
1021 int ones = segment % 100;
1023 if (hundreds)
1025 talk_id(VOICE_ZERO + hundreds, true);
1026 talk_id(VOICE_HUNDRED, true);
1029 /* combination indexing */
1030 if (ones > 20)
1032 int tens = ones/10 + 18;
1033 talk_id(VOICE_ZERO + tens, true);
1034 ones %= 10;
1037 /* direct indexing */
1038 if (ones)
1039 talk_id(VOICE_ZERO + ones, true);
1041 /* add billion, million, thousand */
1042 if (mil)
1043 talk_id(VOICE_THOUSAND + level, true);
1045 level--;
1048 return 0;
1051 /* Say time duration/interval. Input is time in seconds,
1052 say hours,minutes,seconds. */
1053 static int talk_time_unit(long secs, bool enqueue)
1055 int hours, mins;
1056 if (!enqueue)
1057 talk_shutup();
1058 if((hours = secs/3600)) {
1059 secs %= 3600;
1060 talk_value(hours, UNIT_HOUR, true);
1062 if((mins = secs/60)) {
1063 secs %= 60;
1064 talk_value(mins, UNIT_MIN, true);
1066 if((secs) || (!hours && !mins))
1067 talk_value(secs, UNIT_SEC, true);
1068 else if(!hours && secs)
1069 talk_number(secs, true);
1070 return 0;
1073 void talk_fractional(char *tbuf, int value, int unit)
1075 int i;
1076 /* strip trailing zeros from the fraction */
1077 for (i = strlen(tbuf) - 1; (i >= 0) && (tbuf[i] == '0'); i--)
1078 tbuf[i] = '\0';
1080 talk_number(value, true);
1081 if (tbuf[0] != 0)
1083 talk_id(LANG_POINT, true);
1084 talk_spell(tbuf, true);
1086 talk_id(unit, true);
1089 int talk_value(long n, int unit, bool enqueue)
1091 return talk_value_decimal(n, unit, 0, enqueue);
1094 /* singular/plural aware saying of a value */
1095 int talk_value_decimal(long n, int unit, int decimals, bool enqueue)
1097 int unit_id;
1098 static const int unit_voiced[] =
1099 { /* lookup table for the voice ID of the units */
1100 [0 ... UNIT_LAST-1] = -1, /* regular ID, int, signed */
1101 [UNIT_MS]
1102 = VOICE_MILLISECONDS, /* here come the "real" units */
1103 [UNIT_SEC]
1104 = VOICE_SECONDS,
1105 [UNIT_MIN]
1106 = VOICE_MINUTES,
1107 [UNIT_HOUR]
1108 = VOICE_HOURS,
1109 [UNIT_KHZ]
1110 = VOICE_KHZ,
1111 [UNIT_DB]
1112 = VOICE_DB,
1113 [UNIT_PERCENT]
1114 = VOICE_PERCENT,
1115 [UNIT_MAH]
1116 = VOICE_MILLIAMPHOURS,
1117 [UNIT_PIXEL]
1118 = VOICE_PIXEL,
1119 [UNIT_PER_SEC]
1120 = VOICE_PER_SEC,
1121 [UNIT_HERTZ]
1122 = VOICE_HERTZ,
1123 [UNIT_MB]
1124 = LANG_MEGABYTE,
1125 [UNIT_KBIT]
1126 = VOICE_KBIT_PER_SEC,
1127 [UNIT_PM_TICK]
1128 = VOICE_PM_UNITS_PER_TICK,
1131 static const int pow10[] = { /* 10^0 - 10^7 */
1132 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000
1135 char tbuf[8];
1136 char fmt[] = "%0nd";
1138 if (talk_temp_disable_count > 0)
1139 return -1; /* talking has been disabled */
1140 #if CONFIG_CODEC != SWCODEC
1141 if (audio_status()) /* busy, buffer in use */
1142 return -1;
1143 #endif
1145 /* special case for time duration */
1146 if (unit == UNIT_TIME)
1147 return talk_time_unit(n, enqueue);
1149 if (unit < 0 || unit >= UNIT_LAST)
1150 unit_id = -1;
1151 else
1152 unit_id = unit_voiced[unit];
1154 if ((n==1 || n==-1) /* singular? */
1155 && unit_id >= VOICE_SECONDS && unit_id <= VOICE_HOURS)
1157 unit_id--; /* use the singular for those units which have */
1160 /* special case with a "plus" before */
1161 if (n > 0 && (unit == UNIT_SIGNED || unit == UNIT_DB))
1163 talk_id(VOICE_PLUS, enqueue);
1164 enqueue = true;
1167 if (decimals)
1169 /* needed for the "-0.5" corner case */
1170 if (n < 0)
1172 talk_id(VOICE_MINUS, enqueue);
1173 n = -n;
1176 fmt[2] = '0' + decimals;
1178 snprintf(tbuf, sizeof(tbuf), fmt, n % pow10[decimals]);
1179 talk_fractional(tbuf, n / pow10[decimals], unit_id);
1181 return 0;
1184 talk_number(n, enqueue); /* say the number */
1185 talk_id(unit_id, true); /* say the unit, if any */
1187 return 0;
1190 /* spell a string */
1191 int talk_spell(const char* spell, bool enqueue)
1193 char c; /* currently processed char */
1195 if (talk_temp_disable_count > 0)
1196 return -1; /* talking has been disabled */
1197 #if CONFIG_CODEC != SWCODEC
1198 if (audio_status()) /* busy, buffer in use */
1199 return -1;
1200 #endif
1202 if (!enqueue)
1203 talk_shutup(); /* cut off all the pending stuff */
1205 while ((c = *spell++) != '\0')
1207 /* if this grows into too many cases, I should use a table */
1208 if (c >= 'A' && c <= 'Z')
1209 talk_id(VOICE_CHAR_A + c - 'A', true);
1210 else if (c >= 'a' && c <= 'z')
1211 talk_id(VOICE_CHAR_A + c - 'a', true);
1212 else if (c >= '0' && c <= '9')
1213 talk_id(VOICE_ZERO + c - '0', true);
1214 else if (c == '-')
1215 talk_id(VOICE_MINUS, true);
1216 else if (c == '+')
1217 talk_id(VOICE_PLUS, true);
1218 else if (c == '.')
1219 talk_id(VOICE_DOT, true);
1220 else if (c == ' ')
1221 talk_id(VOICE_PAUSE, true);
1222 else if (c == '/')
1223 talk_id(VOICE_CHAR_SLASH, true);
1226 return 0;
1229 void talk_disable(bool disable)
1231 if (disable)
1232 talk_temp_disable_count++;
1233 else
1234 talk_temp_disable_count--;
1237 void talk_setting(const void *global_settings_variable)
1239 const struct settings_list *setting;
1240 if (!global_settings.talk_menu)
1241 return;
1242 setting = find_setting(global_settings_variable, NULL);
1243 if (setting == NULL)
1244 return;
1245 if (setting->lang_id)
1246 talk_id(setting->lang_id,false);
1250 #if CONFIG_RTC
1251 void talk_date(const struct tm *tm, bool enqueue)
1253 talk_id(LANG_MONTH_JANUARY + tm->tm_mon, enqueue);
1254 talk_number(tm->tm_mday, true);
1255 talk_number(1900 + tm->tm_year, true);
1258 void talk_time(const struct tm *tm, bool enqueue)
1260 if (global_settings.timeformat == 1)
1262 /* Voice the hour */
1263 long am_pm_id = VOICE_AM;
1264 int hour = tm->tm_hour;
1265 if (hour >= 12)
1267 am_pm_id = VOICE_PM;
1268 hour -= 12;
1270 if (hour == 0)
1271 hour = 12;
1272 talk_number(hour, enqueue);
1274 /* Voice the minutes */
1275 if (tm->tm_min == 0)
1277 /* Say o'clock if the minute is 0. */
1278 talk_id(VOICE_OCLOCK, true);
1280 else
1282 /* Pronounce the leading 0 */
1283 if(tm->tm_min < 10)
1284 talk_id(VOICE_OH, true);
1285 talk_number(tm->tm_min, true);
1287 talk_id(am_pm_id, true);
1289 else
1291 /* Voice the time in 24 hour format */
1292 talk_number(tm->tm_hour, enqueue);
1293 if (tm->tm_min == 0)
1295 talk_id(VOICE_HUNDRED, true);
1296 talk_id(VOICE_HOUR, true);
1298 else
1300 /* Pronounce the leading 0 */
1301 if(tm->tm_min < 10)
1302 talk_id(VOICE_OH, true);
1303 talk_number(tm->tm_min, true);
1308 #endif /* CONFIG_RTC */