Clear warnings and more cleanup
[Rockbox.git] / apps / playback.c
blob7fd263098887c2cfd551d8cfe77b6ee11bc72ff3
1 /***************************************************************************
2 * __________ __ ___.
3 * Open \______ \ ____ ____ | | _\_ |__ _______ ___
4 * Source | _// _ \_/ ___\| |/ /| __ \ / _ \ \/ /
5 * Jukebox | | ( <_> ) \___| < | \_\ ( <_> > < <
6 * Firmware |____|_ /\____/ \___ >__|_ \|___ /\____/__/\_ \
7 * \/ \/ \/ \/ \/
8 * $Id$
10 * Copyright (C) 2005 Miika Pekkarinen
12 * All files in this archive are subject to the GNU General Public License.
13 * See the file COPYING in the source tree root for full license agreement.
15 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
16 * KIND, either express or implied.
18 ****************************************************************************/
20 /* TODO: Can use the track changed callback to detect end of track and seek
21 * in the previous track until this happens */
22 /* Design: we have prev_ti already, have a conditional for what type of seek
23 * to do on a seek request, if it is a previous track seek, skip previous,
24 * and in the request_next_track callback set the offset up the same way that
25 * starting from an offset works. */
26 /* TODO: Pause should be handled in here, rather than PCMBUF so that voice can
27 * play whilst audio is paused */
29 #include <stdio.h>
30 #include <string.h>
31 #include <stdlib.h>
32 #include <ctype.h>
34 #include "system.h"
35 #include "thread.h"
36 #include "file.h"
37 #include "panic.h"
38 #include "memory.h"
39 #include "lcd.h"
40 #include "font.h"
41 #include "button.h"
42 #include "kernel.h"
43 #include "tree.h"
44 #include "debug.h"
45 #include "sprintf.h"
46 #include "settings.h"
47 #include "codecs.h"
48 #include "audio.h"
49 #include "buffering.h"
50 #include "mp3_playback.h"
51 #include "usb.h"
52 #include "status.h"
53 #include "ata.h"
54 #include "screens.h"
55 #include "playlist.h"
56 #include "playback.h"
57 #include "pcmbuf.h"
58 #include "buffer.h"
59 #include "dsp.h"
60 #include "abrepeat.h"
61 #include "cuesheet.h"
62 #ifdef HAVE_TAGCACHE
63 #include "tagcache.h"
64 #endif
65 #ifdef HAVE_LCD_BITMAP
66 #include "icons.h"
67 #include "peakmeter.h"
68 #include "action.h"
69 #endif
70 #include "lang.h"
71 #include "bookmark.h"
72 #include "misc.h"
73 #include "sound.h"
74 #include "metadata.h"
75 #include "splash.h"
76 #include "talk.h"
77 #include "ata_idle_notify.h"
79 #ifdef HAVE_RECORDING
80 #include "recording.h"
81 #include "talk.h"
82 #endif
84 #ifdef HAVE_WM8758
85 #include "menus/eq_menu.h"
86 #endif
88 #define PLAYBACK_VOICE
91 /* Define LOGF_ENABLE to enable logf output in this file */
92 /*#define LOGF_ENABLE*/
93 #include "logf.h"
95 /* macros to enable logf for queues
96 logging on SYS_TIMEOUT can be disabled */
97 #ifdef SIMULATOR
98 /* Define this for logf output of all queuing except SYS_TIMEOUT */
99 #define PLAYBACK_LOGQUEUES
100 /* Define this to logf SYS_TIMEOUT messages */
101 /*#define PLAYBACK_LOGQUEUES_SYS_TIMEOUT*/
102 #endif
104 #ifdef PLAYBACK_LOGQUEUES
105 #define LOGFQUEUE logf
106 #else
107 #define LOGFQUEUE(...)
108 #endif
110 #ifdef PLAYBACK_LOGQUEUES_SYS_TIMEOUT
111 #define LOGFQUEUE_SYS_TIMEOUT logf
112 #else
113 #define LOGFQUEUE_SYS_TIMEOUT(...)
114 #endif
117 /* Define one constant that includes recording related functionality */
118 #if defined(HAVE_RECORDING) && !defined(SIMULATOR)
119 #define AUDIO_HAVE_RECORDING
120 #endif
122 enum {
123 Q_AUDIO_PLAY = 1,
124 Q_AUDIO_STOP,
125 Q_AUDIO_PAUSE,
126 Q_AUDIO_SKIP,
127 Q_AUDIO_PRE_FF_REWIND,
128 Q_AUDIO_FF_REWIND,
129 /* Q_AUDIO_REBUFFER_SEEK, */
130 Q_AUDIO_CHECK_NEW_TRACK,
131 Q_AUDIO_FLUSH,
132 Q_AUDIO_TRACK_CHANGED,
133 Q_AUDIO_DIR_SKIP,
134 Q_AUDIO_POSTINIT,
135 Q_AUDIO_FILL_BUFFER,
136 #if MEM > 8
137 Q_AUDIO_FILL_BUFFER_IF_ACTIVE_ATA,
138 #endif
139 Q_CODEC_REQUEST_COMPLETE,
140 Q_CODEC_REQUEST_FAILED,
142 Q_VOICE_PLAY,
143 Q_VOICE_STOP,
145 Q_CODEC_LOAD,
146 Q_CODEC_LOAD_DISK,
148 #ifdef AUDIO_HAVE_RECORDING
149 Q_ENCODER_LOAD_DISK,
150 Q_ENCODER_RECORD,
151 #endif
154 /* As defined in plugins/lib/xxx2wav.h */
155 #if MEM > 1
156 #define MALLOC_BUFSIZE (512*1024)
157 #define GUARD_BUFSIZE (32*1024)
158 #else
159 #define MALLOC_BUFSIZE (100*1024)
160 #define GUARD_BUFSIZE (8*1024)
161 #endif
163 /* As defined in plugin.lds */
164 #if defined(CPU_PP)
165 #define CODEC_IRAM_ORIGIN ((unsigned char *)0x4000c000)
166 #define CODEC_IRAM_SIZE ((size_t)0xc000)
167 #elif defined(IAUDIO_X5) || defined(IAUDIO_M5)
168 #define CODEC_IRAM_ORIGIN ((unsigned char *)0x10010000)
169 #define CODEC_IRAM_SIZE ((size_t)0x10000)
170 #else
171 #define CODEC_IRAM_ORIGIN ((unsigned char *)0x1000c000)
172 #define CODEC_IRAM_SIZE ((size_t)0xc000)
173 #endif
175 #ifndef IBSS_ATTR_VOICE_STACK
176 #define IBSS_ATTR_VOICE_STACK IBSS_ATTR
177 #endif
179 bool audio_is_initialized = false;
181 /* Variables are commented with the threads that use them: *
182 * A=audio, C=codec, V=voice. A suffix of - indicates that *
183 * the variable is read but not updated on that thread. */
184 /* TBD: Split out "audio" and "playback" (ie. calling) threads */
186 /* Main state control */
187 static volatile bool audio_codec_loaded NOCACHEBSS_ATTR = false; /* Codec loaded? (C/A-) */
188 static volatile bool playing NOCACHEBSS_ATTR = false; /* Is audio playing? (A) */
189 static volatile bool paused NOCACHEBSS_ATTR = false; /* Is audio paused? (A/C-) */
190 static volatile bool filling IDATA_ATTR = false; /* Is file buffer refilling? (A/C-) */
192 /* Ring buffer where compressed audio and codecs are loaded */
193 static unsigned char *filebuf = NULL; /* Start of buffer (A/C-) */
194 static unsigned char *malloc_buf = NULL; /* Start of malloc buffer (A/C-) */
195 /* FIXME: make filebuflen static */
196 size_t filebuflen = 0; /* Size of buffer (A/C-) */
197 /* FIXME: make buf_ridx (C/A-) */
199 /* Possible arrangements of the buffer */
200 #define BUFFER_STATE_TRASHED -1 /* trashed; must be reset */
201 #define BUFFER_STATE_INITIALIZED 0 /* voice+audio OR audio-only */
202 #define BUFFER_STATE_VOICED_ONLY 1 /* voice-only */
203 static int buffer_state = BUFFER_STATE_TRASHED; /* Buffer state */
205 struct mp3entry curtrack_id3;
206 struct mp3entry nexttrack_id3;
208 /* Track info structure about songs in the file buffer (A/C-) */
209 struct track_info {
210 int audio_hid; /* The ID for the track's buffer handle */
211 int id3_hid; /* The ID for the track's metadata handle */
212 int codec_hid; /* The ID for the track's codec handle */
214 size_t codecsize; /* Codec length in bytes */
215 size_t filesize; /* File total length */
217 bool taginfo_ready; /* Is metadata read */
219 bool event_sent; /* Was this track's buffered event sent */
222 static struct track_info tracks[MAX_TRACK];
223 static volatile int track_ridx = 0; /* Track being decoded (A/C-) */
224 static int track_widx = 0; /* Track being buffered (A) */
226 #if 0
227 static struct track_info *prev_ti = NULL; /* Previous track info pointer (A/C-) */
228 #endif
230 #define CUR_TI (&tracks[track_ridx]) /* Playing track info pointer (A/C-) */
232 /* Set by the audio thread when the current track information has updated
233 * and the WPS may need to update its cached information */
234 static bool track_changed = false;
236 /* Information used only for filling the buffer */
237 /* Playlist steps from playing track to next track to be buffered (A) */
238 static int last_peek_offset = 0;
240 /* Scrobbler support */
241 static unsigned long prev_track_elapsed = 0; /* Previous track elapsed time (C/A-)*/
243 /* Track change controls */
244 static bool automatic_skip = false; /* Who initiated in-progress skip? (C/A-) */
245 static bool playlist_end = false; /* Has the current playlist ended? (A) */
246 static bool dir_skip = false; /* Is a directory skip pending? (A) */
247 static bool new_playlist = false; /* Are we starting a new playlist? (A) */
248 static int wps_offset = 0; /* Pending track change offset, to keep WPS responsive (A) */
249 static bool skipped_during_pause = false; /* Do we need to clear the PCM buffer when playback resumes (A) */
251 /* Callbacks which applications or plugins may set */
252 /* When the playing track has changed from the user's perspective */
253 void (*track_changed_callback)(struct mp3entry *id3) = NULL;
254 /* When a track has been buffered */
255 void (*track_buffer_callback)(struct mp3entry *id3, bool last_track) = NULL;
256 /* When a track's buffer has been overwritten or cleared */
257 void (*track_unbuffer_callback)(struct mp3entry *id3, bool last_track) = NULL;
259 /* Configuration */
260 static size_t conf_watermark = 0; /* Level to trigger filebuf fill (A/C) FIXME */
261 static size_t conf_filechunk = 0; /* Largest chunk the codec accepts (A/C) FIXME */
262 static size_t conf_preseek = 0; /* Codec pre-seek margin (A/C) FIXME */
263 static size_t buffer_margin = 0; /* Buffer margin aka anti-skip buffer (A/C-) */
264 #if MEM > 8
265 static size_t high_watermark = 0; /* High watermark for rebuffer (A/V/other) */
266 #endif
268 /* Multiple threads */
269 static void set_current_codec(int codec_idx);
270 /* Set the watermark to trigger buffer fill (A/C) FIXME */
271 static void set_filebuf_watermark(int seconds);
273 /* Audio thread */
274 static struct event_queue audio_queue NOCACHEBSS_ATTR;
275 static struct queue_sender_list audio_queue_sender_list NOCACHEBSS_ATTR;
276 static long audio_stack[(DEFAULT_STACK_SIZE + 0x1000)/sizeof(long)];
277 static const char audio_thread_name[] = "audio";
279 static void audio_thread(void);
280 static void audio_initiate_track_change(long direction);
281 static bool audio_have_tracks(void);
282 static void audio_reset_buffer(void);
284 /* Codec thread */
285 extern struct codec_api ci;
286 static struct event_queue codec_queue NOCACHEBSS_ATTR;
287 static struct queue_sender_list codec_queue_sender_list;
288 static long codec_stack[(DEFAULT_STACK_SIZE + 0x2000)/sizeof(long)]
289 IBSS_ATTR;
290 static const char codec_thread_name[] = "codec";
291 struct thread_entry *codec_thread_p; /* For modifying thread priority later. */
293 static volatile int current_codec IDATA_ATTR; /* Current codec (normal/voice) */
295 /* Buffering thread */
296 void buffering_thread(void);
297 static long buffering_stack[(DEFAULT_STACK_SIZE + 0x2000)/sizeof(long)];
298 static const char buffering_thread_name[] = "buffering";
299 struct thread_entry *buffering_thread_p;
301 /* Voice thread */
302 #ifdef PLAYBACK_VOICE
304 extern struct codec_api ci_voice;
306 static struct thread_entry *voice_thread_p = NULL;
307 static struct event_queue voice_queue NOCACHEBSS_ATTR;
308 static long voice_stack[(DEFAULT_STACK_SIZE + 0x2000)/sizeof(long)]
309 IBSS_ATTR_VOICE_STACK;
310 static const char voice_thread_name[] = "voice codec";
312 /* Voice codec swapping control */
313 extern unsigned char codecbuf[]; /* DRAM codec swap buffer */
315 #ifdef SIMULATOR
316 /* IRAM codec swap buffer for sim*/
317 static unsigned char sim_iram[CODEC_IRAM_SIZE];
318 #undef CODEC_IRAM_ORIGIN
319 #define CODEC_IRAM_ORIGIN sim_iram
320 #endif
322 /* iram_buf and dram_buf are either both NULL or both non-NULL */
323 /* Pointer to IRAM buffer for codec swapping */
324 static unsigned char *iram_buf = NULL;
325 /* Pointer to DRAM buffer for codec swapping */
326 static unsigned char *dram_buf = NULL;
327 /* Parity of swap_codec calls - needed because one codec swapping itself in
328 automatically swaps in the other and the swap when unlocking should not
329 happen if the parity is even.
331 static bool swap_codec_parity NOCACHEBSS_ATTR = false; /* true=odd, false=even */
332 /* Locking to control which codec (normal/voice) is running */
333 static struct semaphore sem_codecthread NOCACHEBSS_ATTR;
334 static struct event event_codecthread NOCACHEBSS_ATTR;
336 /* Voice state */
337 static volatile bool voice_thread_start = false; /* Triggers voice playback (A/V) */
338 static volatile bool voice_is_playing NOCACHEBSS_ATTR = false; /* Is voice currently playing? (V) */
339 static volatile bool voice_codec_loaded NOCACHEBSS_ATTR = false; /* Is voice codec loaded (V/A-) */
340 static unsigned char *voicebuf = NULL;
341 static size_t voice_remaining = 0;
343 #ifdef IRAM_STEAL
344 /* Voice IRAM has been stolen for other use */
345 static bool voice_iram_stolen = false;
346 #endif
348 static void (*voice_getmore)(unsigned char** start, size_t* size) = NULL;
350 struct voice_info {
351 void (*callback)(unsigned char **start, size_t* size);
352 size_t size;
353 unsigned char *buf;
355 static void voice_thread(void);
356 static void voice_stop(void);
358 #endif /* PLAYBACK_VOICE */
361 /* --- Helper functions --- */
363 struct mp3entry *bufgetid3(int handle_id)
365 if (handle_id < 0)
366 return NULL;
368 struct mp3entry *id3;
369 ssize_t ret = bufgetdata(handle_id, 0, (unsigned char **)&id3);
371 if (ret < 0 || ret != sizeof(struct mp3entry))
372 return NULL;
374 return id3;
377 unsigned char *getptr(int handle_id)
379 unsigned char *ptr;
380 ssize_t ret = bufgetdata(handle_id, 0, &ptr);
382 if (ret < 0)
383 return 0;
385 return ptr;
388 void close_track_handles(struct track_info *track)
390 if (!track)
391 return;
393 if (track->codec_hid > 0) {
394 bufclose(track->codec_hid);
395 track->codec_hid = 0;
398 if (track->id3_hid > 0) {
399 bufclose(track->id3_hid);
400 track->id3_hid = 0;
403 if (track->audio_hid > 0) {
404 bufclose(track->audio_hid);
405 track->audio_hid = 0;
409 /* --- External interfaces --- */
411 void mp3_play_data(const unsigned char* start, int size,
412 void (*get_more)(unsigned char** start, size_t* size))
414 #ifdef PLAYBACK_VOICE
415 static struct voice_info voice_clip;
416 voice_clip.callback = get_more;
417 voice_clip.buf = (unsigned char*)start;
418 voice_clip.size = size;
419 LOGFQUEUE("mp3 > voice Q_VOICE_STOP");
420 queue_post(&voice_queue, Q_VOICE_STOP, 0);
421 LOGFQUEUE("mp3 > voice Q_VOICE_PLAY");
422 queue_post(&voice_queue, Q_VOICE_PLAY, (intptr_t)&voice_clip);
423 voice_thread_start = true;
424 trigger_cpu_boost();
425 #else
426 (void) start;
427 (void) size;
428 (void) get_more;
429 #endif
432 void mp3_play_stop(void)
434 #ifdef PLAYBACK_VOICE
435 queue_remove_from_head(&voice_queue, Q_VOICE_STOP);
436 LOGFQUEUE("mp3 > voice Q_VOICE_STOP");
437 queue_post(&voice_queue, Q_VOICE_STOP, 1);
438 #endif
441 void mp3_play_pause(bool play)
443 /* a dummy */
444 (void)play;
447 bool mp3_is_playing(void)
449 #ifdef PLAYBACK_VOICE
450 return voice_is_playing;
451 #else
452 return false;
453 #endif
456 /* If voice could be swapped out - wait for it to return
457 * Used by buffer claming functions.
459 static void wait_for_voice_swap_in(void)
461 #ifdef PLAYBACK_VOICE
462 if (NULL == iram_buf)
463 return;
465 event_wait(&event_codecthread, STATE_NONSIGNALED);
466 #endif /* PLAYBACK_VOICE */
469 /* This sends a stop message and the audio thread will dump all it's
470 subsequenct messages */
471 static void audio_hard_stop(void)
473 /* Stop playback */
474 LOGFQUEUE("audio >| audio Q_AUDIO_STOP: 1");
475 queue_send(&audio_queue, Q_AUDIO_STOP, 1);
478 unsigned char *audio_get_buffer(bool talk_buf, size_t *buffer_size)
480 unsigned char *buf, *end;
482 if (audio_is_initialized)
484 audio_hard_stop();
485 wait_for_voice_swap_in();
486 #ifdef PLAYBACK_VOICE
487 voice_stop();
488 #endif
490 /* else buffer_state will be BUFFER_STATE_TRASHED at this point */
492 if (buffer_size == NULL)
494 /* Special case for talk_init to use since it already knows it's
495 trashed */
496 buffer_state = BUFFER_STATE_TRASHED;
497 return NULL;
500 if (talk_buf || buffer_state == BUFFER_STATE_TRASHED
501 || !talk_voice_required())
503 logf("get buffer: talk, audio");
504 /* Ok to use everything from audiobuf to audiobufend - voice is loaded,
505 the talk buffer is not needed because voice isn't being used, or
506 could be BUFFER_STATE_TRASHED already. If state is
507 BUFFER_STATE_VOICED_ONLY, no problem as long as memory isn't written
508 without the caller knowing what's going on. Changing certain settings
509 may move it to a worse condition but the memory in use by something
510 else will remain undisturbed.
512 if (buffer_state != BUFFER_STATE_TRASHED)
514 talk_buffer_steal();
515 buffer_state = BUFFER_STATE_TRASHED;
518 buf = audiobuf;
519 end = audiobufend;
521 else
523 /* Safe to just return this if already BUFFER_STATE_VOICED_ONLY or
524 still BUFFER_STATE_INITIALIZED */
525 /* Skip talk buffer and move pcm buffer to end to maximize available
526 contiguous memory - no audio running means voice will not need the
527 swap space */
528 logf("get buffer: audio");
529 buf = audiobuf + talk_get_bufsize();
530 end = audiobufend - pcmbuf_init(audiobufend);
531 buffer_state = BUFFER_STATE_VOICED_ONLY;
534 *buffer_size = end - buf;
536 return buf;
539 #ifdef IRAM_STEAL
540 void audio_iram_steal(void)
542 /* We need to stop audio playback in order to use codec IRAM */
543 audio_hard_stop();
545 #ifdef PLAYBACK_VOICE
546 if (NULL != iram_buf)
548 /* Can't already be stolen */
549 if (voice_iram_stolen)
550 return;
552 /* Must wait for voice to be current again if it is swapped which
553 would cause the caller's buffer to get clobbered when voice locks
554 and runs - we'll wait for it to lock and yield again then make sure
555 the ride has come to a complete stop */
556 wait_for_voice_swap_in();
557 voice_stop();
559 /* Save voice IRAM but just memcpy - safe to do here since voice
560 is current and no audio codec is loaded */
561 memcpy(iram_buf, CODEC_IRAM_ORIGIN, CODEC_IRAM_SIZE);
562 voice_iram_stolen = true;
564 else
566 /* Nothing much to do if no voice */
567 voice_iram_stolen = false;
569 #endif
571 #endif /* IRAM_STEAL */
573 #ifdef HAVE_RECORDING
574 unsigned char *audio_get_recording_buffer(size_t *buffer_size)
576 /* Don't allow overwrite of voice swap area or we'll trash the
577 swapped-out voice codec but can use whole thing if none */
578 unsigned char *end;
580 /* Stop audio and voice. Wait for voice to swap in and be clear
581 of pending events to ensure trouble-free operation of encoders */
582 audio_hard_stop();
583 wait_for_voice_swap_in();
584 #ifdef PLAYBACK_VOICE
585 voice_stop();
586 #endif
587 talk_buffer_steal();
589 #ifdef PLAYBACK_VOICE
590 /* If no dram_buf, swap space not used and recording gets more
591 memory. Codec swap areas will remain unaffected by the next init
592 since they're allocated at the end of the buffer and their sizes
593 don't change between calls */
594 end = dram_buf;
595 if (NULL == end)
596 #endif /* PLAYBACK_VOICE */
597 end = audiobufend;
599 buffer_state = BUFFER_STATE_TRASHED;
601 *buffer_size = end - audiobuf;
603 return (unsigned char *)audiobuf;
606 bool audio_load_encoder(int afmt)
608 #ifndef SIMULATOR
609 const char *enc_fn = get_codec_filename(afmt | CODEC_TYPE_ENCODER);
610 if (!enc_fn)
611 return false;
613 audio_remove_encoder();
614 ci.enc_codec_loaded = 0; /* clear any previous error condition */
616 LOGFQUEUE("codec > Q_ENCODER_LOAD_DISK");
617 queue_post(&codec_queue, Q_ENCODER_LOAD_DISK, (intptr_t)enc_fn);
619 while (ci.enc_codec_loaded == 0)
620 yield();
622 logf("codec loaded: %d", ci.enc_codec_loaded);
624 return ci.enc_codec_loaded > 0;
625 #else
626 (void)afmt;
627 return true;
628 #endif
629 } /* audio_load_encoder */
631 void audio_remove_encoder(void)
633 #ifndef SIMULATOR
634 /* force encoder codec unload (if currently loaded) */
635 if (ci.enc_codec_loaded <= 0)
636 return;
638 ci.stop_encoder = true;
639 while (ci.enc_codec_loaded > 0)
640 yield();
641 #endif
642 } /* audio_remove_encoder */
644 #endif /* HAVE_RECORDING */
646 struct mp3entry* audio_current_track(void)
648 const char *filename;
649 const char *p;
650 static struct mp3entry temp_id3;
651 int cur_idx;
652 int offset = ci.new_track + wps_offset;
654 cur_idx = track_ridx + offset;
655 cur_idx &= MAX_TRACK_MASK;
657 if (tracks[cur_idx].id3_hid > 0)
658 return &curtrack_id3;
660 memset(&temp_id3, 0, sizeof(struct mp3entry));
662 filename = playlist_peek(0);
663 if (!filename)
664 filename = "No file!";
666 #ifdef HAVE_TC_RAMCACHE
667 if (tagcache_fill_tags(&temp_id3, filename))
668 return &temp_id3;
669 #endif
671 p = strrchr(filename, '/');
672 if (!p)
673 p = filename;
674 else
675 p++;
677 strncpy(temp_id3.path, p, sizeof(temp_id3.path)-1);
678 temp_id3.title = &temp_id3.path[0];
680 return &temp_id3;
683 struct mp3entry* audio_next_track(void)
685 int next_idx = track_ridx;
687 if (!audio_have_tracks())
688 return NULL;
690 next_idx++;
691 next_idx &= MAX_TRACK_MASK;
693 if (tracks[next_idx].id3_hid <= 0)
694 return NULL;
696 return &nexttrack_id3;
699 bool audio_has_changed_track(void)
701 if (track_changed)
703 track_changed = false;
704 return true;
707 return false;
710 void audio_play(long offset)
712 logf("audio_play");
714 #ifdef PLAYBACK_VOICE
715 /* Truncate any existing voice output so we don't have spelling
716 * etc. over the first part of the played track */
717 talk_force_shutup();
718 #endif
720 /* Start playback */
721 LOGFQUEUE("audio >| audio Q_AUDIO_PLAY: %ld", offset);
722 /* Don't return until playback has actually started */
723 queue_send(&audio_queue, Q_AUDIO_PLAY, offset);
726 void audio_stop(void)
728 /* Stop playback */
729 LOGFQUEUE("audio >| audio Q_AUDIO_STOP");
730 /* Don't return until playback has actually stopped */
731 queue_send(&audio_queue, Q_AUDIO_STOP, 0);
734 void audio_pause(void)
736 LOGFQUEUE("audio >| audio Q_AUDIO_PAUSE");
737 /* Don't return until playback has actually paused */
738 queue_send(&audio_queue, Q_AUDIO_PAUSE, true);
741 void audio_resume(void)
743 LOGFQUEUE("audio >| audio Q_AUDIO_PAUSE resume");
744 /* Don't return until playback has actually resumed */
745 queue_send(&audio_queue, Q_AUDIO_PAUSE, false);
748 void audio_next(void)
750 if (playlist_check(ci.new_track + wps_offset + 1))
752 if (global_settings.beep)
753 pcmbuf_beep(5000, 100, 2500*global_settings.beep);
755 LOGFQUEUE("audio > audio Q_AUDIO_SKIP 1");
756 queue_post(&audio_queue, Q_AUDIO_SKIP, 1);
757 /* Update wps while our message travels inside deep playback queues. */
758 wps_offset++;
759 track_changed = true;
761 else
763 /* No more tracks. */
764 if (global_settings.beep)
765 pcmbuf_beep(1000, 100, 1000*global_settings.beep);
769 void audio_prev(void)
771 if (playlist_check(ci.new_track + wps_offset - 1))
773 if (global_settings.beep)
774 pcmbuf_beep(5000, 100, 2500*global_settings.beep);
776 LOGFQUEUE("audio > audio Q_AUDIO_SKIP -1");
777 queue_post(&audio_queue, Q_AUDIO_SKIP, -1);
778 /* Update wps while our message travels inside deep playback queues. */
779 wps_offset--;
780 track_changed = true;
782 else
784 /* No more tracks. */
785 if (global_settings.beep)
786 pcmbuf_beep(1000, 100, 1000*global_settings.beep);
790 void audio_next_dir(void)
792 LOGFQUEUE("audio > audio Q_AUDIO_DIR_SKIP 1");
793 queue_post(&audio_queue, Q_AUDIO_DIR_SKIP, 1);
796 void audio_prev_dir(void)
798 LOGFQUEUE("audio > audio Q_AUDIO_DIR_SKIP -1");
799 queue_post(&audio_queue, Q_AUDIO_DIR_SKIP, -1);
802 void audio_pre_ff_rewind(void)
804 LOGFQUEUE("audio > audio Q_AUDIO_PRE_FF_REWIND");
805 queue_post(&audio_queue, Q_AUDIO_PRE_FF_REWIND, 0);
808 void audio_ff_rewind(long newpos)
810 LOGFQUEUE("audio > audio Q_AUDIO_FF_REWIND");
811 queue_post(&audio_queue, Q_AUDIO_FF_REWIND, newpos);
814 void audio_flush_and_reload_tracks(void)
816 LOGFQUEUE("audio > audio Q_AUDIO_FLUSH");
817 queue_post(&audio_queue, Q_AUDIO_FLUSH, 0);
820 void audio_error_clear(void)
822 #ifdef AUDIO_HAVE_RECORDING
823 pcm_rec_error_clear();
824 #endif
827 int audio_status(void)
829 int ret = 0;
831 if (playing)
832 ret |= AUDIO_STATUS_PLAY;
834 if (paused)
835 ret |= AUDIO_STATUS_PAUSE;
837 #ifdef HAVE_RECORDING
838 /* Do this here for constitency with mpeg.c version */
839 ret |= pcm_rec_status();
840 #endif
842 return ret;
845 int audio_get_file_pos(void)
847 return 0;
850 #ifndef HAVE_FLASH_STORAGE
851 void audio_set_buffer_margin(int setting)
853 static const int lookup[] = {5, 15, 30, 60, 120, 180, 300, 600};
854 buffer_margin = lookup[setting];
855 logf("buffer margin: %d", buffer_margin);
856 set_filebuf_watermark(buffer_margin);
858 #endif
860 /* Take nescessary steps to enable or disable the crossfade setting */
861 void audio_set_crossfade(int enable)
863 size_t offset;
864 bool was_playing;
865 size_t size;
867 /* Tell it the next setting to use */
868 pcmbuf_crossfade_enable(enable);
870 /* Return if size hasn't changed or this is too early to determine
871 which in the second case there's no way we could be playing
872 anything at all */
873 if (pcmbuf_is_same_size())
875 /* This function is a copout and just syncs some variables -
876 to be removed at a later date */
877 pcmbuf_crossfade_enable_finished();
878 return;
881 offset = 0;
882 was_playing = playing;
884 /* Playback has to be stopped before changing the buffer size */
885 if (was_playing)
887 /* Store the track resume position */
888 offset = curtrack_id3.offset;
889 gui_syncsplash(0, str(LANG_RESTARTING_PLAYBACK));
892 /* Blast it - audio buffer will have to be setup again next time
893 something plays */
894 audio_get_buffer(true, &size);
896 /* Restart playback if audio was running previously */
897 if (was_playing)
898 audio_play(offset);
901 /* --- Routines called from multiple threads --- */
902 static void set_current_codec(int codec_idx)
904 current_codec = codec_idx;
905 dsp_configure(DSP_SWITCH_CODEC, codec_idx);
908 #ifdef PLAYBACK_VOICE
909 static void swap_codec(void)
911 int my_codec;
913 /* Swap nothing if no swap buffers exist */
914 if (dram_buf == NULL)
916 logf("swap: no swap buffers");
917 return;
920 my_codec = current_codec;
922 logf("swapping out codec: %d", my_codec);
924 /* Invert this when a codec thread enters and leaves */
925 swap_codec_parity = !swap_codec_parity;
927 /* If this is true, an odd number of calls has occurred and there's
928 no codec thread waiting to swap us out when it locks and runs. This
929 occurs when playback is stopped or when just starting playback and
930 the audio thread is loading a codec; parities should always be even
931 on entry when a thread calls this during playback */
932 if (swap_codec_parity)
934 /* Save our current IRAM and DRAM */
935 #ifdef IRAM_STEAL
936 if (voice_iram_stolen)
938 logf("swap: iram restore");
939 voice_iram_stolen = false;
940 /* Don't swap trashed data into buffer as the voice IRAM will
941 already be swapped out - should _always_ be the case if
942 voice_iram_stolen is true since the voice has been swapped
943 in beforehand */
944 if (my_codec == CODEC_IDX_VOICE)
946 logf("voice iram already swapped");
947 goto skip_iram_swap;
950 #endif
952 memswap128(iram_buf, CODEC_IRAM_ORIGIN, CODEC_IRAM_SIZE);
954 #ifdef IRAM_STEAL
955 skip_iram_swap:
956 #endif
958 memswap128(dram_buf, codecbuf, CODEC_SIZE);
959 /* No cache invalidation needed; it will be done in codec_load_ram
960 or we won't be here otherwise */
963 /* Release my semaphore */
964 semaphore_release(&sem_codecthread);
965 logf("unlocked: %d", my_codec);
967 /* Wait for other codec */
968 event_wait(&event_codecthread,
969 (my_codec == CODEC_IDX_AUDIO) ? STATE_NONSIGNALED : STATE_SIGNALED);
971 /* Wait for other codec to unlock */
972 logf("waiting for lock: %d", my_codec);
973 semaphore_wait(&sem_codecthread);
975 /* Take control */
976 set_current_codec(my_codec);
977 event_set_state(&event_codecthread,
978 (my_codec == CODEC_IDX_AUDIO) ? STATE_SIGNALED : STATE_NONSIGNALED);
980 /* Reload our IRAM and DRAM */
981 memswap128(iram_buf, CODEC_IRAM_ORIGIN, CODEC_IRAM_SIZE);
982 memswap128(dram_buf, codecbuf, CODEC_SIZE);
983 invalidate_icache();
985 /* Flip parity again */
986 swap_codec_parity = !swap_codec_parity;
988 logf("resuming codec: %d", my_codec);
991 /* This function is meant to be used by the buffer stealing functions to
992 ensure the codec is no longer active and so voice will be swapped-in
993 before it is called */
994 static void voice_stop(void)
996 /* Must have a voice codec loaded or we'll hang forever here */
997 if (!voice_codec_loaded)
998 return;
1000 talk_force_shutup();
1002 /* Loop until voice empties it's queue, stops and picks up on the new
1003 track; the voice thread must be stopped and waiting for messages
1004 outside the codec */
1005 while (voice_is_playing || !queue_empty(&voice_queue) ||
1006 ci_voice.new_track)
1007 yield();
1009 if (!playing)
1010 pcmbuf_play_stop();
1011 } /* voice_stop */
1013 /* Is voice still speaking */
1014 /* Unfortunately only reliable when music is not also playing. */
1015 static bool is_voice_speaking(void)
1017 return is_voice_queued()
1018 || voice_is_playing
1019 || (!playing && pcm_is_playing());
1022 #endif /* PLAYBACK_VOICE */
1024 /* Wait for voice to finish speaking. */
1025 /* Also only reliable when music is not also playing. */
1026 void voice_wait(void)
1028 #ifdef PLAYBACK_VOICE
1029 while (is_voice_speaking())
1030 sleep(HZ/10);
1031 #endif
1034 static void set_filebuf_watermark(int seconds)
1036 size_t bytes;
1038 if (!filebuf)
1039 return; /* Audio buffers not yet set up */
1041 bytes = MAX(curtrack_id3.bitrate * seconds * (1000/8), conf_watermark);
1042 bytes = MIN(bytes, filebuflen / 2);
1043 conf_watermark = bytes;
1046 const char * get_codec_filename(int cod_spec)
1048 const char *fname;
1050 #ifdef HAVE_RECORDING
1051 /* Can choose decoder or encoder if one available */
1052 int type = cod_spec & CODEC_TYPE_MASK;
1053 int afmt = cod_spec & CODEC_AFMT_MASK;
1055 if ((unsigned)afmt >= AFMT_NUM_CODECS)
1056 type = AFMT_UNKNOWN | (type & CODEC_TYPE_MASK);
1058 fname = (type == CODEC_TYPE_ENCODER) ?
1059 audio_formats[afmt].codec_enc_root_fn :
1060 audio_formats[afmt].codec_root_fn;
1062 logf("%s: %d - %s",
1063 (type == CODEC_TYPE_ENCODER) ? "Encoder" : "Decoder",
1064 afmt, fname ? fname : "<unknown>");
1065 #else /* !HAVE_RECORDING */
1066 /* Always decoder */
1067 if ((unsigned)cod_spec >= AFMT_NUM_CODECS)
1068 cod_spec = AFMT_UNKNOWN;
1069 fname = audio_formats[cod_spec].codec_root_fn;
1070 logf("Codec: %d - %s", cod_spec, fname ? fname : "<unknown>");
1071 #endif /* HAVE_RECORDING */
1073 return fname;
1074 } /* get_codec_filename */
1077 /* --- Voice thread --- */
1079 #ifdef PLAYBACK_VOICE
1081 static bool voice_pcmbuf_insert_callback(
1082 const void *ch1, const void *ch2, int count)
1084 const char *src[2] = { ch1, ch2 };
1086 while (count > 0)
1088 int out_count = dsp_output_count(count);
1089 int inp_count;
1090 char *dest;
1092 while ((dest = pcmbuf_request_voice_buffer(
1093 &out_count, playing)) == NULL)
1095 if (playing && audio_codec_loaded)
1096 swap_codec();
1097 else
1098 yield();
1101 /* Get the real input_size for output_size bytes, guarding
1102 * against resampling buffer overflows. */
1103 inp_count = dsp_input_count(out_count);
1105 if (inp_count <= 0)
1106 return true;
1108 /* Input size has grown, no error, just don't write more than length */
1109 if (inp_count > count)
1110 inp_count = count;
1112 out_count = dsp_process(dest, src, inp_count);
1114 if (out_count <= 0)
1115 return true;
1117 if (playing)
1119 pcmbuf_mix_voice(out_count);
1120 if ((pcmbuf_usage() < 10 || pcmbuf_mix_free() < 30) &&
1121 audio_codec_loaded)
1122 swap_codec();
1124 else
1125 pcmbuf_write_complete(out_count);
1127 count -= inp_count;
1130 return true;
1131 } /* voice_pcmbuf_insert_callback */
1133 static void* voice_get_memory_callback(size_t *size)
1135 /* Voice should have no use for this. If it did, we'd have to
1136 swap the malloc buffer as well. */
1137 *size = 0;
1138 return NULL;
1141 static void voice_set_elapsed_callback(unsigned int value)
1143 (void)value;
1146 static void voice_set_offset_callback(size_t value)
1148 (void)value;
1151 static void voice_configure_callback(int setting, intptr_t value)
1153 if (!dsp_configure(setting, value))
1155 logf("Illegal key:%d", setting);
1159 static size_t voice_filebuf_callback(void *ptr, size_t size)
1161 (void)ptr;
1162 (void)size;
1164 return 0;
1167 /* Handle Q_VOICE_STOP and part of SYS_USB_CONNECTED */
1168 static bool voice_on_voice_stop(bool aborting, size_t *realsize)
1170 if (aborting && !playing)
1172 /* Aborting: Slight hack - flush PCM buffer if
1173 only being used for voice */
1174 pcmbuf_play_stop();
1177 if (voice_is_playing)
1179 /* Clear the current buffer */
1180 voice_is_playing = false;
1181 voice_getmore = NULL;
1182 voice_remaining = 0;
1183 voicebuf = NULL;
1185 /* Cancel any automatic boost if no more clips requested. */
1186 if (!playing || !voice_thread_start)
1187 sleep(0);
1189 /* Force the codec to think it's changing tracks */
1190 ci_voice.new_track = 1;
1192 *realsize = 0;
1193 return true; /* Yes, change tracks */
1196 return false;
1199 static void* voice_request_buffer_callback(size_t *realsize, size_t reqsize)
1201 struct queue_event ev;
1203 if (ci_voice.new_track)
1205 *realsize = 0;
1206 return NULL;
1209 while (1)
1211 if (voice_is_playing || playing)
1213 queue_wait_w_tmo(&voice_queue, &ev, 0);
1214 if (!voice_is_playing && ev.id == SYS_TIMEOUT)
1215 ev.id = Q_AUDIO_PLAY;
1217 else
1219 queue_wait(&voice_queue, &ev);
1222 switch (ev.id) {
1223 case Q_AUDIO_PLAY:
1224 LOGFQUEUE("voice < Q_AUDIO_PLAY");
1225 if (playing)
1227 if (audio_codec_loaded)
1228 swap_codec();
1229 yield();
1231 break;
1233 #ifdef AUDIO_HAVE_RECORDING
1234 case Q_ENCODER_RECORD:
1235 LOGFQUEUE("voice < Q_ENCODER_RECORD");
1236 swap_codec();
1237 break;
1238 #endif
1240 case Q_VOICE_STOP:
1241 LOGFQUEUE("voice < Q_VOICE_STOP");
1242 if (voice_on_voice_stop(ev.data, realsize))
1243 return NULL;
1244 break;
1246 case SYS_USB_CONNECTED:
1248 LOGFQUEUE("voice < SYS_USB_CONNECTED");
1249 bool change_tracks = voice_on_voice_stop(ev.data, realsize);
1250 /* Voice is obviously current so let us swap ourselves away if
1251 playing so audio may stop itself - audio_codec_loaded can
1252 only be true in this case if we're here even if the codec
1253 is only about to load */
1254 if (audio_codec_loaded)
1255 swap_codec();
1256 /* Playback should be finished by now - ack and wait */
1257 usb_acknowledge(SYS_USB_CONNECTED_ACK);
1258 usb_wait_for_disconnect(&voice_queue);
1259 if (change_tracks)
1260 return NULL;
1261 break;
1264 case Q_VOICE_PLAY:
1265 LOGFQUEUE("voice < Q_VOICE_PLAY");
1266 if (!voice_is_playing)
1268 /* Set up new voice data */
1269 struct voice_info *voice_data;
1270 #ifdef IRAM_STEAL
1271 if (voice_iram_stolen)
1273 /* Voice is the first to run again and is currently
1274 loaded */
1275 logf("voice: iram restore");
1276 memcpy(CODEC_IRAM_ORIGIN, iram_buf, CODEC_IRAM_SIZE);
1277 voice_iram_stolen = false;
1279 #endif
1280 /* Must reset the buffer before any playback begins if
1281 needed */
1282 if (buffer_state == BUFFER_STATE_TRASHED)
1283 audio_reset_buffer();
1285 voice_is_playing = true;
1286 trigger_cpu_boost();
1287 voice_data = (struct voice_info *)ev.data;
1288 voice_remaining = voice_data->size;
1289 voicebuf = voice_data->buf;
1290 voice_getmore = voice_data->callback;
1292 goto voice_play_clip; /* To exit both switch and while */
1294 case SYS_TIMEOUT:
1295 LOGFQUEUE_SYS_TIMEOUT("voice < SYS_TIMEOUT");
1296 goto voice_play_clip;
1298 default:
1299 LOGFQUEUE("voice < default");
1303 voice_play_clip:
1305 if (voice_remaining == 0 || voicebuf == NULL)
1307 if (voice_getmore)
1308 voice_getmore((unsigned char **)&voicebuf, &voice_remaining);
1310 /* If this clip is done */
1311 if (voice_remaining == 0)
1313 LOGFQUEUE("voice > voice Q_VOICE_STOP");
1314 queue_post(&voice_queue, Q_VOICE_STOP, 0);
1315 /* Force pcm playback. */
1316 if (!pcm_is_playing())
1317 pcmbuf_play_start();
1321 *realsize = MIN(voice_remaining, reqsize);
1323 if (*realsize == 0)
1324 return NULL;
1326 return voicebuf;
1327 } /* voice_request_buffer_callback */
1329 static void voice_advance_buffer_callback(size_t amount)
1331 amount = MIN(amount, voice_remaining);
1332 voicebuf += amount;
1333 voice_remaining -= amount;
1336 static void voice_advance_buffer_loc_callback(void *ptr)
1338 size_t amount = (size_t)ptr - (size_t)voicebuf;
1340 voice_advance_buffer_callback(amount);
1343 static off_t voice_mp3_get_filepos_callback(int newtime)
1345 (void)newtime;
1347 return 0;
1350 static void voice_do_nothing(void)
1352 return;
1355 static bool voice_seek_buffer_callback(size_t newpos)
1357 (void)newpos;
1359 return false;
1362 static bool voice_request_next_track_callback(void)
1364 ci_voice.new_track = 0;
1365 return true;
1368 static void voice_thread(void)
1370 logf("Loading voice codec");
1371 voice_codec_loaded = true;
1372 semaphore_wait(&sem_codecthread);
1373 event_set_state(&event_codecthread, false);
1374 set_current_codec(CODEC_IDX_VOICE);
1375 dsp_configure(DSP_RESET, 0);
1376 voice_remaining = 0;
1377 voice_getmore = NULL;
1379 /* FIXME: If we being starting the voice thread without reboot, the
1380 voice_queue could be full of old stuff and we must flush it. */
1381 codec_load_file(get_codec_filename(AFMT_MPA_L3), &ci_voice);
1383 logf("Voice codec finished");
1384 voice_codec_loaded = false;
1385 voice_thread_p = NULL;
1386 semaphore_release(&sem_codecthread);
1387 } /* voice_thread */
1389 #endif /* PLAYBACK_VOICE */
1391 /* --- Codec thread --- */
1392 static bool codec_pcmbuf_insert_callback(
1393 const void *ch1, const void *ch2, int count)
1395 const char *src[2] = { ch1, ch2 };
1397 while (count > 0)
1399 int out_count = dsp_output_count(count);
1400 int inp_count;
1401 char *dest;
1403 /* Prevent audio from a previous track from playing */
1404 if (ci.new_track || ci.stop_codec)
1405 return true;
1407 while ((dest = pcmbuf_request_buffer(&out_count)) == NULL)
1409 sleep(1);
1410 if (ci.seek_time || ci.new_track || ci.stop_codec)
1411 return true;
1414 /* Get the real input_size for output_size bytes, guarding
1415 * against resampling buffer overflows. */
1416 inp_count = dsp_input_count(out_count);
1418 if (inp_count <= 0)
1419 return true;
1421 /* Input size has grown, no error, just don't write more than length */
1422 if (inp_count > count)
1423 inp_count = count;
1425 out_count = dsp_process(dest, src, inp_count);
1427 if (out_count <= 0)
1428 return true;
1430 pcmbuf_write_complete(out_count);
1432 #ifdef PLAYBACK_VOICE
1433 if ((voice_is_playing || voice_thread_start)
1434 && pcm_is_playing() && voice_codec_loaded &&
1435 pcmbuf_usage() > 30 && pcmbuf_mix_free() > 80)
1437 voice_thread_start = false;
1438 swap_codec();
1440 #endif
1442 count -= inp_count;
1445 return true;
1446 } /* codec_pcmbuf_insert_callback */
1448 static void* codec_get_memory_callback(size_t *size)
1450 *size = MALLOC_BUFSIZE;
1451 return malloc_buf;
1454 #if 0
1455 static void codec_pcmbuf_position_callback(size_t size) ICODE_ATTR;
1456 static void codec_pcmbuf_position_callback(size_t size)
1458 /* This is called from an ISR, so be quick */
1459 unsigned int time = size * 1000 / 4 / NATIVE_FREQUENCY +
1460 prev_ti->id3.elapsed;
1462 if (time >= prev_ti->id3.length)
1464 pcmbuf_set_position_callback(NULL);
1465 prev_ti->id3.elapsed = prev_ti->id3.length;
1467 else
1468 prev_ti->id3.elapsed = time;
1470 #endif
1472 static void codec_set_elapsed_callback(unsigned int value)
1474 unsigned int latency;
1475 if (ci.seek_time)
1476 return;
1478 #ifdef AB_REPEAT_ENABLE
1479 ab_position_report(value);
1480 #endif
1482 latency = pcmbuf_get_latency();
1483 if (value < latency)
1484 curtrack_id3.elapsed = 0;
1485 else if (value - latency > curtrack_id3.elapsed ||
1486 value - latency < curtrack_id3.elapsed - 2)
1488 curtrack_id3.elapsed = value - latency;
1492 static void codec_set_offset_callback(size_t value)
1494 unsigned int latency;
1496 if (ci.seek_time)
1497 return;
1499 latency = pcmbuf_get_latency() * curtrack_id3.bitrate / 8;
1500 if (value < latency)
1501 curtrack_id3.offset = 0;
1502 else
1503 curtrack_id3.offset = value - latency;
1506 /* copy up-to size bytes into ptr and return the actual size copied */
1507 static size_t codec_filebuf_callback(void *ptr, size_t size)
1509 ssize_t copy_n;
1511 if (ci.stop_codec || !playing)
1512 return 0;
1514 copy_n = bufread(CUR_TI->audio_hid, size, ptr);
1516 /* Nothing requested OR nothing left */
1517 if (copy_n == 0)
1518 return 0;
1520 /* Let the disk buffer catch fill until enough data is available */
1521 while (copy_n == -2)
1523 #if 0
1524 if (!filling)
1526 LOGFQUEUE("codec > audio Q_AUDIO_FILL_BUFFER");
1527 queue_post(&audio_queue, Q_AUDIO_FILL_BUFFER, 0);
1529 #endif
1531 LOGFQUEUE("codec >| buffering Q_BUFFER_HANDLE");
1532 queue_send(&buffering_queue, Q_BUFFER_HANDLE, CUR_TI->audio_hid);
1534 if (ci.stop_codec || ci.new_track)
1535 return 0;
1537 copy_n = bufread(CUR_TI->audio_hid, size, ptr);
1540 /* Update read and other position pointers */
1541 bufadvance(CUR_TI->audio_hid, copy_n);
1542 ci.curpos += copy_n;
1544 /* Return the actual amount of data copied to the buffer */
1545 return copy_n;
1546 } /* codec_filebuf_callback */
1548 static void* codec_request_buffer_callback(size_t *realsize, size_t reqsize)
1550 size_t copy_n = reqsize;
1551 ssize_t ret;
1552 char *ptr;
1554 if (!playing)
1556 *realsize = 0;
1557 return NULL;
1560 ret = bufgetdata(CUR_TI->audio_hid, reqsize, (unsigned char **)&ptr);
1561 if (ret >= 0)
1562 copy_n = MIN((size_t)ret, reqsize);
1564 if (copy_n == 0)
1566 *realsize = 0;
1567 return NULL;
1570 while (ret == -2)
1572 #if 0
1573 if (!filling)
1575 LOGFQUEUE("codec > audio Q_AUDIO_FILL_BUFFER");
1576 queue_post(&audio_queue, Q_AUDIO_FILL_BUFFER, 0);
1578 #endif
1580 LOGFQUEUE("codec >| buffering Q_BUFFER_HANDLE");
1581 queue_send(&buffering_queue, Q_BUFFER_HANDLE, CUR_TI->audio_hid);
1583 sleep(1);
1585 if (ci.stop_codec || ci.new_track)
1587 *realsize = 0;
1588 return NULL;
1590 ret = bufgetdata(CUR_TI->audio_hid, reqsize, (unsigned char **)&ptr);
1592 copy_n = MIN((size_t)ret, reqsize);
1594 *realsize = copy_n;
1596 return ptr;
1597 } /* codec_request_buffer_callback */
1599 static int get_codec_base_type(int type)
1601 switch (type) {
1602 case AFMT_MPA_L1:
1603 case AFMT_MPA_L2:
1604 case AFMT_MPA_L3:
1605 return AFMT_MPA_L3;
1608 return type;
1611 static void codec_advance_buffer_callback(size_t amount)
1613 #if 0
1614 int ret;
1616 while ((ret = bufadvance(CUR_TI->audio_hid, amount) == -2) && filling)
1617 sleep(1);
1619 if (ret == -2)
1621 intptr_t result = Q_CODEC_REQUEST_FAILED;
1623 if (!ci.stop_codec)
1625 LOGFQUEUE("codec >| audio Q_AUDIO_REBUFFER_SEEK");
1626 result = queue_send(&audio_queue, Q_AUDIO_REBUFFER_SEEK,
1627 ci.curpos + amount);
1630 switch (result)
1632 case Q_CODEC_REQUEST_FAILED:
1633 LOGFQUEUE("codec |< Q_CODEC_REQUEST_FAILED");
1634 ci.stop_codec = true;
1635 return;
1637 case Q_CODEC_REQUEST_COMPLETE:
1638 LOGFQUEUE("codec |< Q_CODEC_REQUEST_COMPLETE");
1639 return;
1641 default:
1642 LOGFQUEUE("codec |< default");
1643 ci.stop_codec = true;
1644 return;
1648 /* Start buffer filling as necessary. */
1649 if (!pcmbuf_is_lowdata() && !filling)
1651 if (bufused() < conf_watermark && playing && !playlist_end)
1653 LOGFQUEUE("codec > audio Q_AUDIO_FILL_BUFFER");
1654 queue_post(&audio_queue, Q_AUDIO_FILL_BUFFER, 0);
1657 #endif
1659 bufadvance(CUR_TI->audio_hid, amount);
1661 ci.curpos += amount;
1662 codec_set_offset_callback(ci.curpos);
1665 static void codec_advance_buffer_loc_callback(void *ptr)
1667 size_t amount = get_offset(CUR_TI->audio_hid, ptr);
1669 codec_advance_buffer_callback(amount);
1672 /* Copied from mpeg.c. Should be moved somewhere else. */
1673 static int codec_get_file_pos(void)
1675 int pos = -1;
1676 struct mp3entry *id3 = audio_current_track();
1678 if (id3->vbr)
1680 if (id3->has_toc)
1682 /* Use the TOC to find the new position */
1683 unsigned int percent, remainder;
1684 int curtoc, nexttoc, plen;
1686 percent = (id3->elapsed*100)/id3->length;
1687 if (percent > 99)
1688 percent = 99;
1690 curtoc = id3->toc[percent];
1692 if (percent < 99)
1693 nexttoc = id3->toc[percent+1];
1694 else
1695 nexttoc = 256;
1697 pos = (id3->filesize/256)*curtoc;
1699 /* Use the remainder to get a more accurate position */
1700 remainder = (id3->elapsed*100)%id3->length;
1701 remainder = (remainder*100)/id3->length;
1702 plen = (nexttoc - curtoc)*(id3->filesize/256);
1703 pos += (plen/100)*remainder;
1705 else
1707 /* No TOC exists, estimate the new position */
1708 pos = (id3->filesize / (id3->length / 1000)) *
1709 (id3->elapsed / 1000);
1712 else if (id3->bitrate)
1713 pos = id3->elapsed * (id3->bitrate / 8);
1714 else
1715 return -1;
1717 pos += id3->first_frame_offset;
1719 /* Don't seek right to the end of the file so that we can
1720 transition properly to the next song */
1721 if (pos >= (int)(id3->filesize - id3->id3v1len))
1722 pos = id3->filesize - id3->id3v1len - 1;
1724 return pos;
1727 static off_t codec_mp3_get_filepos_callback(int newtime)
1729 off_t newpos;
1731 curtrack_id3.elapsed = newtime;
1732 newpos = codec_get_file_pos();
1734 return newpos;
1737 static void codec_seek_complete_callback(void)
1739 logf("seek_complete");
1740 if (pcm_is_paused())
1742 /* If this is not a seamless seek, clear the buffer */
1743 pcmbuf_play_stop();
1744 dsp_configure(DSP_FLUSH, 0);
1746 /* If playback was not 'deliberately' paused, unpause now */
1747 if (!paused)
1748 pcmbuf_pause(false);
1750 ci.seek_time = 0;
1753 static bool codec_seek_buffer_callback(size_t newpos)
1755 int difference;
1757 logf("codec_seek_buffer_callback");
1759 if (newpos >= CUR_TI->filesize)
1760 newpos = CUR_TI->filesize - 1;
1762 difference = newpos - ci.curpos;
1763 if (difference >= 0)
1765 /* Seeking forward */
1766 logf("seek: +%d", difference);
1767 codec_advance_buffer_callback(difference);
1768 return true;
1771 /* Seeking backward */
1772 difference = -difference;
1773 if (ci.curpos - difference < 0)
1774 difference = ci.curpos;
1776 #if 0
1777 /* We need to reload the song. */
1778 if (newpos < CUR_TI->start_pos)
1780 intptr_t result = Q_CODEC_REQUEST_FAILED;
1782 if (!ci.stop_codec)
1784 LOGFQUEUE("codec >| audio Q_AUDIO_REBUFFER_SEEK");
1785 result = queue_send(&audio_queue, Q_AUDIO_REBUFFER_SEEK,
1786 newpos);
1789 switch (result)
1791 case Q_CODEC_REQUEST_COMPLETE:
1792 LOGFQUEUE("codec |< Q_CODEC_REQUEST_COMPLETE");
1793 return true;
1795 case Q_CODEC_REQUEST_FAILED:
1796 LOGFQUEUE("codec |< Q_CODEC_REQUEST_FAILED");
1797 ci.stop_codec = true;
1798 return false;
1800 default:
1801 LOGFQUEUE("codec |< default");
1802 return false;
1805 #endif
1807 /* Seeking inside buffer space. */
1808 logf("seek: -%d", difference);
1809 if (bufadvance(CUR_TI->audio_hid, -difference) == 0)
1811 ci.curpos -= difference;
1812 return true;
1814 else
1816 return false;
1821 static void codec_configure_callback(int setting, intptr_t value)
1823 switch (setting) {
1824 case CODEC_SET_FILEBUF_WATERMARK:
1825 conf_watermark = value;
1826 set_filebuf_watermark(buffer_margin);
1827 break;
1829 case CODEC_SET_FILEBUF_CHUNKSIZE:
1830 conf_filechunk = value;
1831 break;
1833 case CODEC_SET_FILEBUF_PRESEEK:
1834 conf_preseek = value;
1835 break;
1837 default:
1838 if (!dsp_configure(setting, value)) { logf("Illegal key:%d", setting); }
1842 static void codec_track_changed(void)
1844 automatic_skip = false;
1845 LOGFQUEUE("codec > audio Q_AUDIO_TRACK_CHANGED");
1846 queue_post(&audio_queue, Q_AUDIO_TRACK_CHANGED, 0);
1849 static void codec_pcmbuf_track_changed_callback(void)
1851 pcmbuf_set_position_callback(NULL);
1852 codec_track_changed();
1855 static void codec_discard_codec_callback(void)
1857 if (CUR_TI->codec_hid > 0)
1859 bufclose(CUR_TI->codec_hid);
1860 CUR_TI->codec_hid = 0;
1863 #if 0
1864 /* Check if a buffer desync has happened, log it and stop playback. */
1865 if (buf_ridx != CUR_TI->buf_idx)
1867 int offset = CUR_TI->buf_idx - buf_ridx;
1868 size_t new_used = bufused() - offset;
1870 logf("Buf off :%d=%d-%d", offset, CUR_TI->buf_idx, buf_ridx);
1871 logf("Used off:%d",bufused() - new_used);
1873 /* This is a fatal internal error and it's not safe to
1874 * continue playback. */
1875 ci.stop_codec = true;
1876 queue_post(&audio_queue, Q_AUDIO_STOP, 0);
1878 #endif
1881 static inline void codec_gapless_track_change(void) {
1882 /* callback keeps the progress bar moving while the pcmbuf empties */
1883 /* pcmbuf_set_position_callback(codec_pcmbuf_position_callback); */
1884 /* set the pcmbuf callback for when the track really changes */
1885 pcmbuf_set_event_handler(codec_pcmbuf_track_changed_callback);
1888 static inline void codec_crossfade_track_change(void) {
1889 /* Initiate automatic crossfade mode */
1890 pcmbuf_crossfade_init(false);
1891 /* Notify the wps that the track change starts now */
1892 codec_track_changed();
1895 static void codec_track_skip_done(bool was_manual)
1897 int crossfade_mode = global_settings.crossfade;
1899 /* Manual track change (always crossfade or flush audio). */
1900 if (was_manual)
1902 pcmbuf_crossfade_init(true);
1903 LOGFQUEUE("codec > audio Q_AUDIO_TRACK_CHANGED");
1904 queue_post(&audio_queue, Q_AUDIO_TRACK_CHANGED, 0);
1906 /* Automatic track change w/crossfade, if not in "Track Skip Only" mode. */
1907 else if (pcmbuf_is_crossfade_enabled() && !pcmbuf_is_crossfade_active()
1908 && crossfade_mode != CROSSFADE_ENABLE_TRACKSKIP)
1910 if (crossfade_mode == CROSSFADE_ENABLE_SHUFFLE_AND_TRACKSKIP)
1912 if (global_settings.playlist_shuffle)
1913 /* shuffle mode is on, so crossfade: */
1914 codec_crossfade_track_change();
1915 else
1916 /* shuffle mode is off, so do a gapless track change */
1917 codec_gapless_track_change();
1919 else
1920 /* normal crossfade: */
1921 codec_crossfade_track_change();
1923 else
1924 /* normal gapless playback. */
1925 codec_gapless_track_change();
1928 static bool codec_load_next_track(void)
1930 intptr_t result = Q_CODEC_REQUEST_FAILED;
1932 prev_track_elapsed = curtrack_id3.elapsed;
1934 if (ci.seek_time)
1935 codec_seek_complete_callback();
1937 #ifdef AB_REPEAT_ENABLE
1938 ab_end_of_track_report();
1939 #endif
1941 logf("Request new track");
1943 if (ci.new_track == 0)
1945 ci.new_track++;
1946 automatic_skip = true;
1949 if (!ci.stop_codec)
1951 trigger_cpu_boost();
1952 LOGFQUEUE("codec >| audio Q_AUDIO_CHECK_NEW_TRACK");
1953 result = queue_send(&audio_queue, Q_AUDIO_CHECK_NEW_TRACK, 0);
1956 switch (result)
1958 case Q_CODEC_REQUEST_COMPLETE:
1959 LOGFQUEUE("codec |< Q_CODEC_REQUEST_COMPLETE");
1960 codec_track_skip_done(!automatic_skip);
1961 return true;
1963 case Q_CODEC_REQUEST_FAILED:
1964 LOGFQUEUE("codec |< Q_CODEC_REQUEST_FAILED");
1965 ci.new_track = 0;
1966 ci.stop_codec = true;
1967 return false;
1969 default:
1970 LOGFQUEUE("codec |< default");
1971 ci.stop_codec = true;
1972 return false;
1976 static bool codec_request_next_track_callback(void)
1978 int prev_codectype;
1980 if (ci.stop_codec || !playing)
1981 return false;
1983 prev_codectype = get_codec_base_type(curtrack_id3.codectype);
1985 if (!codec_load_next_track())
1986 return false;
1988 /* Check if the next codec is the same file. */
1989 if (prev_codectype == get_codec_base_type(curtrack_id3.codectype))
1991 logf("New track loaded");
1992 codec_discard_codec_callback();
1993 return true;
1995 else
1997 logf("New codec:%d/%d", curtrack_id3.codectype, prev_codectype);
1998 return false;
2002 static void codec_thread(void)
2004 struct queue_event ev;
2005 int status;
2006 size_t wrap;
2008 while (1) {
2009 status = 0;
2010 queue_wait(&codec_queue, &ev);
2012 switch (ev.id) {
2013 case Q_CODEC_LOAD_DISK:
2014 LOGFQUEUE("codec < Q_CODEC_LOAD_DISK");
2015 queue_reply(&codec_queue, 1);
2016 audio_codec_loaded = true;
2017 #ifdef PLAYBACK_VOICE
2018 /* Don't sent messages to voice codec if it's already swapped
2019 out or it will never get this */
2020 if (voice_codec_loaded && current_codec == CODEC_IDX_VOICE)
2022 LOGFQUEUE("codec > voice Q_AUDIO_PLAY");
2023 queue_post(&voice_queue, Q_AUDIO_PLAY, 0);
2025 semaphore_wait(&sem_codecthread);
2026 event_set_state(&event_codecthread, true);
2027 #endif
2028 set_current_codec(CODEC_IDX_AUDIO);
2029 ci.stop_codec = false;
2030 status = codec_load_file((const char *)ev.data, &ci);
2031 DEBUGF("codec_load = %d\n", status);
2032 #ifdef PLAYBACK_VOICE
2033 semaphore_release(&sem_codecthread);
2034 #endif
2035 break;
2037 case Q_CODEC_LOAD:
2038 LOGFQUEUE("codec < Q_CODEC_LOAD");
2039 if (CUR_TI->codec_hid <= 0) {
2040 logf("Codec slot is empty!");
2041 /* Wait for the pcm buffer to go empty */
2042 while (pcm_is_playing())
2043 yield();
2044 /* This must be set to prevent an infinite loop */
2045 ci.stop_codec = true;
2046 LOGFQUEUE("codec > codec Q_AUDIO_PLAY");
2047 queue_post(&codec_queue, Q_AUDIO_PLAY, 0);
2048 break;
2051 audio_codec_loaded = true;
2052 #ifdef PLAYBACK_VOICE
2053 if (voice_codec_loaded && current_codec == CODEC_IDX_VOICE)
2055 LOGFQUEUE("codec > voice Q_AUDIO_PLAY");
2056 queue_post(&voice_queue, Q_AUDIO_PLAY, 0);
2058 semaphore_wait(&sem_codecthread);
2059 event_set_state(&event_codecthread, true);
2060 #endif
2061 set_current_codec(CODEC_IDX_AUDIO);
2062 ci.stop_codec = false;
2063 wrap = (size_t)&filebuf[filebuflen] - (size_t)getptr(CUR_TI->codec_hid);
2064 status = codec_load_ram(getptr(CUR_TI->codec_hid), CUR_TI->codecsize,
2065 &filebuf[0], wrap, &ci);
2066 #ifdef PLAYBACK_VOICE
2067 semaphore_release(&sem_codecthread);
2068 #endif
2069 break;
2071 #ifdef AUDIO_HAVE_RECORDING
2072 case Q_ENCODER_LOAD_DISK:
2073 LOGFQUEUE("codec < Q_ENCODER_LOAD_DISK");
2074 audio_codec_loaded = false; /* Not audio codec! */
2075 #ifdef PLAYBACK_VOICE
2076 if (voice_codec_loaded && current_codec == CODEC_IDX_VOICE)
2078 LOGFQUEUE("codec > voice Q_ENCODER_RECORD");
2079 queue_post(&voice_queue, Q_ENCODER_RECORD, 0);
2081 semaphore_wait(&sem_codecthread);
2082 event_set_state(&event_codecthread, true);
2083 #endif
2084 logf("loading encoder");
2085 set_current_codec(CODEC_IDX_AUDIO);
2086 ci.stop_encoder = false;
2087 status = codec_load_file((const char *)ev.data, &ci);
2088 #ifdef PLAYBACK_VOICE
2089 semaphore_release(&sem_codecthread);
2090 #endif
2091 logf("encoder stopped");
2092 break;
2093 #endif /* AUDIO_HAVE_RECORDING */
2095 #ifndef SIMULATOR
2096 case SYS_USB_CONNECTED:
2097 LOGFQUEUE("codec < SYS_USB_CONNECTED");
2098 queue_clear(&codec_queue);
2099 usb_acknowledge(SYS_USB_CONNECTED_ACK);
2100 usb_wait_for_disconnect(&codec_queue);
2101 break;
2102 #endif
2104 default:
2105 LOGFQUEUE("codec < default");
2108 if (audio_codec_loaded)
2110 if (ci.stop_codec)
2112 status = CODEC_OK;
2113 if (!playing)
2114 pcmbuf_play_stop();
2117 audio_codec_loaded = false;
2120 switch (ev.id) {
2121 case Q_CODEC_LOAD_DISK:
2122 case Q_CODEC_LOAD:
2123 LOGFQUEUE("codec < Q_CODEC_LOAD");
2124 if (playing)
2126 if (ci.new_track || status != CODEC_OK)
2128 if (!ci.new_track)
2130 logf("Codec failure");
2131 gui_syncsplash(HZ*2, "Codec failure");
2134 if (!codec_load_next_track())
2136 LOGFQUEUE("codec > audio Q_AUDIO_STOP");
2137 /* End of playlist */
2138 queue_post(&audio_queue, Q_AUDIO_STOP, 0);
2139 break;
2142 else
2144 logf("Codec finished");
2145 if (ci.stop_codec)
2147 /* Wait for the audio to stop playing before
2148 * triggering the WPS exit */
2149 while(pcm_is_playing())
2151 curtrack_id3.elapsed =
2152 curtrack_id3.length - pcmbuf_get_latency();
2153 sleep(1);
2155 LOGFQUEUE("codec > audio Q_AUDIO_STOP");
2156 /* End of playlist */
2157 queue_post(&audio_queue, Q_AUDIO_STOP, 0);
2158 break;
2162 if (CUR_TI->codec_hid > 0)
2164 LOGFQUEUE("codec > codec Q_CODEC_LOAD");
2165 queue_post(&codec_queue, Q_CODEC_LOAD, 0);
2167 else
2169 const char *codec_fn =
2170 get_codec_filename(curtrack_id3.codectype);
2171 LOGFQUEUE("codec > codec Q_CODEC_LOAD_DISK");
2172 queue_post(&codec_queue, Q_CODEC_LOAD_DISK,
2173 (intptr_t)codec_fn);
2176 break;
2178 #ifdef AUDIO_HAVE_RECORDING
2179 case Q_ENCODER_LOAD_DISK:
2180 LOGFQUEUE("codec < Q_ENCODER_LOAD_DISK");
2182 if (status == CODEC_OK)
2183 break;
2185 logf("Encoder failure");
2186 gui_syncsplash(HZ*2, "Encoder failure");
2188 if (ci.enc_codec_loaded < 0)
2189 break;
2191 logf("Encoder failed to load");
2192 ci.enc_codec_loaded = -1;
2193 break;
2194 #endif /* AUDIO_HAVE_RECORDING */
2196 default:
2197 LOGFQUEUE("codec < default");
2199 } /* end switch */
2204 /* --- Audio thread --- */
2206 #if 0
2207 static bool audio_filebuf_is_lowdata(void)
2209 return bufused() < AUDIO_FILEBUF_CRITICAL;
2211 #endif
2213 static bool audio_have_tracks(void)
2215 return track_ridx != track_widx || CUR_TI->filesize;
2218 static bool audio_have_free_tracks(void)
2220 if (track_widx < track_ridx)
2221 return track_widx + 1 < track_ridx;
2222 else if (track_ridx == 0)
2223 return track_widx < MAX_TRACK - 1;
2225 return true;
2228 int audio_track_count(void)
2230 if (audio_have_tracks())
2232 int relative_track_widx = track_widx;
2234 if (track_ridx > track_widx)
2235 relative_track_widx += MAX_TRACK;
2237 return relative_track_widx - track_ridx + 1;
2240 return 0;
2243 long audio_filebufused(void)
2245 return (long) bufused();
2248 #if 0
2249 /* Count the data BETWEEN the selected tracks */
2250 static size_t audio_buffer_count_tracks(int from_track, int to_track)
2252 size_t amount = 0;
2253 bool need_wrap = to_track < from_track;
2255 while (1)
2257 if (++from_track >= MAX_TRACK)
2259 from_track -= MAX_TRACK;
2260 need_wrap = false;
2263 if (from_track >= to_track && !need_wrap)
2264 break;
2266 amount += tracks[from_track].codecsize + tracks[from_track].filesize;
2268 return amount;
2270 #endif
2272 static bool audio_buffer_wind_forward(int new_track_ridx, int old_track_ridx)
2274 (void)new_track_ridx;
2275 (void)old_track_ridx;
2276 #if 0
2277 size_t amount;
2279 /* Start with the remainder of the previously playing track */
2280 amount = tracks[old_track_ridx].filesize - ci.curpos;
2281 /* Then collect all data from tracks in between them */
2282 amount += audio_buffer_count_tracks(old_track_ridx, new_track_ridx);
2283 logf("bwf:%ldB", (long) amount);
2285 if (amount > bufused())
2286 return false;
2288 /* Wind the buffer to the beginning of the target track or its codec */
2289 buf_ridx = RINGBUF_ADD(buf_ridx, amount);
2290 #endif
2291 return true;
2294 static bool audio_buffer_wind_backward(int new_track_ridx, int old_track_ridx)
2296 (void)new_track_ridx;
2297 (void)old_track_ridx;
2298 #if 0
2299 /* Available buffer data */
2300 size_t buf_back;
2301 /* Start with the previously playing track's data and our data */
2302 size_t amount;
2304 amount = ci.curpos;
2305 buf_back = RINGBUF_SUB(buf_ridx, buf_widx);
2307 /* If we're not just resetting the current track */
2308 if (new_track_ridx != old_track_ridx)
2310 /* Need to wind to before the old track's codec and our filesize */
2311 amount += tracks[old_track_ridx].codecsize;
2312 amount += tracks[new_track_ridx].filesize;
2314 /* Rewind the old track to its beginning */
2315 tracks[old_track_ridx].available =
2316 tracks[old_track_ridx].filesize - tracks[old_track_ridx].filerem;
2319 /* If the codec was ever buffered */
2320 if (tracks[new_track_ridx].codecsize)
2322 /* Add the codec to the needed size */
2323 amount += tracks[new_track_ridx].codecsize;
2324 tracks[new_track_ridx].has_codec = true;
2327 /* Then collect all data from tracks between new and old */
2328 amount += audio_buffer_count_tracks(new_track_ridx, old_track_ridx);
2330 /* Do we have space to make this skip? */
2331 if (amount > buf_back)
2332 return false;
2334 logf("bwb:%ldB",amount);
2336 /* Rewind the buffer to the beginning of the target track or its codec */
2337 buf_ridx = RINGBUF_SUB(buf_ridx, amount);
2339 /* Reset to the beginning of the new track */
2340 tracks[new_track_ridx].available = tracks[new_track_ridx].filesize;
2341 #endif
2342 return true;
2345 static void audio_update_trackinfo(void)
2347 ci.filesize = CUR_TI->filesize;
2348 curtrack_id3.elapsed = 0;
2349 curtrack_id3.offset = 0;
2350 ci.id3 = &curtrack_id3;
2351 ci.curpos = 0;
2352 ci.taginfo_ready = &CUR_TI->taginfo_ready;
2355 #if 0
2356 /* Yield to codecs for as long as possible if they are in need of data
2357 * return true if the caller should break to let the audio thread process
2358 * new events */
2359 static bool audio_yield_codecs(void)
2361 yield();
2363 if (!queue_empty(&audio_queue))
2364 return true;
2366 while ((pcmbuf_is_crossfade_active() || pcmbuf_is_lowdata())
2367 && !ci.stop_codec && playing && !audio_filebuf_is_lowdata())
2369 if (filling)
2370 yield();
2371 else
2372 sleep(2);
2374 if (!queue_empty(&audio_queue))
2375 return true;
2378 return false;
2380 #endif
2382 static void audio_clear_track_entries(bool clear_unbuffered)
2384 int cur_idx = track_widx;
2385 int last_idx = -1;
2387 logf("Clearing tracks:%d/%d, %d", track_ridx, track_widx, clear_unbuffered);
2389 /* Loop over all tracks from write-to-read */
2390 while (1)
2392 cur_idx++;
2393 cur_idx &= MAX_TRACK_MASK;
2395 if (cur_idx == track_ridx)
2396 break;
2398 /* If the track is buffered, conditionally clear/notify,
2399 * otherwise clear the track if that option is selected */
2400 if (tracks[cur_idx].event_sent)
2402 if (last_idx >= 0)
2404 /* If there is an unbuffer callback, call it, otherwise,
2405 * just clear the track */
2406 if (track_unbuffer_callback)
2407 track_unbuffer_callback(bufgetid3(tracks[last_idx].id3_hid), false);
2409 close_track_handles(&tracks[last_idx]);
2410 memset(&tracks[last_idx], 0, sizeof(struct track_info));
2412 last_idx = cur_idx;
2414 else if (clear_unbuffered)
2416 close_track_handles(&tracks[cur_idx]);
2417 memset(&tracks[cur_idx], 0, sizeof(struct track_info));
2421 /* We clear the previous instance of a buffered track throughout
2422 * the above loop to facilitate 'last' detection. Clear/notify
2423 * the last track here */
2424 if (last_idx >= 0)
2426 if (track_unbuffer_callback)
2427 track_unbuffer_callback(bufgetid3(tracks[last_idx].id3_hid), true);
2428 memset(&tracks[last_idx], 0, sizeof(struct track_info));
2432 static void audio_release_tracks(void)
2434 int cur_idx = track_ridx;
2436 logf("releasing all tracks");
2438 while (1)
2440 close_track_handles(&tracks[cur_idx]);
2442 cur_idx++;
2443 cur_idx &= MAX_TRACK_MASK;
2445 if (cur_idx == track_widx)
2446 break;
2450 #if 0
2451 /* FIXME: This code should be made more generic and move to metadata.c */
2452 static void audio_strip_tags(void)
2454 int i;
2455 static const unsigned char tag[] = "TAG";
2456 static const unsigned char apetag[] = "APETAGEX";
2457 size_t tag_idx;
2458 size_t cur_idx;
2459 size_t len, version;
2461 tag_idx = RINGBUF_SUB(buf_widx, 128);
2463 if (bufused() > 128 && tag_idx > buf_ridx)
2465 cur_idx = tag_idx;
2466 for(i = 0;i < 3;i++)
2468 if(filebuf[cur_idx] != tag[i])
2469 goto strip_ape_tag;
2471 cur_idx = RINGBUF_ADD(cur_idx, 1);
2474 /* Skip id3v1 tag */
2475 logf("Skipping ID3v1 tag");
2476 buf_widx = tag_idx;
2477 tracks[track_widx].available -= 128;
2478 tracks[track_widx].filesize -= 128;
2481 strip_ape_tag:
2482 /* Check for APE tag (look for the APE tag footer) */
2483 tag_idx = RINGBUF_SUB(buf_widx, 32);
2485 if (bufused() > 32 && tag_idx > buf_ridx)
2487 cur_idx = tag_idx;
2488 for(i = 0;i < 8;i++)
2490 if(filebuf[cur_idx] != apetag[i])
2491 return;
2493 cur_idx = RINGBUF_ADD(cur_idx, 1);
2496 /* Read the version and length from the footer */
2497 version = filebuf[tag_idx+8] | (filebuf[tag_idx+9] << 8) |
2498 (filebuf[tag_idx+10] << 16) | (filebuf[tag_idx+11] << 24);
2499 len = filebuf[tag_idx+12] | (filebuf[tag_idx+13] << 8) |
2500 (filebuf[tag_idx+14] << 16) | (filebuf[tag_idx+15] << 24);
2501 if (version == 2000)
2502 len += 32; /* APEv2 has a 32 byte header */
2504 /* Skip APE tag */
2505 if (bufused() > len)
2507 logf("Skipping APE tag (%ldB)", len);
2508 buf_widx = RINGBUF_SUB(buf_widx, len);
2509 tracks[track_widx].available -= len;
2510 tracks[track_widx].filesize -= len;
2514 #endif
2516 #if 0
2517 /* Returns true if a whole file is read, false otherwise */
2518 static bool audio_read_file(size_t minimum)
2520 bool ret_val = false;
2522 /* If we're called and no file is open, this is an error */
2523 if (current_fd < 0)
2525 logf("Bad fd in arf");
2526 /* Give some hope of miraculous recovery by forcing a track reload */
2527 tracks[track_widx].filesize = 0;
2528 /* Stop this buffering run */
2529 return ret_val;
2532 trigger_cpu_boost();
2533 while (tracks[track_widx].filerem > 0)
2535 size_t copy_n;
2536 int overlap;
2537 int rc;
2539 /* copy_n is the largest chunk that is safe to read */
2540 copy_n = MIN(conf_filechunk, filebuflen - buf_widx);
2542 /* buf_widx == buf_ridx is defined as buffer empty, not buffer full */
2543 if (RINGBUF_ADD_CROSS(buf_widx,copy_n,buf_ridx) >= 0)
2544 break;
2546 /* rc is the actual amount read */
2547 rc = read(current_fd, &filebuf[buf_widx], copy_n);
2549 if (rc < 0)
2551 logf("File ended %ldB early", tracks[track_widx].filerem);
2552 tracks[track_widx].filesize -= tracks[track_widx].filerem;
2553 tracks[track_widx].filerem = 0;
2554 break;
2557 /* How much of the playing track did we overwrite */
2558 if (buf_widx == CUR_TI->buf_idx)
2560 /* Special handling; zero or full overlap? */
2561 if (track_widx == track_ridx && CUR_TI->available == 0)
2562 overlap = 0;
2563 else
2564 overlap = rc;
2566 else
2567 overlap = RINGBUF_ADD_CROSS(buf_widx,rc,CUR_TI->buf_idx);
2569 if ((unsigned)rc > tracks[track_widx].filerem)
2571 logf("Bad: rc-filerem=%ld, fixing", rc-tracks[track_widx].filerem);
2572 tracks[track_widx].filesize += rc - tracks[track_widx].filerem;
2573 tracks[track_widx].filerem = rc;
2576 /* Advance buffer */
2577 buf_widx = RINGBUF_ADD(buf_widx, rc);
2578 tracks[track_widx].available += rc;
2579 tracks[track_widx].filerem -= rc;
2581 /* If we write into the playing track, adjust it's buffer info */
2582 if (overlap > 0)
2584 CUR_TI->buf_idx += overlap;
2585 CUR_TI->start_pos += overlap;
2588 /* For a rebuffer, fill at least this minimum */
2589 if (minimum > (unsigned)rc)
2590 minimum -= rc;
2591 /* Let the codec process up to the watermark */
2592 /* Break immediately if this is a quick buffer, or there is an event */
2593 else if (minimum || audio_yield_codecs())
2595 /* Exit quickly, but don't stop the overall buffering process */
2596 ret_val = true;
2597 break;
2601 if (tracks[track_widx].filerem == 0)
2603 logf("Finished buf:%ldB", tracks[track_widx].filesize);
2604 close(current_fd);
2605 current_fd = -1;
2606 audio_strip_tags();
2608 track_widx++;
2609 track_widx &= MAX_TRACK_MASK;
2611 tracks[track_widx].filesize = 0;
2612 return true;
2614 else
2616 logf("%s buf:%ldB", ret_val?"Quick":"Partially",
2617 tracks[track_widx].filesize - tracks[track_widx].filerem);
2618 return ret_val;
2621 #endif
2623 static bool audio_loadcodec(bool start_play)
2625 int fd;
2626 int prev_track;
2627 char codec_path[MAX_PATH]; /* Full path to codec */
2629 DEBUGF("audio_loadcodec(start_play = %s)\n", start_play ? "true" : "false");
2631 if (tracks[track_widx].id3_hid <= 0) {
2632 DEBUGF("track ID3 info not ready\n");
2633 return false;
2636 const char * codec_fn =
2637 get_codec_filename(bufgetid3(tracks[track_widx].id3_hid)->codectype);
2638 if (codec_fn == NULL)
2639 return false;
2641 tracks[track_widx].codec_hid = 0;
2643 if (start_play)
2645 /* Load the codec directly from disk and save some memory. */
2646 track_ridx = track_widx;
2647 ci.filesize = CUR_TI->filesize;
2648 ci.id3 = &curtrack_id3;
2649 ci.taginfo_ready = &CUR_TI->taginfo_ready;
2650 ci.curpos = 0;
2651 LOGFQUEUE("codec > codec Q_CODEC_LOAD_DISK");
2652 queue_post(&codec_queue, Q_CODEC_LOAD_DISK, (intptr_t)codec_fn);
2653 return true;
2655 else
2657 /* If we already have another track than this one buffered */
2658 if (track_widx != track_ridx)
2660 prev_track = (track_widx - 1) & MAX_TRACK_MASK;
2662 /* If the previous codec is the same as this one, there is no need
2663 * to put another copy of it on the file buffer */
2664 if (get_codec_base_type(
2665 bufgetid3(tracks[track_widx].id3_hid)->codectype) ==
2666 get_codec_base_type(
2667 bufgetid3(tracks[prev_track].id3_hid)->codectype)
2668 && audio_codec_loaded)
2670 logf("Reusing prev. codec");
2671 return true;
2676 codec_get_full_path(codec_path, codec_fn);
2678 fd = open(codec_path, O_RDONLY);
2679 if (fd < 0)
2681 logf("Codec doesn't exist!");
2682 return false;
2685 tracks[track_widx].codecsize = filesize(fd);
2687 tracks[track_widx].codec_hid = bufopen(codec_path, 0, TYPE_CODEC);
2688 if (tracks[track_widx].codec_hid < 0)
2690 logf("Not enough space");
2691 close(fd);
2692 return false;
2695 close(fd);
2696 logf("Loaded codec");
2698 return true;
2701 /* TODO: Copied from mpeg.c. Should be moved somewhere else. */
2702 static void audio_set_elapsed(struct mp3entry* id3)
2704 unsigned long offset = id3->offset > id3->first_frame_offset ?
2705 id3->offset - id3->first_frame_offset : 0;
2707 if ( id3->vbr ) {
2708 if ( id3->has_toc ) {
2709 /* calculate elapsed time using TOC */
2710 int i;
2711 unsigned int remainder, plen, relpos, nextpos;
2713 /* find wich percent we're at */
2714 for (i=0; i<100; i++ )
2715 if ( offset < id3->toc[i] * (id3->filesize / 256) )
2716 break;
2718 i--;
2719 if (i < 0)
2720 i = 0;
2722 relpos = id3->toc[i];
2724 if (i < 99)
2725 nextpos = id3->toc[i+1];
2726 else
2727 nextpos = 256;
2729 remainder = offset - (relpos * (id3->filesize / 256));
2731 /* set time for this percent (divide before multiply to prevent
2732 overflow on long files. loss of precision is negligible on
2733 short files) */
2734 id3->elapsed = i * (id3->length / 100);
2736 /* calculate remainder time */
2737 plen = (nextpos - relpos) * (id3->filesize / 256);
2738 id3->elapsed += (((remainder * 100) / plen) *
2739 (id3->length / 10000));
2741 else {
2742 /* no TOC exists. set a rough estimate using average bitrate */
2743 int tpk = id3->length /
2744 ((id3->filesize - id3->first_frame_offset - id3->id3v1len) /
2745 1024);
2746 id3->elapsed = offset / 1024 * tpk;
2749 else
2751 /* constant bitrate, use exact calculation */
2752 if (id3->bitrate != 0)
2753 id3->elapsed = offset / (id3->bitrate / 8);
2757 /* Load one track by making the appropriate bufopen calls. Return true if
2758 everything required was loaded correctly, false if not. */
2759 static bool audio_load_track(int offset, bool start_play, bool rebuffer)
2761 (void)rebuffer;
2762 char *trackname;
2763 /* char msgbuf[80]; */
2764 int fd;
2765 int file_offset = 0;
2766 struct mp3entry id3;
2768 /* Stop buffer filling if there is no free track entries.
2769 Don't fill up the last track entry (we wan't to store next track
2770 metadata there). */
2771 if (!audio_have_free_tracks())
2773 logf("No free tracks");
2774 return false;
2777 last_peek_offset++;
2778 peek_again:
2779 logf("Buffering track:%d/%d", track_widx, track_ridx);
2780 /* Get track name from current playlist read position. */
2781 while ((trackname = playlist_peek(last_peek_offset)) != NULL)
2783 /* Handle broken playlists. */
2784 fd = open(trackname, O_RDONLY);
2785 if (fd < 0)
2787 logf("Open failed");
2788 /* Skip invalid entry from playlist. */
2789 playlist_skip_entry(NULL, last_peek_offset);
2791 else
2792 break;
2795 if (!trackname)
2797 logf("End-of-playlist");
2798 playlist_end = true;
2799 return false;
2802 tracks[track_widx].filesize = filesize(fd);
2804 /* Get track metadata if we don't already have it. */
2805 if (tracks[track_widx].id3_hid <= 0)
2807 if (get_metadata(&id3, fd, trackname))
2809 tracks[track_widx].id3_hid = bufalloc(&id3, sizeof(struct mp3entry),
2810 TYPE_ID3);
2811 tracks[track_widx].taginfo_ready = (tracks[track_widx].id3_hid > 0);
2813 if (tracks[track_widx].id3_hid <= 0)
2815 DEBUGF("failed to allocate space for metadata\n");
2816 last_peek_offset--;
2817 close(fd);
2818 return false;
2821 if (track_widx == track_ridx)
2822 copy_mp3entry(&curtrack_id3, &id3);
2823 else if (track_widx == ((track_ridx + 1) & MAX_TRACK_MASK))
2824 copy_mp3entry(&nexttrack_id3, &id3);
2826 if (start_play)
2828 track_changed = true;
2829 playlist_update_resume_info(audio_current_track());
2832 else
2834 logf("mde:%s!",trackname);
2836 /* Skip invalid entry from playlist. */
2837 playlist_skip_entry(NULL, last_peek_offset);
2838 tracks[track_widx].taginfo_ready = false;
2839 goto peek_again;
2844 close(fd);
2846 /* Set default values */
2847 if (start_play)
2849 int last_codec = current_codec;
2851 set_current_codec(CODEC_IDX_AUDIO);
2852 conf_watermark = AUDIO_DEFAULT_WATERMARK;
2853 conf_filechunk = AUDIO_DEFAULT_FILECHUNK;
2854 conf_preseek = AUDIO_REBUFFER_GUESS_SIZE;
2855 dsp_configure(DSP_RESET, 0);
2856 set_current_codec(last_codec);
2858 track_changed = true;
2859 playlist_update_resume_info(audio_current_track());
2862 #if 0
2863 if (cuesheet_is_enabled() && tracks[track_widx].id3.cuesheet_type == 1)
2865 char cuepath[MAX_PATH];
2867 struct cuesheet *cue = start_play ? curr_cue : temp_cue;
2869 if (look_for_cuesheet_file(trackname, cuepath) &&
2870 parse_cuesheet(cuepath, cue))
2872 strcpy((cue)->audio_filename, trackname);
2873 if (start_play)
2874 cue_spoof_id3(curr_cue, &tracks[track_widx].id3);
2877 #endif
2879 /* Load the codec. */
2880 if (!audio_loadcodec(start_play))
2882 #if 0
2883 /* Set filesize to zero to indicate no file was loaded. */
2884 /* tracks[track_widx].filesize = 0;
2885 tracks[track_widx].filerem = 0;
2886 close(current_fd);
2887 current_fd = -1; */
2889 if (tracks[track_widx].codecsize)
2891 /* No space for codec on buffer, not an error */
2892 tracks[track_widx].codecsize = 0;
2893 return false;
2896 /* This is an error condition, either no codec was found, or reading
2897 * the codec file failed part way through, either way, skip the track */
2898 snprintf(msgbuf, sizeof(msgbuf)-1, "No codec for: %s", trackname);
2899 /* We should not use gui_syncplash from audio thread! */
2900 gui_syncsplash(HZ*2, msgbuf);
2901 /* Skip invalid entry from playlist. */
2902 playlist_skip_entry(NULL, last_peek_offset);
2903 tracks[track_widx].taginfo_ready = false;
2904 goto peek_again;
2905 #endif
2906 return false;
2909 struct mp3entry *track_id3;
2911 if (track_widx == track_ridx)
2912 track_id3 = &curtrack_id3;
2913 else if (track_widx == ((track_ridx + 1) & MAX_TRACK_MASK))
2914 track_id3 = &nexttrack_id3;
2915 else
2916 track_id3 = bufgetid3(tracks[track_widx].id3_hid);
2918 /* tracks[track_widx].start_pos = 0; */
2919 set_filebuf_watermark(buffer_margin);
2920 track_id3->elapsed = 0;
2922 if (offset > 0)
2924 switch (track_id3->codectype) {
2925 case AFMT_MPA_L1:
2926 case AFMT_MPA_L2:
2927 case AFMT_MPA_L3:
2928 file_offset = offset;
2929 track_id3->offset = offset;
2930 audio_set_elapsed(track_id3);
2931 ci.curpos = offset;
2932 break;
2934 case AFMT_WAVPACK:
2935 file_offset = offset;
2936 track_id3->offset = offset;
2937 track_id3->elapsed = track_id3->length / 2;
2938 ci.curpos = offset;
2939 break;
2941 case AFMT_OGG_VORBIS:
2942 case AFMT_SPEEX:
2943 case AFMT_FLAC:
2944 case AFMT_PCM_WAV:
2945 case AFMT_A52:
2946 case AFMT_AAC:
2947 case AFMT_MPC:
2948 case AFMT_APE:
2949 track_id3->offset = offset;
2950 break;
2954 logf("alt:%s", trackname);
2955 /* tracks[track_widx].buf_idx = buf_widx; */
2957 //return audio_read_file(rebuffer);
2959 tracks[track_widx].audio_hid = bufopen(trackname, file_offset, TYPE_AUDIO);
2961 if (tracks[track_widx].audio_hid <= 0)
2962 return false;
2964 if (start_play)
2966 LOGFQUEUE("audio >| buffering Q_BUFFER_HANDLE");
2967 queue_send(&buffering_queue, Q_BUFFER_HANDLE, tracks[track_widx].audio_hid);
2970 track_widx++;
2971 track_widx &= MAX_TRACK_MASK;
2973 return true;
2976 #if 0
2977 static bool audio_read_next_metadata(void)
2979 int fd;
2980 char *trackname;
2981 int next_idx;
2982 int status;
2984 next_idx = track_widx;
2985 if (tracks[next_idx].id3_hid > 0)
2987 next_idx++;
2988 next_idx &= MAX_TRACK_MASK;
2990 if (tracks[next_idx].id3_hid > 0)
2991 return true;
2994 trackname = playlist_peek(last_peek_offset + 1);
2995 if (!trackname)
2996 return false;
2998 fd = open(trackname, O_RDONLY);
2999 if (fd < 0)
3000 return false;
3002 struct mp3entry id3;
3004 status = get_metadata(&id3, fd, trackname);
3005 /* Preload the glyphs in the tags */
3006 if (status)
3008 tracks[next_idx].id3_hid = bufalloc(&id3, sizeof(struct mp3entry), TYPE_ID3);
3010 if (tracks[next_idx].id3_hid > 0)
3012 tracks[next_idx].taginfo_ready = true;
3013 if (id3.title)
3014 lcd_getstringsize(id3.title, NULL, NULL);
3015 if (id3.artist)
3016 lcd_getstringsize(id3.artist, NULL, NULL);
3017 if (id3.album)
3018 lcd_getstringsize(id3.album, NULL, NULL);
3020 else
3021 status = false;
3023 close(fd);
3025 return status;
3027 #endif
3029 /* Send callback events to notify about new tracks. */
3030 static void audio_generate_postbuffer_events(void)
3032 int cur_idx;
3033 int last_idx = -1;
3035 logf("Postbuffer:%d/%d",track_ridx,track_widx);
3037 if (audio_have_tracks())
3039 cur_idx = track_ridx;
3041 while (1) {
3042 if (!tracks[cur_idx].event_sent)
3044 if (last_idx >= 0 && !tracks[last_idx].event_sent)
3046 /* Mark the event 'sent' even if we don't really send one */
3047 tracks[last_idx].event_sent = true;
3048 if (track_buffer_callback)
3049 track_buffer_callback(bufgetid3(tracks[last_idx].id3_hid), false);
3051 last_idx = cur_idx;
3053 if (cur_idx == track_widx)
3054 break;
3055 cur_idx++;
3056 cur_idx &= MAX_TRACK_MASK;
3059 if (last_idx >= 0 && !tracks[last_idx].event_sent)
3061 tracks[last_idx].event_sent = true;
3062 if (track_buffer_callback)
3063 track_buffer_callback(bufgetid3(tracks[last_idx].id3_hid), true);
3068 static bool audio_initialize_buffer_fill(bool clear_tracks)
3070 /* Don't initialize if we're already initialized */
3071 if (filling)
3072 return true;
3074 logf("Starting buffer fill");
3076 /* Set the filling flag true before calling audio_clear_tracks as that
3077 * function can yield and we start looping. */
3078 filling = true;
3080 if (clear_tracks)
3081 audio_clear_track_entries(false);
3083 /* Save the current resume position once. */
3084 playlist_update_resume_info(audio_current_track());
3086 return true;
3089 static void audio_fill_file_buffer(
3090 bool start_play, bool rebuffer, size_t offset)
3092 bool had_next_track = audio_next_track() != NULL;
3093 bool continue_buffering;
3095 /* Must reset the buffer before use if trashed or voice only - voice
3096 file size shouldn't have changed so we can go straight from
3097 BUFFER_STATE_VOICED_ONLY to BUFFER_STATE_INITIALIZED */
3098 if (buffer_state != BUFFER_STATE_INITIALIZED)
3099 audio_reset_buffer();
3101 if (!audio_initialize_buffer_fill(!start_play))
3102 return ;
3104 continue_buffering = audio_load_track(offset, start_play, rebuffer);
3106 if (!had_next_track && audio_next_track())
3107 track_changed = true;
3109 /* If we're done buffering */
3110 if (!continue_buffering)
3112 //audio_read_next_metadata();
3114 audio_generate_postbuffer_events();
3115 filling = false;
3117 #ifndef SIMULATOR
3118 ata_sleep();
3119 #endif
3123 static void audio_rebuffer(void)
3125 logf("Forcing rebuffer");
3127 #if 0
3128 /* Stop in progress fill, and clear open file descriptor */
3129 if (current_fd >= 0)
3131 close(current_fd);
3132 current_fd = -1;
3134 filling = false;
3136 /* Reset buffer and track pointers */
3137 CUR_TI->buf_idx = buf_ridx = buf_widx = 0;
3138 track_widx = track_ridx;
3139 audio_clear_track_entries(true);
3140 CUR_TI->available = 0;
3142 /* Fill the buffer */
3143 last_peek_offset = -1;
3144 CUR_TI->filesize = 0;
3145 CUR_TI->start_pos = 0;
3146 ci.curpos = 0;
3147 #endif
3149 if (!CUR_TI->taginfo_ready)
3150 memset(&curtrack_id3, 0, sizeof(struct mp3entry));
3152 audio_fill_file_buffer(false, true, 0);
3155 static int audio_check_new_track(void)
3157 DEBUGF("audio_check_new_track\n");
3159 int track_count = audio_track_count();
3160 int old_track_ridx = track_ridx;
3161 int next_idx;
3162 bool forward;
3164 if (dir_skip)
3166 dir_skip = false;
3167 if (playlist_next_dir(ci.new_track))
3169 ci.new_track = 0;
3170 CUR_TI->taginfo_ready = false;
3171 audio_rebuffer();
3172 goto skip_done;
3174 else
3176 LOGFQUEUE("audio >|= codec Q_CODEC_REQUEST_FAILED");
3177 return Q_CODEC_REQUEST_FAILED;
3181 if (new_playlist)
3182 ci.new_track = 0;
3184 /* If the playlist isn't that big */
3185 if (!playlist_check(ci.new_track))
3187 if (ci.new_track >= 0)
3189 LOGFQUEUE("audio >|= codec Q_CODEC_REQUEST_FAILED");
3190 return Q_CODEC_REQUEST_FAILED;
3192 /* Find the beginning backward if the user over-skips it */
3193 while (!playlist_check(++ci.new_track))
3194 if (ci.new_track >= 0)
3196 LOGFQUEUE("audio >|= codec Q_CODEC_REQUEST_FAILED");
3197 return Q_CODEC_REQUEST_FAILED;
3200 /* Update the playlist */
3201 last_peek_offset -= ci.new_track;
3203 if (playlist_next(ci.new_track) < 0)
3205 LOGFQUEUE("audio >|= codec Q_CODEC_REQUEST_FAILED");
3206 return Q_CODEC_REQUEST_FAILED;
3209 if (new_playlist)
3211 ci.new_track = 1;
3212 new_playlist = false;
3215 /* Save the old track */
3216 /* prev_ti = CUR_TI; */
3218 int i, idx;
3219 for (i = 0; i < ci.new_track; i++)
3221 idx = (track_ridx + i) & MAX_TRACK_MASK;
3222 close_track_handles(&tracks[idx]);
3225 /* Move to the new track */
3226 track_ridx += ci.new_track;
3227 track_ridx &= MAX_TRACK_MASK;
3229 if (CUR_TI->id3_hid > 0)
3230 copy_mp3entry(&curtrack_id3, bufgetid3(CUR_TI->id3_hid));
3232 next_idx = track_ridx + 1;
3233 next_idx &= MAX_TRACK_MASK;
3235 if (tracks[next_idx].id3_hid > 0)
3236 copy_mp3entry(&nexttrack_id3, bufgetid3(tracks[next_idx].id3_hid));
3238 if (automatic_skip)
3239 playlist_end = false;
3241 track_changed = !automatic_skip;
3243 /* If it is not safe to even skip this many track entries */
3244 if (ci.new_track >= track_count || ci.new_track <= track_count - MAX_TRACK)
3246 ci.new_track = 0;
3247 CUR_TI->taginfo_ready = false;
3248 audio_rebuffer();
3249 goto skip_done;
3252 forward = ci.new_track > 0;
3253 ci.new_track = 0;
3255 /* If the target track is clearly not in memory */
3256 if (CUR_TI->filesize == 0 || !CUR_TI->taginfo_ready)
3258 audio_rebuffer();
3259 goto skip_done;
3262 /* The track may be in memory, see if it really is */
3263 if (forward)
3265 if (!audio_buffer_wind_forward(track_ridx, old_track_ridx))
3266 audio_rebuffer();
3268 else
3270 int cur_idx = track_ridx;
3271 bool taginfo_ready = true;
3272 bool wrap = track_ridx > old_track_ridx;
3274 while (1)
3276 cur_idx++;
3277 cur_idx &= MAX_TRACK_MASK;
3278 if (!(wrap || cur_idx < old_track_ridx))
3279 break;
3281 /* If we hit a track in between without valid tag info, bail */
3282 if (!tracks[cur_idx].taginfo_ready)
3284 taginfo_ready = false;
3285 break;
3288 tracks[cur_idx].available = tracks[cur_idx].filesize;
3289 if (tracks[cur_idx].codecsize)
3290 tracks[cur_idx].has_codec = true;*/
3292 if (taginfo_ready)
3294 if (!audio_buffer_wind_backward(track_ridx, old_track_ridx))
3295 audio_rebuffer();
3297 else
3299 CUR_TI->taginfo_ready = false;
3300 audio_rebuffer();
3304 skip_done:
3305 audio_update_trackinfo();
3306 LOGFQUEUE("audio >|= codec Q_CODEC_REQUEST_COMPLETE");
3307 return Q_CODEC_REQUEST_COMPLETE;
3310 #if 0
3311 static int audio_rebuffer_and_seek(size_t newpos)
3313 size_t real_preseek;
3314 int fd;
3315 char *trackname;
3317 /* (Re-)open current track's file handle. */
3318 trackname = playlist_peek(0);
3319 fd = open(trackname, O_RDONLY);
3320 if (fd < 0)
3322 LOGFQUEUE("audio >|= codec Q_CODEC_REQUEST_FAILED");
3323 return Q_CODEC_REQUEST_FAILED;
3326 if (current_fd >= 0)
3327 close(current_fd);
3328 current_fd = fd;
3330 playlist_end = false;
3332 ci.curpos = newpos;
3334 /* Clear codec buffer. */
3335 track_widx = track_ridx;
3336 tracks[track_widx].buf_idx = buf_widx = buf_ridx = 0;
3338 last_peek_offset = 0;
3339 filling = false;
3340 audio_initialize_buffer_fill(true);
3342 /* This may have been tweaked by the id3v1 code */
3343 CUR_TI->filesize=filesize(fd);
3344 if (newpos > conf_preseek)
3346 CUR_TI->start_pos = newpos - conf_preseek;
3347 lseek(current_fd, CUR_TI->start_pos, SEEK_SET);
3348 CUR_TI->filerem = CUR_TI->filesize - CUR_TI->start_pos;
3349 real_preseek = conf_preseek;
3351 else
3353 CUR_TI->start_pos = 0;
3354 CUR_TI->filerem = CUR_TI->filesize;
3355 real_preseek = newpos;
3358 CUR_TI->available = 0;
3360 audio_read_file(real_preseek);
3362 /* Account for the data we just read that is 'behind' us now */
3363 CUR_TI->available -= real_preseek;
3365 buf_ridx = RINGBUF_ADD(buf_ridx, real_preseek);
3367 (void)newpos;
3368 DEBUGF("/!\\ not implemented /!\\");
3369 LOGFQUEUE("audio >|= codec Q_CODEC_REQUEST_COMPLETE");
3370 return Q_CODEC_REQUEST_COMPLETE;
3372 #endif
3374 void audio_set_track_buffer_event(void (*handler)(struct mp3entry *id3,
3375 bool last_track))
3377 track_buffer_callback = handler;
3380 void audio_set_track_unbuffer_event(void (*handler)(struct mp3entry *id3,
3381 bool last_track))
3383 track_unbuffer_callback = handler;
3386 void audio_set_track_changed_event(void (*handler)(struct mp3entry *id3))
3388 track_changed_callback = handler;
3391 unsigned long audio_prev_elapsed(void)
3393 return prev_track_elapsed;
3396 static void audio_stop_codec_flush(void)
3398 ci.stop_codec = true;
3399 pcmbuf_pause(true);
3401 while (audio_codec_loaded)
3402 yield();
3404 /* If the audio codec is not loaded any more, and the audio is still
3405 * playing, it is now and _only_ now safe to call this function from the
3406 * audio thread */
3407 if (pcm_is_playing())
3408 pcmbuf_play_stop();
3409 pcmbuf_pause(paused);
3412 static void audio_stop_playback(void)
3414 /* If we were playing, save resume information */
3415 if (playing)
3417 struct mp3entry *id3 = NULL;
3419 if (!playlist_end || !ci.stop_codec)
3421 /* Set this early, the outside code yields and may allow the codec
3422 to try to wait for a reply on a buffer wait */
3423 ci.stop_codec = true;
3424 id3 = audio_current_track();
3427 /* Save the current playing spot, or NULL if the playlist has ended */
3428 playlist_update_resume_info(id3);
3430 prev_track_elapsed = curtrack_id3.elapsed;
3432 /* Increment index so runtime info is saved in audio_clear_track_entries().
3433 * Done here, as audio_stop_playback() may be called more than once.
3434 * Don't update runtime unless playback is stopped because of end of playlist.
3435 * Updating runtime when manually stopping a tracks, can destroy autoscores
3436 * and playcounts.
3438 if (playlist_end)
3440 track_ridx++;
3441 track_ridx &= MAX_TRACK_MASK;
3445 filling = false;
3446 paused = false;
3447 audio_stop_codec_flush();
3448 playing = false;
3450 /* Close all tracks */
3451 audio_release_tracks();
3453 /* Mark all entries null. */
3454 audio_clear_track_entries(false);
3457 static void audio_play_start(size_t offset)
3459 #if INPUT_SRC_CAPS != 0
3460 audio_set_input_source(AUDIO_SRC_PLAYBACK, SRCF_PLAYBACK);
3461 audio_set_output_source(AUDIO_SRC_PLAYBACK);
3462 #endif
3464 /* Wait for any previously playing audio to flush - TODO: Not necessary? */
3465 paused = false;
3466 audio_stop_codec_flush();
3468 track_changed = true;
3469 playlist_end = false;
3471 playing = true;
3473 ci.new_track = 0;
3474 ci.seek_time = 0;
3475 wps_offset = 0;
3477 sound_set_volume(global_settings.volume);
3478 track_widx = track_ridx = 0;
3480 /* Mark all entries null. */
3481 memset(tracks, 0, sizeof(struct track_info) * MAX_TRACK);
3483 last_peek_offset = -1;
3485 /* Officially playing */
3486 queue_reply(&audio_queue, 1);
3488 audio_fill_file_buffer(true, false, offset);
3490 LOGFQUEUE("audio > audio Q_AUDIO_TRACK_CHANGED");
3491 queue_post(&audio_queue, Q_AUDIO_TRACK_CHANGED, 0);
3495 /* Invalidates all but currently playing track. */
3496 static void audio_invalidate_tracks(void)
3498 #if 0
3499 if (audio_have_tracks())
3501 last_peek_offset = 0;
3502 playlist_end = false;
3503 track_widx = track_ridx;
3505 /* Mark all other entries null (also buffered wrong metadata). */
3506 audio_clear_track_entries(true);
3508 /* If the current track is fully buffered, advance the write pointer */
3509 if (tracks[track_widx].filerem == 0)
3510 track_widx = (track_widx + 1) & MAX_TRACK_MASK;
3512 buf_widx = RINGBUF_ADD(buf_ridx, CUR_TI->available);
3514 audio_read_next_metadata();
3516 #endif
3519 static void audio_new_playlist(void)
3521 /* Prepare to start a new fill from the beginning of the playlist */
3522 last_peek_offset = -1;
3523 if (audio_have_tracks())
3525 if (paused)
3526 skipped_during_pause = true;
3527 playlist_end = false;
3528 track_widx = track_ridx;
3529 audio_clear_track_entries(true);
3531 track_widx++;
3532 track_widx &= MAX_TRACK_MASK;
3534 /* Mark the current track as invalid to prevent skipping back to it */
3535 CUR_TI->taginfo_ready = false;
3538 /* Signal the codec to initiate a track change forward */
3539 new_playlist = true;
3540 ci.new_track = 1;
3542 /* Officially playing */
3543 queue_reply(&audio_queue, 1);
3545 audio_fill_file_buffer(false, true, 0);
3548 static void audio_initiate_track_change(long direction)
3550 playlist_end = false;
3551 ci.new_track += direction;
3552 wps_offset -= direction;
3553 if (paused)
3554 skipped_during_pause = true;
3557 static void audio_initiate_dir_change(long direction)
3559 playlist_end = false;
3560 dir_skip = true;
3561 ci.new_track = direction;
3562 if (paused)
3563 skipped_during_pause = true;
3567 * Layout audio buffer as follows - iram buffer depends on target:
3568 * [|SWAP:iram][|TALK]|MALLOC|FILE|GUARD|PCM|[SWAP:dram[|iram]|]
3570 static void audio_reset_buffer(void)
3572 /* see audio_get_recording_buffer if this is modified */
3573 logf("audio_reset_buffer");
3575 /* If the setup of anything allocated before the file buffer is
3576 changed, do check the adjustments after the buffer_alloc call
3577 as it will likely be affected and need sliding over */
3579 /* Initially set up file buffer as all space available */
3580 malloc_buf = audiobuf + talk_get_bufsize();
3581 /* Align the malloc buf to line size. Especially important to cf
3582 targets that do line reads/writes. */
3583 malloc_buf = (unsigned char *)(((uintptr_t)malloc_buf + 15) & ~15);
3584 filebuf = malloc_buf + MALLOC_BUFSIZE; /* filebuf line align implied */
3585 filebuflen = audiobufend - filebuf;
3587 /* Allow for codec swap space at end of audio buffer */
3588 if (talk_voice_required())
3590 /* Layout of swap buffer:
3591 * #ifdef IRAM_STEAL (dedicated iram_buf):
3592 * |iram_buf|...audiobuf...|dram_buf|audiobufend
3593 * #else:
3594 * audiobuf...|dram_buf|iram_buf|audiobufend
3596 #ifdef PLAYBACK_VOICE
3597 /* Check for an absolutely nasty situation which should never,
3598 ever happen - frankly should just panic */
3599 if (voice_codec_loaded && current_codec != CODEC_IDX_VOICE)
3601 logf("buffer reset with voice swapped");
3603 /* line align length which line aligns the calculations below since
3604 all sizes are also at least line aligned - needed for memswap128 */
3605 filebuflen &= ~15;
3606 #ifdef IRAM_STEAL
3607 filebuflen -= CODEC_SIZE;
3608 #else
3609 filebuflen -= CODEC_SIZE + CODEC_IRAM_SIZE;
3610 #endif
3611 /* Allocate buffers for swapping voice <=> audio */
3612 /* If using IRAM for plugins voice IRAM swap buffer must be dedicated
3613 and out of the way of buffer usage or else a call to audio_get_buffer
3614 and subsequent buffer use might trash the swap space. A plugin
3615 initializing IRAM after getting the full buffer would present similar
3616 problem. Options include: failing the request if the other buffer
3617 has been obtained already or never allowing use of the voice IRAM
3618 buffer within the audio buffer. Using buffer_alloc basically
3619 implements the second in a more convenient way. */
3620 dram_buf = filebuf + filebuflen;
3622 #ifdef IRAM_STEAL
3623 /* Allocate voice IRAM swap buffer once */
3624 if (iram_buf == NULL)
3626 iram_buf = buffer_alloc(CODEC_IRAM_SIZE);
3627 /* buffer_alloc moves audiobuf; this is safe because only the end
3628 * has been touched so far in this function and the address of
3629 * filebuf + filebuflen is not changed */
3630 malloc_buf += CODEC_IRAM_SIZE;
3631 filebuf += CODEC_IRAM_SIZE;
3632 filebuflen -= CODEC_IRAM_SIZE;
3634 #else
3635 /* Allocate iram_buf after dram_buf */
3636 iram_buf = dram_buf + CODEC_SIZE;
3637 #endif /* IRAM_STEAL */
3638 #endif /* PLAYBACK_VOICE */
3640 else
3642 #ifdef PLAYBACK_VOICE
3643 /* No swap buffers needed */
3644 iram_buf = NULL;
3645 dram_buf = NULL;
3646 #endif
3649 /* Subtract whatever the pcm buffer says it used plus the guard buffer */
3650 filebuflen -= pcmbuf_init(filebuf + filebuflen) + GUARD_BUFSIZE;
3652 /* Make sure filebuflen is a longword multiple after adjustment - filebuf
3653 will already be line aligned */
3654 filebuflen &= ~3;
3656 /* Set the high watermark as 75% full...or 25% empty :) */
3657 #if MEM > 8
3658 high_watermark = 3*filebuflen / 4;
3659 #endif
3661 /* Clear any references to the file buffer */
3662 buffer_state = BUFFER_STATE_INITIALIZED;
3664 #if defined(ROCKBOX_HAS_LOGF) && defined(LOGF_ENABLE)
3665 /* Make sure everything adds up - yes, some info is a bit redundant but
3666 aids viewing and the sumation of certain variables should add up to
3667 the location of others. */
3669 size_t pcmbufsize;
3670 unsigned char * pcmbuf = pcmbuf_get_meminfo(&pcmbufsize);
3671 logf("mabuf: %08X", (unsigned)malloc_buf);
3672 logf("mabufe: %08X", (unsigned)(malloc_buf + MALLOC_BUFSIZE));
3673 logf("fbuf: %08X", (unsigned)filebuf);
3674 logf("fbufe: %08X", (unsigned)(filebuf + filebuflen));
3675 logf("gbuf: %08X", (unsigned)(filebuf + filebuflen));
3676 logf("gbufe: %08X", (unsigned)(filebuf + filebuflen + GUARD_BUFSIZE));
3677 logf("pcmb: %08X", (unsigned)pcmbuf);
3678 logf("pcmbe: %08X", (unsigned)(pcmbuf + pcmbufsize));
3679 if (dram_buf)
3681 logf("dramb: %08X", (unsigned)dram_buf);
3682 logf("drambe: %08X", (unsigned)(dram_buf + CODEC_SIZE));
3684 if (iram_buf)
3686 logf("iramb: %08X", (unsigned)iram_buf);
3687 logf("irambe: %08X", (unsigned)(iram_buf + CODEC_IRAM_SIZE));
3690 #endif
3693 #if MEM > 8
3694 /* we dont want this rebuffering on targets with little ram
3695 because the disk may never spin down */
3696 static bool ata_fillbuffer_callback(void)
3698 queue_post(&audio_queue, Q_AUDIO_FILL_BUFFER_IF_ACTIVE_ATA, 0);
3699 return true;
3701 #endif
3703 static void audio_thread(void)
3705 struct queue_event ev;
3707 pcm_postinit();
3709 #ifdef PLAYBACK_VOICE
3710 /* Unlock semaphore that init stage locks before creating this thread */
3711 semaphore_release(&sem_codecthread);
3713 /* Buffers must be set up by now - should panic - really */
3714 if (buffer_state != BUFFER_STATE_INITIALIZED)
3716 logf("audio_thread start: no buffer");
3719 /* Have to wait for voice to load up or else the codec swap will be
3720 invalid when an audio codec is loaded */
3721 wait_for_voice_swap_in();
3722 #endif
3724 while (1)
3726 if (filling)
3728 queue_wait_w_tmo(&audio_queue, &ev, 0);
3729 if (ev.id == SYS_TIMEOUT)
3730 ev.id = Q_AUDIO_FILL_BUFFER;
3732 else
3734 queue_wait_w_tmo(&audio_queue, &ev, HZ/2);
3735 #if MEM > 8
3736 if (playing && (ev.id == SYS_TIMEOUT) &&
3737 (bufused() < high_watermark))
3738 register_ata_idle_func(ata_fillbuffer_callback);
3739 #endif
3742 switch (ev.id) {
3743 #if MEM > 8
3744 case Q_AUDIO_FILL_BUFFER_IF_ACTIVE_ATA:
3745 /* only fill if the disk is still spining */
3746 #ifndef SIMULATOR
3747 if (!ata_disk_is_active())
3748 break;
3749 #endif
3750 #endif /* MEM > 8 */
3751 /* else fall through to Q_AUDIO_FILL_BUFFER */
3752 case Q_AUDIO_FILL_BUFFER:
3753 LOGFQUEUE("audio < Q_AUDIO_FILL_BUFFER");
3754 if (!filling)
3755 if (!playing || playlist_end || ci.stop_codec)
3756 break;
3757 audio_fill_file_buffer(false, false, 0);
3758 break;
3760 case Q_AUDIO_PLAY:
3761 LOGFQUEUE("audio < Q_AUDIO_PLAY");
3762 if (playing && ev.data <= 0)
3763 audio_new_playlist();
3764 else
3766 audio_stop_playback();
3767 audio_play_start((size_t)ev.data);
3769 break;
3771 case Q_AUDIO_STOP:
3772 LOGFQUEUE("audio < Q_AUDIO_STOP");
3773 if (playing)
3774 audio_stop_playback();
3775 if (ev.data != 0)
3776 queue_clear(&audio_queue);
3777 break;
3779 case Q_AUDIO_PAUSE:
3780 LOGFQUEUE("audio < Q_AUDIO_PAUSE");
3781 if (!(bool) ev.data && skipped_during_pause && !pcmbuf_is_crossfade_active())
3782 pcmbuf_play_stop(); /* Flush old track on resume after skip */
3783 skipped_during_pause = false;
3784 if (!playing)
3785 break;
3786 pcmbuf_pause((bool)ev.data);
3787 paused = (bool)ev.data;
3788 break;
3790 case Q_AUDIO_SKIP:
3791 LOGFQUEUE("audio < Q_AUDIO_SKIP");
3792 audio_initiate_track_change((long)ev.data);
3793 break;
3795 case Q_AUDIO_PRE_FF_REWIND:
3796 LOGFQUEUE("audio < Q_AUDIO_PRE_FF_REWIND");
3797 if (!playing)
3798 break;
3799 pcmbuf_pause(true);
3800 break;
3802 case Q_AUDIO_FF_REWIND:
3803 LOGFQUEUE("audio < Q_AUDIO_FF_REWIND");
3804 if (!playing)
3805 break;
3806 ci.seek_time = (long)ev.data+1;
3807 break;
3809 #if 0
3810 case Q_AUDIO_REBUFFER_SEEK:
3811 LOGFQUEUE("audio < Q_AUDIO_REBUFFER_SEEK");
3812 queue_reply(&audio_queue, audio_rebuffer_and_seek(ev.data));
3813 break;
3814 #endif
3816 case Q_AUDIO_CHECK_NEW_TRACK:
3817 LOGFQUEUE("audio < Q_AUDIO_CHECK_NEW_TRACK");
3818 queue_reply(&audio_queue, audio_check_new_track());
3819 break;
3821 case Q_AUDIO_DIR_SKIP:
3822 LOGFQUEUE("audio < Q_AUDIO_DIR_SKIP");
3823 playlist_end = false;
3824 audio_initiate_dir_change(ev.data);
3825 break;
3827 case Q_AUDIO_FLUSH:
3828 LOGFQUEUE("audio < Q_AUDIO_FLUSH");
3829 audio_invalidate_tracks();
3830 break;
3832 case Q_AUDIO_TRACK_CHANGED:
3833 LOGFQUEUE("audio < Q_AUDIO_TRACK_CHANGED");
3834 if (track_changed_callback)
3835 track_changed_callback(&curtrack_id3);
3836 track_changed = true;
3837 playlist_update_resume_info(audio_current_track());
3838 break;
3840 #ifndef SIMULATOR
3841 case SYS_USB_CONNECTED:
3842 LOGFQUEUE("audio < SYS_USB_CONNECTED");
3843 if (playing)
3844 audio_stop_playback();
3845 usb_acknowledge(SYS_USB_CONNECTED_ACK);
3846 usb_wait_for_disconnect(&audio_queue);
3847 break;
3848 #endif
3850 case SYS_TIMEOUT:
3851 LOGFQUEUE_SYS_TIMEOUT("audio < SYS_TIMEOUT");
3852 break;
3854 default:
3855 //LOGFQUEUE("audio < default");
3856 break;
3857 } /* end switch */
3858 } /* end while */
3861 #ifdef ROCKBOX_HAS_LOGF
3862 static void audio_test_track_changed_event(struct mp3entry *id3)
3864 (void)id3;
3866 logf("tce:%s", id3->path);
3868 #endif
3870 /* Initialize the audio system - called from init() in main.c.
3871 * Last function because of all the references to internal symbols
3873 void audio_init(void)
3875 #ifdef PLAYBACK_VOICE
3876 static bool voicetagtrue = true;
3877 static struct mp3entry id3_voice;
3878 struct thread_entry *voice_thread_p = NULL;
3879 #endif
3880 struct thread_entry *audio_thread_p;
3882 /* Can never do this twice */
3883 if (audio_is_initialized)
3885 logf("audio: already initialized");
3886 return;
3889 logf("audio: initializing");
3891 /* Initialize queues before giving control elsewhere in case it likes
3892 to send messages. Thread creation will be delayed however so nothing
3893 starts running until ready if something yields such as talk_init. */
3894 #ifdef PLAYBACK_VOICE
3895 /* Take ownership of lock to prevent playback of anything before audio
3896 hardware is initialized - audio thread unlocks it after final init
3897 stage */
3898 semaphore_init(&sem_codecthread, 1, 0);
3899 event_init(&event_codecthread, EVENT_MANUAL | STATE_SIGNALED);
3900 #endif
3901 queue_init(&audio_queue, true);
3902 queue_enable_queue_send(&audio_queue, &audio_queue_sender_list);
3903 queue_init(&codec_queue, true);
3904 queue_enable_queue_send(&codec_queue, &codec_queue_sender_list);
3906 pcm_init();
3908 #ifdef ROCKBOX_HAS_LOGF
3909 audio_set_track_changed_event(audio_test_track_changed_event);
3910 #endif
3912 /* Initialize codec api. */
3913 ci.read_filebuf = codec_filebuf_callback;
3914 ci.pcmbuf_insert = codec_pcmbuf_insert_callback;
3915 ci.get_codec_memory = codec_get_memory_callback;
3916 ci.request_buffer = codec_request_buffer_callback;
3917 ci.advance_buffer = codec_advance_buffer_callback;
3918 ci.advance_buffer_loc = codec_advance_buffer_loc_callback;
3919 ci.request_next_track = codec_request_next_track_callback;
3920 ci.mp3_get_filepos = codec_mp3_get_filepos_callback;
3921 ci.seek_buffer = codec_seek_buffer_callback;
3922 ci.seek_complete = codec_seek_complete_callback;
3923 ci.set_elapsed = codec_set_elapsed_callback;
3924 ci.set_offset = codec_set_offset_callback;
3925 ci.configure = codec_configure_callback;
3926 ci.discard_codec = codec_discard_codec_callback;
3928 /* Initialize voice codec api. */
3929 #ifdef PLAYBACK_VOICE
3930 memcpy(&ci_voice, &ci, sizeof(ci_voice));
3931 memset(&id3_voice, 0, sizeof(id3_voice));
3932 ci_voice.read_filebuf = voice_filebuf_callback;
3933 ci_voice.pcmbuf_insert = voice_pcmbuf_insert_callback;
3934 ci_voice.get_codec_memory = voice_get_memory_callback;
3935 ci_voice.request_buffer = voice_request_buffer_callback;
3936 ci_voice.advance_buffer = voice_advance_buffer_callback;
3937 ci_voice.advance_buffer_loc = voice_advance_buffer_loc_callback;
3938 ci_voice.request_next_track = voice_request_next_track_callback;
3939 ci_voice.mp3_get_filepos = voice_mp3_get_filepos_callback;
3940 ci_voice.seek_buffer = voice_seek_buffer_callback;
3941 ci_voice.seek_complete = voice_do_nothing;
3942 ci_voice.set_elapsed = voice_set_elapsed_callback;
3943 ci_voice.set_offset = voice_set_offset_callback;
3944 ci_voice.configure = voice_configure_callback;
3945 ci_voice.discard_codec = voice_do_nothing;
3946 ci_voice.taginfo_ready = &voicetagtrue;
3947 ci_voice.id3 = &id3_voice;
3948 id3_voice.frequency = 11200;
3949 id3_voice.length = 1000000L;
3950 #endif
3952 /* initialize the buffer */
3953 filebuf = audiobuf;
3955 /* audio_reset_buffer must to know the size of voice buffer so init
3956 talk first */
3957 talk_init();
3959 codec_thread_p = create_thread(
3960 codec_thread, codec_stack, sizeof(codec_stack),
3961 CREATE_THREAD_FROZEN,
3962 codec_thread_name IF_PRIO(, PRIORITY_PLAYBACK)
3963 IF_COP(, CPU));
3965 audio_thread_p = create_thread(audio_thread, audio_stack,
3966 sizeof(audio_stack), CREATE_THREAD_FROZEN,
3967 audio_thread_name IF_PRIO(, PRIORITY_BACKGROUND)
3968 IF_COP(, CPU));
3970 buffering_thread_p = create_thread( buffering_thread, buffering_stack,
3971 sizeof(buffering_stack), CREATE_THREAD_FROZEN,
3972 buffering_thread_name IF_PRIO(, PRIORITY_BUFFERING)
3973 IF_COP(, CPU, true));
3975 #ifdef PLAYBACK_VOICE
3976 /* TODO: Change this around when various speech codecs can be used */
3977 if (talk_voice_required())
3979 logf("Starting voice codec");
3980 queue_init(&voice_queue, true);
3981 voice_thread_p = create_thread(voice_thread, voice_stack,
3982 sizeof(voice_stack), CREATE_THREAD_FROZEN,
3983 voice_thread_name
3984 IF_PRIO(, PRIORITY_PLAYBACK) IF_COP(, CPU));
3986 #endif
3988 /* Set crossfade setting for next buffer init which should be about... */
3989 pcmbuf_crossfade_enable(global_settings.crossfade);
3991 /* ...now! Set up the buffers */
3992 audio_reset_buffer();
3994 buffering_init(filebuf, filebuflen);
3996 /* Probably safe to say */
3997 audio_is_initialized = true;
3999 sound_settings_apply();
4000 #ifdef HAVE_WM8758
4001 eq_hw_enable(global_settings.eq_hw_enabled);
4002 #endif
4003 #ifndef HAVE_FLASH_STORAGE
4004 audio_set_buffer_margin(global_settings.buffer_margin);
4005 #endif
4007 /* it's safe to let the threads run now */
4008 thread_thaw(codec_thread_p);
4009 #ifdef PLAYBACK_VOICE
4010 if (voice_thread_p)
4011 thread_thaw(voice_thread_p);
4012 #endif
4013 thread_thaw(audio_thread_p);
4014 thread_thaw(buffering_thread_p);
4015 } /* audio_init */