Added old.t
[kugel-rb.git] / apps / talk.c
blobc7e2e035fd6f30ef8e63990dbfc7f0d1a54138c0
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 * All files in this archive are subject to the GNU General Public License.
17 * See the file COPYING in the source tree root for full license agreement.
19 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
20 * KIND, either express or implied.
22 ****************************************************************************/
24 #include <stdio.h>
25 #include <stddef.h>
26 #include <string.h>
27 #include "file.h"
28 #include "buffer.h"
29 #include "system.h"
30 #include "settings.h"
31 #include "mp3_playback.h"
32 #include "audio.h"
33 #include "lang.h"
34 #include "talk.h"
35 #include "id3.h"
36 #include "logf.h"
37 #include "bitswap.h"
38 #if CONFIG_CODEC == SWCODEC
39 #include "playback.h"
40 #endif
42 /***************** Constants *****************/
44 #define QUEUE_SIZE 64 /* must be a power of two */
45 #define QUEUE_MASK (QUEUE_SIZE-1)
46 const char* const dir_thumbnail_name = "_dirname.talk";
47 const char* const file_thumbnail_ext = ".talk";
49 /***************** Functional Macros *****************/
51 #define QUEUE_LEVEL ((queue_write - queue_read) & QUEUE_MASK)
53 #define LOADED_MASK 0x80000000 /* MSB */
56 /***************** Data types *****************/
58 struct clip_entry /* one entry of the index table */
60 int offset; /* offset from start of voicefile file */
61 int size; /* size of the clip */
64 struct voicefile /* file format of our voice file */
66 int version; /* version of the voicefile */
67 int table; /* offset to index table, (=header size) */
68 int id1_max; /* number of "normal" clips contained in above index */
69 int id2_max; /* number of "voice only" clips contained in above index */
70 struct clip_entry index[]; /* followed by the index tables */
71 /* and finally the bitswapped mp3 clips, not visible here */
74 struct queue_entry /* one entry of the internal queue */
76 unsigned char* buf;
77 long len;
81 /***************** Globals *****************/
83 static unsigned char* p_thumbnail; /* buffer for thumbnail */
84 static long size_for_thumbnail; /* leftover buffer size for it */
85 static struct voicefile* p_voicefile; /* loaded voicefile */
86 static bool has_voicefile; /* a voicefile file is present */
87 static struct queue_entry queue[QUEUE_SIZE]; /* queue of scheduled clips */
88 static int queue_write; /* write index of queue, by application */
89 static int queue_read; /* read index of queue, by ISR context */
90 static int sent; /* how many bytes handed over to playback, owned by ISR */
91 static unsigned char curr_hd[3]; /* current frame header, for re-sync */
92 static int filehandle; /* global, so the MMC variant can keep the file open */
93 static unsigned char* p_silence; /* VOICE_PAUSE clip, used for termination */
94 static long silence_len; /* length of the VOICE_PAUSE clip */
95 static unsigned char* p_lastclip; /* address of latest clip, for silence add */
96 static unsigned long voicefile_size = 0; /* size of the loaded voice file */
97 static unsigned char last_lang[MAX_FILENAME+1]; /* name of last used lang file (in talk_init) */
98 static bool talk_initialized; /* true if talk_init has been called */
100 /***************** Private prototypes *****************/
102 static void load_voicefile(void);
103 static void mp3_callback(unsigned char** start, int* size);
104 static int shutup(void);
105 static int queue_clip(unsigned char* buf, long size, bool enqueue);
106 static int open_voicefile(void);
107 static unsigned char* get_clip(long id, long* p_size);
110 /***************** Private implementation *****************/
112 static int open_voicefile(void)
114 char buf[64];
115 char* p_lang = "english"; /* default */
117 if ( global_settings.lang_file[0] &&
118 global_settings.lang_file[0] != 0xff )
119 { /* try to open the voice file of the selected language */
120 p_lang = (char *)global_settings.lang_file;
123 snprintf(buf, sizeof(buf), ROCKBOX_DIR LANG_DIR "/%s.voice", p_lang);
125 return open(buf, O_RDONLY);
128 int talk_get_bufsize(void)
130 return voicefile_size;
133 #ifdef SIMULATOR
134 static unsigned short BSWAP16(unsigned short value)
136 return (value >> 8) | (value << 8);
139 static unsigned long BSWAP32(unsigned long value)
141 unsigned long hi = BSWAP16(value >> 16);
142 unsigned long lo = BSWAP16(value & 0xffff);
143 return (lo << 16) | hi;
145 #endif
147 /* load the voice file into the mp3 buffer */
148 static void load_voicefile(void)
150 int load_size;
151 int got_size;
152 int file_size;
153 #if CONFIG_CODEC == SWCODEC
154 int length, i;
155 unsigned char *buf, temp;
156 #endif
158 filehandle = open_voicefile();
159 if (filehandle < 0) /* failed to open */
160 goto load_err;
162 file_size = filesize(filehandle);
163 if (file_size > audiobufend - audiobuf) /* won't fit? */
164 goto load_err;
166 #ifdef HAVE_MMC /* load only the header for now */
167 load_size = offsetof(struct voicefile, index);
168 #else /* load the full file */
169 load_size = file_size;
170 #endif
172 got_size = read(filehandle, audiobuf, load_size);
173 if (got_size != load_size /* failure */)
174 goto load_err;
176 #ifdef SIMULATOR
177 logf("Byte swapping voice file");
178 p_voicefile = (struct voicefile*)audiobuf;
179 p_voicefile->version = BSWAP32(p_voicefile->version);
180 p_voicefile->table = BSWAP32(p_voicefile->table);
181 p_voicefile->id1_max = BSWAP32(p_voicefile->id1_max);
182 p_voicefile->id2_max = BSWAP32(p_voicefile->id2_max);
183 p_voicefile = NULL;
184 #endif
186 if (((struct voicefile*)audiobuf)->table /* format check */
187 == offsetof(struct voicefile, index))
189 p_voicefile = (struct voicefile*)audiobuf;
191 /* thumbnail buffer is the remaining space behind */
192 p_thumbnail = audiobuf + file_size;
193 p_thumbnail += (long)p_thumbnail % 2; /* 16-bit align */
194 size_for_thumbnail = audiobufend - p_thumbnail;
196 else
197 goto load_err;
199 #ifdef SIMULATOR
200 for (i = 0; i < p_voicefile->id1_max + p_voicefile->id2_max; i++)
202 struct clip_entry *ce;
203 ce = &p_voicefile->index[i];
204 ce->offset = BSWAP32(ce->offset);
205 ce->size = BSWAP32(ce->size);
207 #endif
209 /* Do a bitswap as necessary. */
210 #if CONFIG_CODEC == SWCODEC
211 logf("Bitswapping voice file.");
212 cpu_boost(true);
213 buf = (unsigned char *)(&p_voicefile->index) +
214 (p_voicefile->id1_max + p_voicefile->id2_max) * sizeof(struct clip_entry);
215 length = file_size - (buf - audiobuf);
217 for (i = 0; i < length; i++)
219 temp = buf[i];
220 temp = ((temp >> 4) & 0x0f) | ((temp & 0x0f) << 4);
221 temp = ((temp >> 2) & 0x33) | ((temp & 0x33) << 2);
222 buf[i] = ((temp >> 1) & 0x55) | ((temp & 0x55) << 1);
224 cpu_boost(false);
226 #endif
228 #ifdef HAVE_MMC
229 /* load the index table, now that we know its size from the header */
230 load_size = (p_voicefile->id1_max + p_voicefile->id2_max)
231 * sizeof(struct clip_entry);
232 got_size = read(filehandle,
233 audiobuf + offsetof(struct voicefile, index), load_size);
234 if (got_size != load_size) /* read error */
235 goto load_err;
236 #else
237 close(filehandle); /* only the MMC variant leaves it open */
238 filehandle = -1;
239 #endif
241 /* make sure to have the silence clip, if available */
242 p_silence = get_clip(VOICE_PAUSE, &silence_len);
244 return;
246 load_err:
247 p_voicefile = NULL;
248 has_voicefile = false; /* don't try again */
249 if (filehandle >= 0)
251 close(filehandle);
252 filehandle = -1;
254 return;
258 /* called in ISR context if mp3 data got consumed */
259 static void mp3_callback(unsigned char** start, int* size)
261 queue[queue_read].len -= sent; /* we completed this */
262 queue[queue_read].buf += sent;
264 if (queue[queue_read].len > 0) /* current clip not finished? */
265 { /* feed the next 64K-1 chunk */
266 #if CONFIG_CODEC != SWCODEC
267 sent = MIN(queue[queue_read].len, 0xFFFF);
268 #else
269 sent = queue[queue_read].len;
270 #endif
271 *start = queue[queue_read].buf;
272 *size = sent;
273 return;
275 else if (sent > 0) /* go to next entry */
277 queue_read = (queue_read + 1) & QUEUE_MASK;
280 re_check:
282 if (QUEUE_LEVEL) /* queue is not empty? */
283 { /* start next clip */
284 #if CONFIG_CODEC != SWCODEC
285 sent = MIN(queue[queue_read].len, 0xFFFF);
286 #else
287 sent = queue[queue_read].len;
288 #endif
289 *start = p_lastclip = queue[queue_read].buf;
290 *size = sent;
291 curr_hd[0] = p_lastclip[1];
292 curr_hd[1] = p_lastclip[2];
293 curr_hd[2] = p_lastclip[3];
295 else if (p_silence != NULL /* silence clip available */
296 && p_lastclip != p_silence /* previous clip wasn't silence */
297 && p_lastclip < p_thumbnail) /* ..and not a thumbnail */
298 { /* add silence clip when queue runs empty playing a voice clip */
299 queue[queue_write].buf = p_silence;
300 queue[queue_write].len = silence_len;
301 queue_write = (queue_write + 1) & QUEUE_MASK;
303 goto re_check;
305 else
307 *size = 0; /* end of data */
308 mp3_play_stop(); /* fixme: should be done by caller */
312 /* stop the playback and the pending clips, but at frame boundary */
313 static int shutup(void)
315 unsigned char* pos;
316 unsigned char* search;
317 unsigned char* end;
319 if (QUEUE_LEVEL == 0) /* has ended anyway */
321 return 0;
323 #if CONFIG_CPU == SH7034
324 CHCR3 &= ~0x0001; /* disable the DMA (and therefore the interrupt also) */
325 #endif
326 /* search next frame boundary and continue up to there */
327 pos = search = mp3_get_pos();
328 end = queue[queue_read].buf + queue[queue_read].len;
330 if (pos >= queue[queue_read].buf
331 && pos <= end) /* really our clip? */
332 { /* (for strange reasons this isn't nesessarily the case) */
333 /* find the next frame boundary */
334 while (search < end) /* search the remaining data */
336 if (*search++ != 0xFF) /* quick search for frame sync byte */
337 continue; /* (this does the majority of the job) */
339 /* look at the (bitswapped) rest of header candidate */
340 if (search[0] == curr_hd[0] /* do the quicker checks first */
341 && search[2] == curr_hd[2]
342 && (search[1] & 0x30) == (curr_hd[1] & 0x30)) /* sample rate */
344 search--; /* back to the sync byte */
345 break; /* From looking at it, this is our header. */
349 if (search-pos)
350 { /* play old data until the frame end, to keep the MAS in sync */
351 sent = search-pos;
353 queue_write = (queue_read + 1) & QUEUE_MASK; /* will be empty after next callback */
354 queue[queue_read].len = sent; /* current one ends after this */
356 #if CONFIG_CPU == SH7034
357 DTCR3 = sent; /* let the DMA finish this frame */
358 CHCR3 |= 0x0001; /* re-enable DMA */
359 #endif
360 return 0;
364 /* nothing to do, was frame boundary or not our clip */
365 mp3_play_stop();
366 queue_write = queue_read = 0; /* reset the queue */
368 return 0;
372 /* schedule a clip, at the end or discard the existing queue */
373 static int queue_clip(unsigned char* buf, long size, bool enqueue)
375 int queue_level;
377 if (!enqueue)
378 shutup(); /* cut off all the pending stuff */
380 if (!size)
381 return 0; /* safety check */
382 #if CONFIG_CPU == SH7034
383 /* disable the DMA temporarily, to be safe of race condition */
384 CHCR3 &= ~0x0001;
385 #endif
386 queue_level = QUEUE_LEVEL; /* check old level */
388 if (queue_level < QUEUE_SIZE - 1) /* space left? */
390 queue[queue_write].buf = buf; /* populate an entry */
391 queue[queue_write].len = size;
392 queue_write = (queue_write + 1) & QUEUE_MASK;
395 if (queue_level == 0)
396 { /* queue was empty, we have to do the initial start */
397 p_lastclip = buf;
398 #if CONFIG_CODEC != SWCODEC
399 sent = MIN(size, 0xFFFF); /* DMA can do no more */
400 #else
401 sent = size;
402 #endif
403 mp3_play_data(buf, sent, mp3_callback);
404 curr_hd[0] = buf[1];
405 curr_hd[1] = buf[2];
406 curr_hd[2] = buf[3];
407 mp3_play_pause(true); /* kickoff audio */
409 else
411 #if CONFIG_CPU == SH7034
412 CHCR3 |= 0x0001; /* re-enable DMA */
413 #endif
416 return 0;
419 /* fetch a clip from the voice file */
420 static unsigned char* get_clip(long id, long* p_size)
422 long clipsize;
423 unsigned char* clipbuf;
425 if (id > VOICEONLY_DELIMITER)
426 { /* voice-only entries use the second part of the table */
427 id -= VOICEONLY_DELIMITER + 1;
428 if (id >= p_voicefile->id2_max)
429 return NULL; /* must be newer than we have */
430 id += p_voicefile->id1_max; /* table 2 is behind table 1 */
432 else
433 { /* normal use of the first table */
434 if (id >= p_voicefile->id1_max)
435 return NULL; /* must be newer than we have */
438 clipsize = p_voicefile->index[id].size;
439 if (clipsize == 0) /* clip not included in voicefile */
440 return NULL;
441 clipbuf = audiobuf + p_voicefile->index[id].offset;
443 #ifdef HAVE_MMC /* dynamic loading, on demand */
444 if (!(clipsize & LOADED_MASK))
445 { /* clip used for the first time, needs loading */
446 lseek(filehandle, p_voicefile->index[id].offset, SEEK_SET);
447 if (read(filehandle, clipbuf, clipsize) != clipsize)
448 return NULL; /* read error */
450 p_voicefile->index[id].size |= LOADED_MASK; /* mark as loaded */
452 else
453 { /* clip is in memory already */
454 clipsize &= ~LOADED_MASK; /* without the extra bit gives true size */
456 #endif
458 *p_size = clipsize;
459 return clipbuf;
463 /* common code for talk_init() and talk_buffer_steal() */
464 static void reset_state(void)
466 queue_write = queue_read = 0; /* reset the queue */
467 p_voicefile = NULL; /* indicate no voicefile (trashed) */
468 p_thumbnail = audiobuf; /* whole space for thumbnail */
469 size_for_thumbnail = audiobufend - audiobuf;
470 p_silence = NULL; /* pause clip not accessible */
473 /***************** Public implementation *****************/
475 void talk_init(void)
477 if (talk_initialized && !strcasecmp(last_lang, global_settings.lang_file))
479 /* not a new file, nothing to do */
480 return;
483 talk_initialized = true;
484 strncpy((char *) last_lang, (char *)global_settings.lang_file,
485 MAX_FILENAME);
487 #if CONFIG_CODEC == SWCODEC
488 audio_stop();
489 #endif
490 reset_state(); /* use this for most of our inits */
492 #ifdef HAVE_MMC
493 load_voicefile(); /* load the tables right away */
494 has_voicefile = (p_voicefile != NULL);
495 #else
496 filehandle = open_voicefile();
497 has_voicefile = (filehandle >= 0); /* test if we can open it */
498 voicefile_size = 0;
500 if (has_voicefile)
502 voicefile_size = filesize(filehandle);
503 #if CONFIG_CODEC == SWCODEC
504 voice_init();
505 #endif
506 close(filehandle); /* close again, this was just to detect presence */
507 filehandle = -1;
509 #endif
514 /* somebody else claims the mp3 buffer, e.g. for regular play/record */
515 int talk_buffer_steal(void)
517 mp3_play_stop();
518 #ifdef HAVE_MMC
519 if (filehandle >= 0) /* only relevant for MMC */
521 close(filehandle);
522 filehandle = -1;
524 #endif
525 reset_state();
526 return 0;
530 /* play a voice ID from voicefile */
531 int talk_id(long id, bool enqueue)
533 long clipsize;
534 unsigned char* clipbuf;
535 int unit;
537 #if CONFIG_CODEC != SWCODEC
538 if (audio_status()) /* busy, buffer in use */
539 return -1;
540 #endif
542 if (p_voicefile == NULL && has_voicefile)
543 load_voicefile(); /* reload needed */
545 if (p_voicefile == NULL) /* still no voices? */
546 return -1;
548 if (id == -1) /* -1 is an indication for silence */
549 return -1;
551 /* check if this is a special ID, with a value */
552 unit = ((unsigned long)id) >> UNIT_SHIFT;
553 if (unit)
554 { /* sign-extend the value */
555 id = (unsigned long)id << (32-UNIT_SHIFT);
556 id >>= (32-UNIT_SHIFT);
557 talk_value(id, unit, enqueue); /* speak it */
558 return 0; /* and stop, end of special case */
561 clipbuf = get_clip(id, &clipsize);
562 if (clipbuf == NULL)
563 return -1; /* not present */
565 queue_clip(clipbuf, clipsize, enqueue);
567 return 0;
571 /* play a thumbnail from file */
572 int talk_file(const char* filename, bool enqueue)
574 int fd;
575 int size;
576 struct mp3entry info;
578 if (audio_status()) /* busy, buffer in use */
579 return -1;
581 if (p_thumbnail == NULL || size_for_thumbnail <= 0)
582 return -1;
584 if(mp3info(&info, filename, false)) /* use this to find real start */
586 return 0; /* failed to open, or invalid */
589 fd = open(filename, O_RDONLY);
590 if (fd < 0) /* failed to open */
592 return 0;
595 lseek(fd, info.first_frame_offset, SEEK_SET); /* behind ID data */
597 size = read(fd, p_thumbnail, size_for_thumbnail);
598 close(fd);
600 /* ToDo: find audio, skip ID headers and trailers */
602 if (size)
604 #if CONFIG_CODEC != SWCODEC
605 bitswap(p_thumbnail, size);
606 #endif
607 queue_clip(p_thumbnail, size, enqueue);
610 return size;
614 /* say a numeric value, this word ordering works for english,
615 but not necessarily for other languages (e.g. german) */
616 int talk_number(long n, bool enqueue)
618 int level = 0; /* mille count */
619 long mil = 1000000000; /* highest possible "-illion" */
621 #if CONFIG_CODEC != SWCODEC
622 if (audio_status()) /* busy, buffer in use */
623 return -1;
624 #endif
626 if (!enqueue)
627 shutup(); /* cut off all the pending stuff */
629 if (n==0)
630 { /* special case */
631 talk_id(VOICE_ZERO, true);
632 return 0;
635 if (n<0)
637 talk_id(VOICE_MINUS, true);
638 n = -n;
641 while (n)
643 int segment = n / mil; /* extract in groups of 3 digits */
644 n -= segment * mil; /* remove the used digits from number */
645 mil /= 1000; /* digit place for next round */
647 if (segment)
649 int hundreds = segment / 100;
650 int ones = segment % 100;
652 if (hundreds)
654 talk_id(VOICE_ZERO + hundreds, true);
655 talk_id(VOICE_HUNDRED, true);
658 /* combination indexing */
659 if (ones > 20)
661 int tens = ones/10 + 18;
662 talk_id(VOICE_ZERO + tens, true);
663 ones %= 10;
666 /* direct indexing */
667 if (ones)
668 talk_id(VOICE_ZERO + ones, true);
670 /* add billion, million, thousand */
671 if (mil)
672 talk_id(VOICE_BILLION + level, true);
674 level++;
677 return 0;
680 /* singular/plural aware saying of a value */
681 int talk_value(long n, int unit, bool enqueue)
683 int unit_id;
684 static const int unit_voiced[] =
685 { /* lookup table for the voice ID of the units */
686 -1, -1, -1, /* regular ID, int, signed */
687 VOICE_MILLISECONDS, /* here come the "real" units */
688 VOICE_SECONDS,
689 VOICE_MINUTES,
690 VOICE_HOURS,
691 VOICE_KHZ,
692 VOICE_DB,
693 VOICE_PERCENT,
694 VOICE_MEGABYTE,
695 VOICE_GIGABYTE,
696 VOICE_MILLIAMPHOURS,
697 VOICE_PIXEL,
698 VOICE_PER_SEC,
699 VOICE_HERTZ,
702 #if CONFIG_CODEC != SWCODEC
703 if (audio_status()) /* busy, buffer in use */
704 return -1;
705 #endif
707 if (unit < 0 || unit >= UNIT_LAST)
708 unit_id = -1;
709 else
710 unit_id = unit_voiced[unit];
712 if ((n==1 || n==-1) /* singular? */
713 && unit_id >= VOICE_SECONDS && unit_id <= VOICE_HOURS)
715 unit_id--; /* use the singular for those units which have */
718 /* special case with a "plus" before */
719 if (n > 0 && (unit == UNIT_SIGNED || unit == UNIT_DB))
721 talk_id(VOICE_PLUS, enqueue);
722 enqueue = true;
725 talk_number(n, enqueue); /* say the number */
726 talk_id(unit_id, true); /* say the unit, if any */
728 return 0;
731 /* spell a string */
732 int talk_spell(const char* spell, bool enqueue)
734 char c; /* currently processed char */
736 #if CONFIG_CODEC != SWCODEC
737 if (audio_status()) /* busy, buffer in use */
738 return -1;
739 #endif
741 if (!enqueue)
742 shutup(); /* cut off all the pending stuff */
744 while ((c = *spell++) != '\0')
746 /* if this grows into too many cases, I should use a table */
747 if (c >= 'A' && c <= 'Z')
748 talk_id(VOICE_CHAR_A + c - 'A', true);
749 else if (c >= 'a' && c <= 'z')
750 talk_id(VOICE_CHAR_A + c - 'a', true);
751 else if (c >= '0' && c <= '9')
752 talk_id(VOICE_ZERO + c - '0', true);
753 else if (c == '-')
754 talk_id(VOICE_MINUS, true);
755 else if (c == '+')
756 talk_id(VOICE_PLUS, true);
757 else if (c == '.')
758 talk_id(VOICE_DOT, true);
759 else if (c == ' ')
760 talk_id(VOICE_PAUSE, true);
763 return 0;