Fix for ff/rw in long MP3 files.
[kugel-rb.git] / apps / talk.c
bloba896ca3a1a2afe62e855a1a3e0f6dfccdcc3a37a
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 "file.h"
27 #include "buffer.h"
28 #include "system.h"
29 #include "settings.h"
30 #include "mp3_playback.h"
31 #include "audio.h"
32 #include "lang.h"
33 #include "talk.h"
34 #include "id3.h"
35 #include "bitswap.h"
37 /***************** Constants *****************/
39 #define QUEUE_SIZE 64 /* must be a power of two */
40 #define QUEUE_MASK (QUEUE_SIZE-1)
41 const char* const dir_thumbnail_name = "_dirname.talk";
42 const char* const file_thumbnail_ext = ".talk";
44 /***************** Functional Macros *****************/
46 #define QUEUE_LEVEL ((queue_write - queue_read) & QUEUE_MASK)
48 #define LOADED_MASK 0x80000000 /* MSB */
51 /***************** Data types *****************/
53 struct clip_entry /* one entry of the index table */
55 int offset; /* offset from start of voicefile file */
56 int size; /* size of the clip */
59 struct voicefile /* file format of our voice file */
61 int version; /* version of the voicefile */
62 int table; /* offset to index table, (=header size) */
63 int id1_max; /* number of "normal" clips contained in above index */
64 int id2_max; /* number of "voice only" clips contained in above index */
65 struct clip_entry index[]; /* followed by the index tables */
66 /* and finally the bitswapped mp3 clips, not visible here */
69 struct queue_entry /* one entry of the internal queue */
71 unsigned char* buf;
72 long len;
76 /***************** Globals *****************/
78 static unsigned char* p_thumbnail; /* buffer for thumbnail */
79 static long size_for_thumbnail; /* leftover buffer size for it */
80 static struct voicefile* p_voicefile; /* loaded voicefile */
81 static bool has_voicefile; /* a voicefile file is present */
82 static struct queue_entry queue[QUEUE_SIZE]; /* queue of scheduled clips */
83 static int queue_write; /* write index of queue, by application */
84 static int queue_read; /* read index of queue, by ISR context */
85 static int sent; /* how many bytes handed over to playback, owned by ISR */
86 static unsigned char curr_hd[3]; /* current frame header, for re-sync */
87 static int filehandle; /* global, so the MMC variant can keep the file open */
88 static unsigned char* p_silence; /* VOICE_PAUSE clip, used for termination */
89 static long silence_len; /* length of the VOICE_PAUSE clip */
90 static unsigned char* p_lastclip; /* address of latest clip, for silence add */
93 /***************** Private prototypes *****************/
95 static void load_voicefile(void);
96 static void mp3_callback(unsigned char** start, int* size);
97 static int shutup(void);
98 static int queue_clip(unsigned char* buf, long size, bool enqueue);
99 static int open_voicefile(void);
100 static unsigned char* get_clip(long id, long* p_size);
103 /***************** Private implementation *****************/
105 static int open_voicefile(void)
107 char buf[64];
108 char* p_lang = "english"; /* default */
110 if ( global_settings.lang_file[0] &&
111 global_settings.lang_file[0] != 0xff )
112 { /* try to open the voice file of the selected language */
113 p_lang = global_settings.lang_file;
116 snprintf(buf, sizeof(buf), ROCKBOX_DIR LANG_DIR "/%s.voice", p_lang);
118 return open(buf, O_RDONLY);
122 /* load the voice file into the mp3 buffer */
123 static void load_voicefile(void)
125 int load_size;
126 int got_size;
127 int file_size;
129 filehandle = open_voicefile();
130 if (filehandle < 0) /* failed to open */
131 goto load_err;
133 file_size = filesize(filehandle);
134 if (file_size > audiobufend - audiobuf) /* won't fit? */
135 goto load_err;
137 #ifdef HAVE_MMC /* load only the header for now */
138 load_size = offsetof(struct voicefile, index);
139 #else /* load the full file */
140 load_size = file_size;
141 #endif
143 got_size = read(filehandle, audiobuf, load_size);
144 if (got_size == load_size /* success */
145 && ((struct voicefile*)audiobuf)->table /* format check */
146 == offsetof(struct voicefile, index))
148 p_voicefile = (struct voicefile*)audiobuf;
150 /* thumbnail buffer is the remaining space behind */
151 p_thumbnail = audiobuf + file_size;
152 p_thumbnail += (long)p_thumbnail % 2; /* 16-bit align */
153 size_for_thumbnail = audiobufend - p_thumbnail;
155 else
156 goto load_err;
158 #ifdef HAVE_MMC
159 /* load the index table, now that we know its size from the header */
160 load_size = (p_voicefile->id1_max + p_voicefile->id2_max)
161 * sizeof(struct clip_entry);
162 got_size = read(filehandle,
163 audiobuf + offsetof(struct voicefile, index), load_size);
164 if (got_size != load_size) /* read error */
165 goto load_err;
166 #else
167 close(filehandle); /* only the MMC variant leaves it open */
168 filehandle = -1;
169 #endif
171 /* make sure to have the silence clip, if available */
172 p_silence = get_clip(VOICE_PAUSE, &silence_len);
174 return;
176 load_err:
177 p_voicefile = NULL;
178 has_voicefile = false; /* don't try again */
179 if (filehandle >= 0)
181 close(filehandle);
182 filehandle = -1;
184 return;
188 /* called in ISR context if mp3 data got consumed */
189 static void mp3_callback(unsigned char** start, int* size)
191 queue[queue_read].len -= sent; /* we completed this */
192 queue[queue_read].buf += sent;
194 if (queue[queue_read].len > 0) /* current clip not finished? */
195 { /* feed the next 64K-1 chunk */
196 sent = MIN(queue[queue_read].len, 0xFFFF);
197 *start = queue[queue_read].buf;
198 *size = sent;
199 return;
201 else if (sent > 0) /* go to next entry */
203 queue_read = (queue_read + 1) & QUEUE_MASK;
206 re_check:
208 if (QUEUE_LEVEL) /* queue is not empty? */
209 { /* start next clip */
210 sent = MIN(queue[queue_read].len, 0xFFFF);
211 *start = p_lastclip = queue[queue_read].buf;
212 *size = sent;
213 curr_hd[0] = p_lastclip[1];
214 curr_hd[1] = p_lastclip[2];
215 curr_hd[2] = p_lastclip[3];
217 else if (p_silence != NULL /* silence clip available */
218 && p_lastclip != p_silence /* previous clip wasn't silence */
219 && p_lastclip < p_thumbnail) /* ..and not a thumbnail */
220 { /* add silence clip when queue runs empty playing a voice clip */
221 queue[queue_write].buf = p_silence;
222 queue[queue_write].len = silence_len;
223 queue_write = (queue_write + 1) & QUEUE_MASK;
225 goto re_check;
227 else
229 *size = 0; /* end of data */
230 mp3_play_stop(); /* fixme: should be done by caller */
234 /* stop the playback and the pending clips, but at frame boundary */
235 static int shutup(void)
237 unsigned char* pos;
238 unsigned char* search;
239 unsigned char* end;
241 if (QUEUE_LEVEL == 0) /* has ended anyway */
243 return 0;
245 #if CONFIG_CPU == SH7034
246 CHCR3 &= ~0x0001; /* disable the DMA (and therefore the interrupt also) */
247 #endif
248 /* search next frame boundary and continue up to there */
249 pos = search = mp3_get_pos();
250 end = queue[queue_read].buf + queue[queue_read].len;
252 if (pos >= queue[queue_read].buf
253 && pos <= end) /* really our clip? */
254 { /* (for strange reasons this isn't nesessarily the case) */
255 /* find the next frame boundary */
256 while (search < end) /* search the remaining data */
258 if (*search++ != 0xFF) /* quick search for frame sync byte */
259 continue; /* (this does the majority of the job) */
261 /* look at the (bitswapped) rest of header candidate */
262 if (search[0] == curr_hd[0] /* do the quicker checks first */
263 && search[2] == curr_hd[2]
264 && (search[1] & 0x30) == (curr_hd[1] & 0x30)) /* sample rate */
266 search--; /* back to the sync byte */
267 break; /* From looking at it, this is our header. */
271 if (search-pos)
272 { /* play old data until the frame end, to keep the MAS in sync */
273 sent = search-pos;
275 queue_write = (queue_read + 1) & QUEUE_MASK; /* will be empty after next callback */
276 queue[queue_read].len = sent; /* current one ends after this */
278 #if CONFIG_CPU == SH7034
279 DTCR3 = sent; /* let the DMA finish this frame */
280 CHCR3 |= 0x0001; /* re-enable DMA */
281 #endif
282 return 0;
286 /* nothing to do, was frame boundary or not our clip */
287 mp3_play_stop();
288 queue_write = queue_read = 0; /* reset the queue */
290 return 0;
294 /* schedule a clip, at the end or discard the existing queue */
295 static int queue_clip(unsigned char* buf, long size, bool enqueue)
297 int queue_level;
299 if (!enqueue)
300 shutup(); /* cut off all the pending stuff */
302 if (!size)
303 return 0; /* safety check */
304 #if CONFIG_CPU == SH7034
305 /* disable the DMA temporarily, to be safe of race condition */
306 CHCR3 &= ~0x0001;
307 #endif
308 queue_level = QUEUE_LEVEL; /* check old level */
310 if (queue_level < QUEUE_SIZE - 1) /* space left? */
312 queue[queue_write].buf = buf; /* populate an entry */
313 queue[queue_write].len = size;
314 queue_write = (queue_write + 1) & QUEUE_MASK;
317 if (queue_level == 0)
318 { /* queue was empty, we have to do the initial start */
319 p_lastclip = buf;
320 sent = MIN(size, 0xFFFF); /* DMA can do no more */
321 mp3_play_data(buf, sent, mp3_callback);
322 curr_hd[0] = buf[1];
323 curr_hd[1] = buf[2];
324 curr_hd[2] = buf[3];
325 mp3_play_pause(true); /* kickoff audio */
327 else
329 #if CONFIG_CPU == SH7034
330 CHCR3 |= 0x0001; /* re-enable DMA */
331 #endif
334 return 0;
337 /* fetch a clip from the voice file */
338 static unsigned char* get_clip(long id, long* p_size)
340 long clipsize;
341 unsigned char* clipbuf;
343 if (id > VOICEONLY_DELIMITER)
344 { /* voice-only entries use the second part of the table */
345 id -= VOICEONLY_DELIMITER + 1;
346 if (id >= p_voicefile->id2_max)
347 return NULL; /* must be newer than we have */
348 id += p_voicefile->id1_max; /* table 2 is behind table 1 */
350 else
351 { /* normal use of the first table */
352 if (id >= p_voicefile->id1_max)
353 return NULL; /* must be newer than we have */
356 clipsize = p_voicefile->index[id].size;
357 if (clipsize == 0) /* clip not included in voicefile */
358 return NULL;
359 clipbuf = audiobuf + p_voicefile->index[id].offset;
361 #ifdef HAVE_MMC /* dynamic loading, on demand */
362 if (!(clipsize & LOADED_MASK))
363 { /* clip used for the first time, needs loading */
364 lseek(filehandle, p_voicefile->index[id].offset, SEEK_SET);
365 if (read(filehandle, clipbuf, clipsize) != clipsize)
366 return NULL; /* read error */
368 p_voicefile->index[id].size |= LOADED_MASK; /* mark as loaded */
370 else
371 { /* clip is in memory already */
372 clipsize &= ~LOADED_MASK; /* without the extra bit gives true size */
374 #endif
376 *p_size = clipsize;
377 return clipbuf;
381 /* common code for talk_init() and talk_buffer_steal() */
382 static void reset_state(void)
384 queue_write = queue_read = 0; /* reset the queue */
385 p_voicefile = NULL; /* indicate no voicefile (trashed) */
386 p_thumbnail = audiobuf; /* whole space for thumbnail */
387 size_for_thumbnail = audiobufend - audiobuf;
388 p_silence = NULL; /* pause clip not accessible */
391 /***************** Public implementation *****************/
393 void talk_init(void)
395 reset_state(); /* use this for most of our inits */
397 #ifdef HAVE_MMC
398 load_voicefile(); /* load the tables right away */
399 has_voicefile = (p_voicefile != NULL);
400 #else
401 filehandle = open_voicefile();
402 has_voicefile = (filehandle >= 0); /* test if we can open it */
403 if (has_voicefile)
405 close(filehandle); /* close again, this was just to detect presence */
406 filehandle = -1;
408 #endif
412 /* somebody else claims the mp3 buffer, e.g. for regular play/record */
413 int talk_buffer_steal(void)
415 mp3_play_stop();
416 #ifdef HAVE_MMC
417 if (filehandle >= 0) /* only relevant for MMC */
419 close(filehandle);
420 filehandle = -1;
422 #endif
423 reset_state();
424 return 0;
428 /* play a voice ID from voicefile */
429 int talk_id(long id, bool enqueue)
431 long clipsize;
432 unsigned char* clipbuf;
433 int unit;
435 if (audio_status()) /* busy, buffer in use */
436 return -1;
438 if (p_voicefile == NULL && has_voicefile)
439 load_voicefile(); /* reload needed */
441 if (p_voicefile == NULL) /* still no voices? */
442 return -1;
444 if (id == -1) /* -1 is an indication for silence */
445 return -1;
447 /* check if this is a special ID, with a value */
448 unit = ((unsigned long)id) >> UNIT_SHIFT;
449 if (unit)
450 { /* sign-extend the value */
451 id = (unsigned long)id << (32-UNIT_SHIFT);
452 id >>= (32-UNIT_SHIFT);
453 talk_value(id, unit, enqueue); /* speak it */
454 return 0; /* and stop, end of special case */
457 clipbuf = get_clip(id, &clipsize);
458 if (clipbuf == NULL)
459 return -1; /* not present */
461 queue_clip(clipbuf, clipsize, enqueue);
463 return 0;
467 /* play a thumbnail from file */
468 int talk_file(const char* filename, bool enqueue)
470 int fd;
471 int size;
472 struct mp3entry info;
474 if (audio_status()) /* busy, buffer in use */
475 return -1;
477 if (p_thumbnail == NULL || size_for_thumbnail <= 0)
478 return -1;
480 if(mp3info(&info, filename, false)) /* use this to find real start */
482 return 0; /* failed to open, or invalid */
485 fd = open(filename, O_RDONLY);
486 if (fd < 0) /* failed to open */
488 return 0;
491 lseek(fd, info.first_frame_offset, SEEK_SET); /* behind ID data */
493 size = read(fd, p_thumbnail, size_for_thumbnail);
494 close(fd);
496 /* ToDo: find audio, skip ID headers and trailers */
498 if (size)
500 #if CONFIG_HWCODEC != MASNONE
501 bitswap(p_thumbnail, size);
502 #endif
503 queue_clip(p_thumbnail, size, enqueue);
506 return size;
510 /* say a numeric value, this word ordering works for english,
511 but not necessarily for other languages (e.g. german) */
512 int talk_number(long n, bool enqueue)
514 int level = 0; /* mille count */
515 long mil = 1000000000; /* highest possible "-illion" */
517 if (audio_status()) /* busy, buffer in use */
518 return -1;
520 if (!enqueue)
521 shutup(); /* cut off all the pending stuff */
523 if (n==0)
524 { /* special case */
525 talk_id(VOICE_ZERO, true);
526 return 0;
529 if (n<0)
531 talk_id(VOICE_MINUS, true);
532 n = -n;
535 while (n)
537 int segment = n / mil; /* extract in groups of 3 digits */
538 n -= segment * mil; /* remove the used digits from number */
539 mil /= 1000; /* digit place for next round */
541 if (segment)
543 int hundreds = segment / 100;
544 int ones = segment % 100;
546 if (hundreds)
548 talk_id(VOICE_ZERO + hundreds, true);
549 talk_id(VOICE_HUNDRED, true);
552 /* combination indexing */
553 if (ones > 20)
555 int tens = ones/10 + 18;
556 talk_id(VOICE_ZERO + tens, true);
557 ones %= 10;
560 /* direct indexing */
561 if (ones)
562 talk_id(VOICE_ZERO + ones, true);
564 /* add billion, million, thousand */
565 if (mil)
566 talk_id(VOICE_BILLION + level, true);
568 level++;
571 return 0;
574 /* singular/plural aware saying of a value */
575 int talk_value(long n, int unit, bool enqueue)
577 int unit_id;
578 static const int unit_voiced[] =
579 { /* lookup table for the voice ID of the units */
580 -1, -1, -1, /* regular ID, int, signed */
581 VOICE_MILLISECONDS, /* here come the "real" units */
582 VOICE_SECONDS,
583 VOICE_MINUTES,
584 VOICE_HOURS,
585 VOICE_KHZ,
586 VOICE_DB,
587 VOICE_PERCENT,
588 VOICE_MEGABYTE,
589 VOICE_GIGABYTE,
590 VOICE_MILLIAMPHOURS,
591 VOICE_PIXEL,
592 VOICE_PER_SEC,
593 VOICE_HERTZ,
596 if (audio_status()) /* busy, buffer in use */
597 return -1;
599 if (unit < 0 || unit >= UNIT_LAST)
600 unit_id = -1;
601 else
602 unit_id = unit_voiced[unit];
604 if ((n==1 || n==-1) /* singular? */
605 && unit_id >= VOICE_SECONDS && unit_id <= VOICE_HOURS)
607 unit_id--; /* use the singular for those units which have */
610 /* special case with a "plus" before */
611 if (n > 0 && (unit == UNIT_SIGNED || unit == UNIT_DB))
613 talk_id(VOICE_PLUS, enqueue);
614 enqueue = true;
617 talk_number(n, enqueue); /* say the number */
618 talk_id(unit_id, true); /* say the unit, if any */
620 return 0;
623 /* spell a string */
624 int talk_spell(const char* spell, bool enqueue)
626 char c; /* currently processed char */
628 if (audio_status()) /* busy, buffer in use */
629 return -1;
631 if (!enqueue)
632 shutup(); /* cut off all the pending stuff */
634 while ((c = *spell++) != '\0')
636 /* if this grows into too many cases, I should use a table */
637 if (c >= 'A' && c <= 'Z')
638 talk_id(VOICE_CHAR_A + c - 'A', true);
639 else if (c >= 'a' && c <= 'z')
640 talk_id(VOICE_CHAR_A + c - 'a', true);
641 else if (c >= '0' && c <= '9')
642 talk_id(VOICE_ZERO + c - '0', true);
643 else if (c == '-')
644 talk_id(VOICE_MINUS, true);
645 else if (c == '+')
646 talk_id(VOICE_PLUS, true);
647 else if (c == '.')
648 talk_id(VOICE_DOT, true);
649 else if (c == ' ')
650 talk_id(VOICE_PAUSE, true);
653 return 0;