Kill warnings that annoy me when building for Gigabeat S.
[kugel-rb.git] / apps / playback.c
blobbce4b6b03021e3c564f7dc504bc10b161f670a2c
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: Pause should be handled in here, rather than PCMBUF so that voice can
21 * play whilst audio is paused */
23 #include <stdio.h>
24 #include <string.h>
25 #include <stdlib.h>
26 #include <ctype.h>
28 #include "system.h"
29 #include "thread.h"
30 #include "file.h"
31 #include "panic.h"
32 #include "memory.h"
33 #include "lcd.h"
34 #include "font.h"
35 #include "button.h"
36 #include "kernel.h"
37 #include "tree.h"
38 #include "debug.h"
39 #include "sprintf.h"
40 #include "settings.h"
41 #include "codecs.h"
42 #include "audio.h"
43 #include "buffering.h"
44 #include "events.h"
45 #include "voice_thread.h"
46 #include "mp3_playback.h"
47 #include "usb.h"
48 #include "status.h"
49 #include "ata.h"
50 #include "screens.h"
51 #include "playlist.h"
52 #include "playback.h"
53 #include "pcmbuf.h"
54 #include "buffer.h"
55 #include "dsp.h"
56 #include "abrepeat.h"
57 #include "cuesheet.h"
58 #ifdef HAVE_TAGCACHE
59 #include "tagcache.h"
60 #endif
61 #ifdef HAVE_LCD_BITMAP
62 #include "icons.h"
63 #include "peakmeter.h"
64 #include "action.h"
65 #include "albumart.h"
66 #endif
67 #include "lang.h"
68 #include "bookmark.h"
69 #include "misc.h"
70 #include "sound.h"
71 #include "metadata.h"
72 #include "splash.h"
73 #include "talk.h"
74 #include "ata_idle_notify.h"
76 #ifdef HAVE_RECORDING
77 #include "recording.h"
78 #include "talk.h"
79 #endif
81 #define PLAYBACK_VOICE
83 /* default point to start buffer refill */
84 #define AUDIO_DEFAULT_WATERMARK (1024*512)
85 /* amount of guess-space to allow for codecs that must hunt and peck
86 * for their correct seeek target, 32k seems a good size */
87 #define AUDIO_REBUFFER_GUESS_SIZE (1024*32)
89 /* Define LOGF_ENABLE to enable logf output in this file */
90 /*#define LOGF_ENABLE*/
91 #include "logf.h"
93 /* macros to enable logf for queues
94 logging on SYS_TIMEOUT can be disabled */
95 #ifdef SIMULATOR
96 /* Define this for logf output of all queuing except SYS_TIMEOUT */
97 #define PLAYBACK_LOGQUEUES
98 /* Define this to logf SYS_TIMEOUT messages */
99 /*#define PLAYBACK_LOGQUEUES_SYS_TIMEOUT*/
100 #endif
102 #ifdef PLAYBACK_LOGQUEUES
103 #define LOGFQUEUE logf
104 #else
105 #define LOGFQUEUE(...)
106 #endif
108 #ifdef PLAYBACK_LOGQUEUES_SYS_TIMEOUT
109 #define LOGFQUEUE_SYS_TIMEOUT logf
110 #else
111 #define LOGFQUEUE_SYS_TIMEOUT(...)
112 #endif
115 /* Define one constant that includes recording related functionality */
116 #if defined(HAVE_RECORDING) && !defined(SIMULATOR)
117 #define AUDIO_HAVE_RECORDING
118 #endif
120 enum {
121 Q_NULL = 0,
122 Q_AUDIO_PLAY = 1,
123 Q_AUDIO_STOP,
124 Q_AUDIO_PAUSE,
125 Q_AUDIO_SKIP,
126 Q_AUDIO_PRE_FF_REWIND,
127 Q_AUDIO_FF_REWIND,
128 Q_AUDIO_CHECK_NEW_TRACK,
129 Q_AUDIO_FLUSH,
130 Q_AUDIO_TRACK_CHANGED,
131 Q_AUDIO_DIR_SKIP,
132 Q_AUDIO_POSTINIT,
133 Q_AUDIO_FILL_BUFFER,
134 Q_AUDIO_FINISH_LOAD,
135 Q_CODEC_REQUEST_COMPLETE,
136 Q_CODEC_REQUEST_FAILED,
138 Q_CODEC_LOAD,
139 Q_CODEC_LOAD_DISK,
141 #ifdef AUDIO_HAVE_RECORDING
142 Q_ENCODER_LOAD_DISK,
143 Q_ENCODER_RECORD,
144 #endif
147 enum filling_state {
148 STATE_IDLE, /* audio is stopped: nothing to do */
149 STATE_FILLING, /* adding tracks to the buffer */
150 STATE_FULL, /* can't add any more tracks */
151 STATE_FINISHED, /* all remaining tracks have been added */
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 bool audio_is_initialized = false;
176 static bool audio_thread_ready SHAREDBSS_ATTR = false;
178 /* Variables are commented with the threads that use them: *
179 * A=audio, C=codec, V=voice. A suffix of - indicates that *
180 * the variable is read but not updated on that thread. */
181 /* TBD: Split out "audio" and "playback" (ie. calling) threads */
183 /* Main state control */
184 static volatile bool audio_codec_loaded SHAREDBSS_ATTR = false; /* Codec loaded? (C/A-) */
185 static volatile bool playing SHAREDBSS_ATTR = false; /* Is audio playing? (A) */
186 static volatile bool paused SHAREDBSS_ATTR = false; /* Is audio paused? (A/C-) */
188 /* Ring buffer where compressed audio and codecs are loaded */
189 static unsigned char *filebuf = NULL; /* Start of buffer (A/C-) */
190 static unsigned char *malloc_buf = NULL; /* Start of malloc buffer (A/C-) */
191 /* FIXME: make filebuflen static */
192 size_t filebuflen = 0; /* Size of buffer (A/C-) */
193 /* FIXME: make buf_ridx (C/A-) */
195 /* Possible arrangements of the buffer */
196 #define BUFFER_STATE_TRASHED -1 /* trashed; must be reset */
197 #define BUFFER_STATE_INITIALIZED 0 /* voice+audio OR audio-only */
198 #define BUFFER_STATE_VOICED_ONLY 1 /* voice-only */
199 static int buffer_state = BUFFER_STATE_TRASHED; /* Buffer state */
201 /* Used to keep the WPS up-to-date during track transtition */
202 static struct mp3entry prevtrack_id3;
204 /* Used to provide the codec with a pointer */
205 static struct mp3entry curtrack_id3;
207 /* Used to make next track info available while playing last track on buffer */
208 static struct mp3entry lasttrack_id3;
210 /* Track info structure about songs in the file buffer (A/C-) */
211 struct track_info {
212 int audio_hid; /* The ID for the track's buffer handle */
213 int id3_hid; /* The ID for the track's metadata handle */
214 int codec_hid; /* The ID for the track's codec handle */
215 #ifdef HAVE_ALBUMART
216 int aa_hid; /* The ID for the track's album art handle */
217 #endif
219 size_t filesize; /* File total length */
221 bool taginfo_ready; /* Is metadata read */
224 static struct track_info tracks[MAX_TRACK];
225 static volatile int track_ridx = 0; /* Track being decoded (A/C-) */
226 static int track_widx = 0; /* Track being buffered (A) */
228 #define CUR_TI (&tracks[track_ridx]) /* Playing track info pointer (A/C-) */
229 static struct track_info *prev_ti = NULL; /* Pointer to the previously played
230 track */
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 static enum filling_state filling;
245 /* Track change controls */
246 static bool automatic_skip = false; /* Who initiated in-progress skip? (C/A-) */
247 static bool dir_skip = false; /* Is a directory skip pending? (A) */
248 static bool new_playlist = false; /* Are we starting a new playlist? (A) */
249 static int wps_offset = 0; /* Pending track change offset, to keep WPS responsive (A) */
250 static bool skipped_during_pause = false; /* Do we need to clear the PCM buffer when playback resumes (A) */
252 static bool start_play_g = false; /* Used by audio_load_track to notify
253 audio_finish_load_track about start_play */
255 /* Set to true if the codec thread should send an audio stop request
256 * (typically because the end of the playlist has been reached).
258 static bool codec_requested_stop = false;
260 static size_t buffer_margin = 0; /* Buffer margin aka anti-skip buffer (A/C-) */
262 /* Multiple threads */
263 /* Set the watermark to trigger buffer fill (A/C) FIXME */
264 static void set_filebuf_watermark(int seconds, size_t max);
266 /* Audio thread */
267 static struct event_queue audio_queue SHAREDBSS_ATTR;
268 static struct queue_sender_list audio_queue_sender_list SHAREDBSS_ATTR;
269 static long audio_stack[(DEFAULT_STACK_SIZE + 0x1000)/sizeof(long)];
270 static const char audio_thread_name[] = "audio";
272 static void audio_thread(void);
273 static void audio_initiate_track_change(long direction);
274 static bool audio_have_tracks(void);
275 static void audio_reset_buffer(void);
277 /* Codec thread */
278 extern struct codec_api ci;
279 static struct event_queue codec_queue SHAREDBSS_ATTR;
280 static struct queue_sender_list codec_queue_sender_list;
281 static long codec_stack[(DEFAULT_STACK_SIZE + 0x2000)/sizeof(long)]
282 IBSS_ATTR;
283 static const char codec_thread_name[] = "codec";
284 struct thread_entry *codec_thread_p; /* For modifying thread priority later. */
286 /* PCM buffer messaging */
287 static struct event_queue pcmbuf_queue SHAREDBSS_ATTR;
289 /* Function to be called by pcm buffer callbacks.
290 * Permissible Context(s): Audio interrupt
292 static void pcmbuf_callback_queue_post(long id, intptr_t data)
294 /* No lock since we're already in audio interrupt context */
295 queue_post(&pcmbuf_queue, id, data);
298 /* Scan the pcmbuf queue and return true if a message pulled.
299 * Permissible Context(s): Thread
301 static bool pcmbuf_queue_scan(struct queue_event *ev)
303 if (!queue_empty(&pcmbuf_queue))
305 /* Transfer message to audio queue */
306 pcm_play_lock();
307 /* Pull message - never, ever any blocking call! */
308 queue_wait_w_tmo(&pcmbuf_queue, ev, 0);
309 pcm_play_unlock();
310 return true;
313 return false;
316 /* Clear the pcmbuf queue of messages
317 * Permissible Context(s): Thread
319 static void pcmbuf_queue_clear(void)
321 pcm_play_lock();
322 queue_clear(&pcmbuf_queue);
323 pcm_play_unlock();
326 /* --- Helper functions --- */
328 static struct mp3entry *bufgetid3(int handle_id)
330 if (handle_id < 0)
331 return NULL;
333 struct mp3entry *id3;
334 ssize_t ret = bufgetdata(handle_id, 0, (void *)&id3);
336 if (ret < 0 || ret != sizeof(struct mp3entry))
337 return NULL;
339 return id3;
342 static bool clear_track_info(struct track_info *track)
344 /* bufclose returns true if the handle is not found, or if it is closed
345 * successfully, so these checks are safe on non-existant handles */
346 if (!track)
347 return false;
349 if (track->codec_hid >= 0) {
350 if (bufclose(track->codec_hid))
351 track->codec_hid = -1;
352 else
353 return false;
356 if (track->id3_hid >= 0) {
357 if (bufclose(track->id3_hid))
358 track->id3_hid = -1;
359 else
360 return false;
363 if (track->audio_hid >= 0) {
364 if (bufclose(track->audio_hid))
365 track->audio_hid = -1;
366 else
367 return false;
370 #ifdef HAVE_ALBUMART
371 if (track->aa_hid >= 0) {
372 if (bufclose(track->aa_hid))
373 track->aa_hid = -1;
374 else
375 return false;
377 #endif
379 track->filesize = 0;
380 track->taginfo_ready = false;
382 return true;
385 /* --- External interfaces --- */
387 /* This sends a stop message and the audio thread will dump all it's
388 subsequenct messages */
389 void audio_hard_stop(void)
391 /* Stop playback */
392 LOGFQUEUE("audio >| audio Q_AUDIO_STOP: 1");
393 queue_send(&audio_queue, Q_AUDIO_STOP, 1);
394 #ifdef PLAYBACK_VOICE
395 voice_stop();
396 #endif
399 bool audio_restore_playback(int type)
401 switch (type)
403 case AUDIO_WANT_PLAYBACK:
404 if (buffer_state != BUFFER_STATE_INITIALIZED)
405 audio_reset_buffer();
406 return true;
407 case AUDIO_WANT_VOICE:
408 if (buffer_state == BUFFER_STATE_TRASHED)
409 audio_reset_buffer();
410 return true;
411 default:
412 return false;
416 unsigned char *audio_get_buffer(bool talk_buf, size_t *buffer_size)
418 unsigned char *buf, *end;
420 if (audio_is_initialized)
422 audio_hard_stop();
424 /* else buffer_state will be BUFFER_STATE_TRASHED at this point */
426 if (buffer_size == NULL)
428 /* Special case for talk_init to use since it already knows it's
429 trashed */
430 buffer_state = BUFFER_STATE_TRASHED;
431 return NULL;
434 if (talk_buf || buffer_state == BUFFER_STATE_TRASHED
435 || !talk_voice_required())
437 logf("get buffer: talk, audio");
438 /* Ok to use everything from audiobuf to audiobufend - voice is loaded,
439 the talk buffer is not needed because voice isn't being used, or
440 could be BUFFER_STATE_TRASHED already. If state is
441 BUFFER_STATE_VOICED_ONLY, no problem as long as memory isn't written
442 without the caller knowing what's going on. Changing certain settings
443 may move it to a worse condition but the memory in use by something
444 else will remain undisturbed.
446 if (buffer_state != BUFFER_STATE_TRASHED)
448 talk_buffer_steal();
449 buffer_state = BUFFER_STATE_TRASHED;
452 buf = audiobuf;
453 end = audiobufend;
455 else
457 /* Safe to just return this if already BUFFER_STATE_VOICED_ONLY or
458 still BUFFER_STATE_INITIALIZED */
459 /* Skip talk buffer and move pcm buffer to end to maximize available
460 contiguous memory - no audio running means voice will not need the
461 swap space */
462 logf("get buffer: audio");
463 buf = audiobuf + talk_get_bufsize();
464 end = audiobufend - pcmbuf_init(audiobufend);
465 buffer_state = BUFFER_STATE_VOICED_ONLY;
468 *buffer_size = end - buf;
470 return buf;
473 #ifdef HAVE_RECORDING
474 unsigned char *audio_get_recording_buffer(size_t *buffer_size)
476 /* Stop audio, voice and obtain all available buffer space */
477 audio_hard_stop();
478 talk_buffer_steal();
480 unsigned char *end = audiobufend;
481 buffer_state = BUFFER_STATE_TRASHED;
482 *buffer_size = end - audiobuf;
484 return (unsigned char *)audiobuf;
487 bool audio_load_encoder(int afmt)
489 #ifndef SIMULATOR
490 const char *enc_fn = get_codec_filename(afmt | CODEC_TYPE_ENCODER);
491 if (!enc_fn)
492 return false;
494 audio_remove_encoder();
495 ci.enc_codec_loaded = 0; /* clear any previous error condition */
497 LOGFQUEUE("codec > Q_ENCODER_LOAD_DISK");
498 queue_post(&codec_queue, Q_ENCODER_LOAD_DISK, (intptr_t)enc_fn);
500 while (ci.enc_codec_loaded == 0)
501 yield();
503 logf("codec loaded: %d", ci.enc_codec_loaded);
505 return ci.enc_codec_loaded > 0;
506 #else
507 (void)afmt;
508 return true;
509 #endif
510 } /* audio_load_encoder */
512 void audio_remove_encoder(void)
514 #ifndef SIMULATOR
515 /* force encoder codec unload (if currently loaded) */
516 if (ci.enc_codec_loaded <= 0)
517 return;
519 ci.stop_encoder = true;
520 while (ci.enc_codec_loaded > 0)
521 yield();
522 #endif
523 } /* audio_remove_encoder */
525 #endif /* HAVE_RECORDING */
527 #ifdef HAVE_ALBUMART
528 int audio_current_aa_hid(void)
530 int cur_idx;
531 int offset = ci.new_track + wps_offset;
533 cur_idx = track_ridx + offset;
534 cur_idx &= MAX_TRACK_MASK;
536 return tracks[cur_idx].aa_hid;
538 #endif
540 struct mp3entry* audio_current_track(void)
542 const char *filename;
543 const char *p;
544 static struct mp3entry temp_id3;
545 int cur_idx;
546 int offset = ci.new_track + wps_offset;
548 cur_idx = (track_ridx + offset) & MAX_TRACK_MASK;
550 if (cur_idx == track_ridx && *curtrack_id3.path)
552 /* The usual case */
553 return &curtrack_id3;
555 else if (offset == -1 && *prevtrack_id3.path)
557 /* We're in a track transition. The codec has moved on to the nex track,
558 but the audio being played is still the same (now previous) track.
559 prevtrack_id3.elapsed is being updated in an ISR by
560 codec_pcmbuf_position_callback */
561 return &prevtrack_id3;
563 else if (tracks[cur_idx].id3_hid >= 0)
565 /* Get the ID3 metadata from the main buffer */
566 return bufgetid3(tracks[cur_idx].id3_hid);
569 /* We didn't find the ID3 metadata, so we fill temp_id3 with the little info
570 we have and return that. */
572 memset(&temp_id3, 0, sizeof(struct mp3entry));
574 filename = playlist_peek(0);
575 if (!filename)
576 filename = "No file!";
578 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
579 if (tagcache_fill_tags(&temp_id3, filename))
580 return &temp_id3;
581 #endif
583 p = strrchr(filename, '/');
584 if (!p)
585 p = filename;
586 else
587 p++;
589 strncpy(temp_id3.path, p, sizeof(temp_id3.path)-1);
590 temp_id3.title = &temp_id3.path[0];
592 return &temp_id3;
595 struct mp3entry* audio_next_track(void)
597 int next_idx;
598 int offset = ci.new_track + wps_offset;
600 if (!audio_have_tracks())
601 return NULL;
603 if (wps_offset == -1 && *prevtrack_id3.path)
605 /* We're in a track transition. The next track for the WPS is the one
606 currently being decoded. */
607 return &curtrack_id3;
610 next_idx = (track_ridx + offset + 1) & MAX_TRACK_MASK;
612 if (tracks[next_idx].id3_hid >= 0)
613 return bufgetid3(tracks[next_idx].id3_hid);
615 if (next_idx == track_widx)
617 /* The next track hasn't been buffered yet, so we return the static
618 version of its metadata. */
619 return &lasttrack_id3;
622 return NULL;
625 bool audio_has_changed_track(void)
627 if (track_changed)
629 track_changed = false;
630 return true;
633 return false;
636 void audio_play(long offset)
638 logf("audio_play");
640 #ifdef PLAYBACK_VOICE
641 /* Truncate any existing voice output so we don't have spelling
642 * etc. over the first part of the played track */
643 talk_force_shutup();
644 #endif
646 /* Start playback */
647 LOGFQUEUE("audio >| audio Q_AUDIO_PLAY: %ld", offset);
648 /* Don't return until playback has actually started */
649 queue_send(&audio_queue, Q_AUDIO_PLAY, offset);
652 void audio_stop(void)
654 /* Stop playback */
655 LOGFQUEUE("audio >| audio Q_AUDIO_STOP");
656 /* Don't return until playback has actually stopped */
657 queue_send(&audio_queue, Q_AUDIO_STOP, 0);
660 void audio_pause(void)
662 LOGFQUEUE("audio >| audio Q_AUDIO_PAUSE");
663 /* Don't return until playback has actually paused */
664 queue_send(&audio_queue, Q_AUDIO_PAUSE, true);
667 void audio_resume(void)
669 LOGFQUEUE("audio >| audio Q_AUDIO_PAUSE resume");
670 /* Don't return until playback has actually resumed */
671 queue_send(&audio_queue, Q_AUDIO_PAUSE, false);
674 static void audio_skip(int direction)
676 if (playlist_check(ci.new_track + wps_offset + direction))
678 if (global_settings.beep)
679 pcmbuf_beep(5000, 100, 2500*global_settings.beep);
681 LOGFQUEUE("audio > audio Q_AUDIO_SKIP %d", direction);
682 queue_post(&audio_queue, Q_AUDIO_SKIP, direction);
683 /* Update wps while our message travels inside deep playback queues. */
684 wps_offset += direction;
685 track_changed = true;
687 else
689 /* No more tracks. */
690 if (global_settings.beep)
691 pcmbuf_beep(1000, 100, 1000*global_settings.beep);
695 void audio_next(void)
697 audio_skip(1);
700 void audio_prev(void)
702 audio_skip(-1);
705 void audio_next_dir(void)
707 LOGFQUEUE("audio > audio Q_AUDIO_DIR_SKIP 1");
708 queue_post(&audio_queue, Q_AUDIO_DIR_SKIP, 1);
711 void audio_prev_dir(void)
713 LOGFQUEUE("audio > audio Q_AUDIO_DIR_SKIP -1");
714 queue_post(&audio_queue, Q_AUDIO_DIR_SKIP, -1);
717 void audio_pre_ff_rewind(void)
719 LOGFQUEUE("audio > audio Q_AUDIO_PRE_FF_REWIND");
720 queue_post(&audio_queue, Q_AUDIO_PRE_FF_REWIND, 0);
723 void audio_ff_rewind(long newpos)
725 LOGFQUEUE("audio > audio Q_AUDIO_FF_REWIND");
726 queue_post(&audio_queue, Q_AUDIO_FF_REWIND, newpos);
729 void audio_flush_and_reload_tracks(void)
731 LOGFQUEUE("audio > audio Q_AUDIO_FLUSH");
732 queue_post(&audio_queue, Q_AUDIO_FLUSH, 0);
735 void audio_error_clear(void)
737 #ifdef AUDIO_HAVE_RECORDING
738 pcm_rec_error_clear();
739 #endif
742 int audio_status(void)
744 int ret = 0;
746 if (playing)
747 ret |= AUDIO_STATUS_PLAY;
749 if (paused)
750 ret |= AUDIO_STATUS_PAUSE;
752 #ifdef HAVE_RECORDING
753 /* Do this here for constitency with mpeg.c version */
754 ret |= pcm_rec_status();
755 #endif
757 return ret;
760 int audio_get_file_pos(void)
762 return 0;
765 #ifndef HAVE_FLASH_STORAGE
766 void audio_set_buffer_margin(int setting)
768 static const int lookup[] = {5, 15, 30, 60, 120, 180, 300, 600};
769 buffer_margin = lookup[setting];
770 logf("buffer margin: %ld", (long)buffer_margin);
771 set_filebuf_watermark(buffer_margin, 0);
773 #endif
775 /* Take necessary steps to enable or disable the crossfade setting */
776 void audio_set_crossfade(int enable)
778 size_t offset;
779 bool was_playing;
780 size_t size;
782 /* Tell it the next setting to use */
783 pcmbuf_crossfade_enable(enable);
785 /* Return if size hasn't changed or this is too early to determine
786 which in the second case there's no way we could be playing
787 anything at all */
788 if (pcmbuf_is_same_size())
790 /* This function is a copout and just syncs some variables -
791 to be removed at a later date */
792 pcmbuf_crossfade_enable_finished();
793 return;
796 offset = 0;
797 was_playing = playing;
799 /* Playback has to be stopped before changing the buffer size */
800 if (was_playing)
802 /* Store the track resume position */
803 offset = curtrack_id3.offset;
804 gui_syncsplash(0, str(LANG_RESTARTING_PLAYBACK));
807 /* Blast it - audio buffer will have to be setup again next time
808 something plays */
809 audio_get_buffer(true, &size);
811 /* Restart playback if audio was running previously */
812 if (was_playing)
813 audio_play(offset);
816 /* --- Routines called from multiple threads --- */
818 static void set_filebuf_watermark(int seconds, size_t max)
820 size_t bytes;
822 if (!filebuf)
823 return; /* Audio buffers not yet set up */
825 bytes = seconds?MAX(curtrack_id3.bitrate * seconds * (1000/8), max):max;
826 bytes = MIN(bytes, filebuflen / 2);
827 buf_set_watermark(bytes);
830 const char *get_codec_filename(int cod_spec)
832 const char *fname;
834 #ifdef HAVE_RECORDING
835 /* Can choose decoder or encoder if one available */
836 int type = cod_spec & CODEC_TYPE_MASK;
837 int afmt = cod_spec & CODEC_AFMT_MASK;
839 if ((unsigned)afmt >= AFMT_NUM_CODECS)
840 type = AFMT_UNKNOWN | (type & CODEC_TYPE_MASK);
842 fname = (type == CODEC_TYPE_ENCODER) ?
843 audio_formats[afmt].codec_enc_root_fn :
844 audio_formats[afmt].codec_root_fn;
846 logf("%s: %d - %s",
847 (type == CODEC_TYPE_ENCODER) ? "Encoder" : "Decoder",
848 afmt, fname ? fname : "<unknown>");
849 #else /* !HAVE_RECORDING */
850 /* Always decoder */
851 if ((unsigned)cod_spec >= AFMT_NUM_CODECS)
852 cod_spec = AFMT_UNKNOWN;
853 fname = audio_formats[cod_spec].codec_root_fn;
854 logf("Codec: %d - %s", cod_spec, fname ? fname : "<unknown>");
855 #endif /* HAVE_RECORDING */
857 return fname;
858 } /* get_codec_filename */
860 /* --- Codec thread --- */
861 static bool codec_pcmbuf_insert_callback(
862 const void *ch1, const void *ch2, int count)
864 const char *src[2] = { ch1, ch2 };
866 while (count > 0)
868 int out_count = dsp_output_count(ci.dsp, count);
869 int inp_count;
870 char *dest;
872 /* Prevent audio from a previous track from playing */
873 if (ci.new_track || ci.stop_codec)
874 return true;
876 while ((dest = pcmbuf_request_buffer(&out_count)) == NULL)
878 cancel_cpu_boost();
879 sleep(1);
880 if (ci.seek_time || ci.new_track || ci.stop_codec)
881 return true;
884 /* Get the real input_size for output_size bytes, guarding
885 * against resampling buffer overflows. */
886 inp_count = dsp_input_count(ci.dsp, out_count);
888 if (inp_count <= 0)
889 return true;
891 /* Input size has grown, no error, just don't write more than length */
892 if (inp_count > count)
893 inp_count = count;
895 out_count = dsp_process(ci.dsp, dest, src, inp_count);
897 if (out_count <= 0)
898 return true;
900 pcmbuf_write_complete(out_count);
902 count -= inp_count;
905 return true;
906 } /* codec_pcmbuf_insert_callback */
908 static void* codec_get_memory_callback(size_t *size)
910 *size = MALLOC_BUFSIZE;
911 return malloc_buf;
914 /* Between the codec and PCM track change, we need to keep updating the
915 "elapsed" value of the previous (to the codec, but current to the
916 user/PCM/WPS) track, so that the progressbar reaches the end.
917 During that transition, the WPS will display prevtrack_id3. */
918 static void codec_pcmbuf_position_callback(size_t size) ICODE_ATTR;
919 static void codec_pcmbuf_position_callback(size_t size)
921 /* This is called from an ISR, so be quick */
922 unsigned int time = size * 1000 / 4 / NATIVE_FREQUENCY +
923 prevtrack_id3.elapsed;
925 if (time >= prevtrack_id3.length)
927 pcmbuf_set_position_callback(NULL);
928 prevtrack_id3.elapsed = prevtrack_id3.length;
930 else
931 prevtrack_id3.elapsed = time;
934 static void codec_set_elapsed_callback(unsigned int value)
936 unsigned int latency;
937 if (ci.seek_time)
938 return;
940 #ifdef AB_REPEAT_ENABLE
941 ab_position_report(value);
942 #endif
944 latency = pcmbuf_get_latency();
945 if (value < latency)
946 curtrack_id3.elapsed = 0;
947 else if (value - latency > curtrack_id3.elapsed ||
948 value - latency < curtrack_id3.elapsed - 2)
950 curtrack_id3.elapsed = value - latency;
954 static void codec_set_offset_callback(size_t value)
956 unsigned int latency;
958 if (ci.seek_time)
959 return;
961 latency = pcmbuf_get_latency() * curtrack_id3.bitrate / 8;
962 if (value < latency)
963 curtrack_id3.offset = 0;
964 else
965 curtrack_id3.offset = value - latency;
968 static void codec_advance_buffer_counters(size_t amount)
970 bufadvance(CUR_TI->audio_hid, amount);
971 ci.curpos += amount;
974 /* copy up-to size bytes into ptr and return the actual size copied */
975 static size_t codec_filebuf_callback(void *ptr, size_t size)
977 ssize_t copy_n;
979 if (ci.stop_codec || !playing)
980 return 0;
982 copy_n = bufread(CUR_TI->audio_hid, size, ptr);
984 /* Nothing requested OR nothing left */
985 if (copy_n == 0)
986 return 0;
988 /* Update read and other position pointers */
989 codec_advance_buffer_counters(copy_n);
991 /* Return the actual amount of data copied to the buffer */
992 return copy_n;
993 } /* codec_filebuf_callback */
995 static void* codec_request_buffer_callback(size_t *realsize, size_t reqsize)
997 size_t copy_n = reqsize;
998 ssize_t ret;
999 void *ptr;
1001 if (!playing)
1003 *realsize = 0;
1004 return NULL;
1007 ret = bufgetdata(CUR_TI->audio_hid, reqsize, &ptr);
1008 if (ret >= 0)
1009 copy_n = MIN((size_t)ret, reqsize);
1011 if (copy_n == 0)
1013 *realsize = 0;
1014 return NULL;
1017 *realsize = copy_n;
1019 return ptr;
1020 } /* codec_request_buffer_callback */
1022 static int get_codec_base_type(int type)
1024 switch (type) {
1025 case AFMT_MPA_L1:
1026 case AFMT_MPA_L2:
1027 case AFMT_MPA_L3:
1028 return AFMT_MPA_L3;
1031 return type;
1034 static void codec_advance_buffer_callback(size_t amount)
1036 codec_advance_buffer_counters(amount);
1037 codec_set_offset_callback(ci.curpos);
1040 static void codec_advance_buffer_loc_callback(void *ptr)
1042 size_t amount = buf_get_offset(CUR_TI->audio_hid, ptr);
1043 codec_advance_buffer_callback(amount);
1046 static void codec_seek_complete_callback(void)
1048 logf("seek_complete");
1049 if (pcm_is_paused())
1051 /* If this is not a seamless seek, clear the buffer */
1052 pcmbuf_play_stop();
1053 dsp_configure(ci.dsp, DSP_FLUSH, 0);
1055 /* If playback was not 'deliberately' paused, unpause now */
1056 if (!paused)
1057 pcmbuf_pause(false);
1059 ci.seek_time = 0;
1062 static bool codec_seek_buffer_callback(size_t newpos)
1064 logf("codec_seek_buffer_callback");
1066 int ret = bufseek(CUR_TI->audio_hid, newpos);
1067 if (ret == 0) {
1068 ci.curpos = newpos;
1069 return true;
1071 else {
1072 return false;
1076 static void codec_configure_callback(int setting, intptr_t value)
1078 switch (setting) {
1079 case CODEC_SET_FILEBUF_WATERMARK:
1080 set_filebuf_watermark(buffer_margin, value);
1081 break;
1083 default:
1084 if (!dsp_configure(ci.dsp, setting, value))
1085 { logf("Illegal key:%d", setting); }
1089 static void codec_track_changed(void)
1091 LOGFQUEUE("codec > audio Q_AUDIO_TRACK_CHANGED");
1092 queue_post(&audio_queue, Q_AUDIO_TRACK_CHANGED, 0);
1095 static void codec_pcmbuf_track_changed_callback(void)
1097 pcmbuf_set_position_callback(NULL);
1098 pcmbuf_callback_queue_post(Q_AUDIO_TRACK_CHANGED, 0);
1101 static void codec_discard_codec_callback(void)
1103 if (CUR_TI->codec_hid >= 0)
1105 bufclose(CUR_TI->codec_hid);
1106 CUR_TI->codec_hid = -1;
1110 static inline void codec_gapless_track_change(void)
1112 /* callback keeps the progress bar moving while the pcmbuf empties */
1113 pcmbuf_set_position_callback(codec_pcmbuf_position_callback);
1114 /* set the pcmbuf callback for when the track really changes */
1115 pcmbuf_set_event_handler(codec_pcmbuf_track_changed_callback);
1118 static inline void codec_crossfade_track_change(void)
1120 /* Initiate automatic crossfade mode */
1121 pcmbuf_crossfade_init(false);
1122 /* Notify the wps that the track change starts now */
1123 codec_track_changed();
1126 static void codec_track_skip_done(bool was_manual)
1128 /* Manual track change (always crossfade or flush audio). */
1129 if (was_manual)
1131 pcmbuf_crossfade_init(true);
1132 LOGFQUEUE("codec > audio Q_AUDIO_TRACK_CHANGED");
1133 queue_post(&audio_queue, Q_AUDIO_TRACK_CHANGED, 0);
1135 /* Automatic track change w/crossfade, if not in "Track Skip Only" mode. */
1136 else if (pcmbuf_is_crossfade_enabled() && !pcmbuf_is_crossfade_active()
1137 && global_settings.crossfade != CROSSFADE_ENABLE_TRACKSKIP)
1139 if (global_settings.crossfade == CROSSFADE_ENABLE_SHUFFLE_AND_TRACKSKIP)
1141 if (global_settings.playlist_shuffle)
1142 /* shuffle mode is on, so crossfade: */
1143 codec_crossfade_track_change();
1144 else
1145 /* shuffle mode is off, so do a gapless track change */
1146 codec_gapless_track_change();
1148 else
1149 /* normal crossfade: */
1150 codec_crossfade_track_change();
1152 else
1153 /* normal gapless playback. */
1154 codec_gapless_track_change();
1157 static bool codec_load_next_track(void)
1159 intptr_t result = Q_CODEC_REQUEST_FAILED;
1161 prev_track_elapsed = curtrack_id3.elapsed;
1163 #ifdef AB_REPEAT_ENABLE
1164 ab_end_of_track_report();
1165 #endif
1167 logf("Request new track");
1169 if (ci.new_track == 0)
1171 ci.new_track++;
1172 automatic_skip = true;
1175 if (!ci.stop_codec)
1177 trigger_cpu_boost();
1178 LOGFQUEUE("codec >| audio Q_AUDIO_CHECK_NEW_TRACK");
1179 result = queue_send(&audio_queue, Q_AUDIO_CHECK_NEW_TRACK, 0);
1182 switch (result)
1184 case Q_CODEC_REQUEST_COMPLETE:
1185 LOGFQUEUE("codec |< Q_CODEC_REQUEST_COMPLETE");
1186 codec_track_skip_done(!automatic_skip);
1187 return true;
1189 case Q_CODEC_REQUEST_FAILED:
1190 LOGFQUEUE("codec |< Q_CODEC_REQUEST_FAILED");
1191 ci.new_track = 0;
1192 ci.stop_codec = true;
1193 codec_requested_stop = true;
1194 return false;
1196 default:
1197 LOGFQUEUE("codec |< default");
1198 ci.stop_codec = true;
1199 codec_requested_stop = true;
1200 return false;
1204 static bool codec_request_next_track_callback(void)
1206 int prev_codectype;
1208 if (ci.stop_codec || !playing)
1209 return false;
1211 prev_codectype = get_codec_base_type(curtrack_id3.codectype);
1213 if (!codec_load_next_track())
1214 return false;
1216 /* Seek to the beginning of the new track because if the struct
1217 mp3entry was buffered, "elapsed" might not be zero (if the track has
1218 been played already but not unbuffered) */
1219 codec_seek_buffer_callback(curtrack_id3.first_frame_offset);
1221 /* Check if the next codec is the same file. */
1222 if (prev_codectype == get_codec_base_type(curtrack_id3.codectype))
1224 logf("New track loaded");
1225 codec_discard_codec_callback();
1226 return true;
1228 else
1230 logf("New codec:%d/%d", curtrack_id3.codectype, prev_codectype);
1231 return false;
1235 static void codec_thread(void)
1237 struct queue_event ev;
1238 int status;
1240 while (1) {
1241 status = 0;
1243 if (!pcmbuf_is_crossfade_active()) {
1244 cancel_cpu_boost();
1247 queue_wait(&codec_queue, &ev);
1248 codec_requested_stop = false;
1250 switch (ev.id) {
1251 case Q_CODEC_LOAD_DISK:
1252 LOGFQUEUE("codec < Q_CODEC_LOAD_DISK");
1253 queue_reply(&codec_queue, 1);
1254 audio_codec_loaded = true;
1255 ci.stop_codec = false;
1256 status = codec_load_file((const char *)ev.data, &ci);
1257 break;
1259 case Q_CODEC_LOAD:
1260 LOGFQUEUE("codec < Q_CODEC_LOAD");
1261 if (CUR_TI->codec_hid < 0) {
1262 logf("Codec slot is empty!");
1263 /* Wait for the pcm buffer to go empty */
1264 while (pcm_is_playing())
1265 yield();
1266 /* This must be set to prevent an infinite loop */
1267 ci.stop_codec = true;
1268 LOGFQUEUE("codec > codec Q_AUDIO_PLAY");
1269 queue_post(&codec_queue, Q_AUDIO_PLAY, 0);
1270 break;
1273 audio_codec_loaded = true;
1274 ci.stop_codec = false;
1275 status = codec_load_buf(CUR_TI->codec_hid, &ci);
1276 break;
1278 #ifdef AUDIO_HAVE_RECORDING
1279 case Q_ENCODER_LOAD_DISK:
1280 LOGFQUEUE("codec < Q_ENCODER_LOAD_DISK");
1281 audio_codec_loaded = false; /* Not audio codec! */
1282 logf("loading encoder");
1283 ci.stop_encoder = false;
1284 status = codec_load_file((const char *)ev.data, &ci);
1285 logf("encoder stopped");
1286 break;
1287 #endif /* AUDIO_HAVE_RECORDING */
1289 default:
1290 LOGFQUEUE("codec < default");
1293 if (audio_codec_loaded)
1295 if (ci.stop_codec)
1297 status = CODEC_OK;
1298 if (!playing)
1299 pcmbuf_play_stop();
1302 audio_codec_loaded = false;
1305 switch (ev.id) {
1306 case Q_CODEC_LOAD_DISK:
1307 case Q_CODEC_LOAD:
1308 LOGFQUEUE("codec < Q_CODEC_LOAD");
1309 if (playing)
1311 if (ci.new_track || status != CODEC_OK)
1313 if (!ci.new_track)
1315 logf("Codec failure");
1316 gui_syncsplash(HZ*2, "Codec failure");
1319 if (!codec_load_next_track())
1321 LOGFQUEUE("codec > audio Q_AUDIO_STOP");
1322 /* End of playlist */
1323 queue_post(&audio_queue, Q_AUDIO_STOP, 0);
1324 break;
1327 else
1329 logf("Codec finished");
1330 if (ci.stop_codec)
1332 /* Wait for the audio to stop playing before
1333 * triggering the WPS exit */
1334 while(pcm_is_playing())
1336 curtrack_id3.elapsed =
1337 curtrack_id3.length - pcmbuf_get_latency();
1338 sleep(1);
1341 if (codec_requested_stop)
1343 LOGFQUEUE("codec > audio Q_AUDIO_STOP");
1344 queue_post(&audio_queue, Q_AUDIO_STOP, 0);
1346 break;
1350 if (CUR_TI->codec_hid >= 0)
1352 LOGFQUEUE("codec > codec Q_CODEC_LOAD");
1353 queue_post(&codec_queue, Q_CODEC_LOAD, 0);
1355 else
1357 const char *codec_fn =
1358 get_codec_filename(curtrack_id3.codectype);
1359 if (codec_fn)
1361 LOGFQUEUE("codec > codec Q_CODEC_LOAD_DISK");
1362 queue_post(&codec_queue, Q_CODEC_LOAD_DISK,
1363 (intptr_t)codec_fn);
1367 break;
1369 #ifdef AUDIO_HAVE_RECORDING
1370 case Q_ENCODER_LOAD_DISK:
1371 LOGFQUEUE("codec < Q_ENCODER_LOAD_DISK");
1373 if (status == CODEC_OK)
1374 break;
1376 logf("Encoder failure");
1377 gui_syncsplash(HZ*2, "Encoder failure");
1379 if (ci.enc_codec_loaded < 0)
1380 break;
1382 logf("Encoder failed to load");
1383 ci.enc_codec_loaded = -1;
1384 break;
1385 #endif /* AUDIO_HAVE_RECORDING */
1387 default:
1388 LOGFQUEUE("codec < default");
1390 } /* end switch */
1395 /* --- Buffering callbacks --- */
1397 static void buffering_low_buffer_callback(void *data)
1399 (void)data;
1400 logf("low buffer callback");
1402 if (filling == STATE_FULL) {
1403 /* force a refill */
1404 LOGFQUEUE("buffering > audio Q_AUDIO_FILL_BUFFER");
1405 queue_post(&audio_queue, Q_AUDIO_FILL_BUFFER, 0);
1409 static void buffering_handle_rebuffer_callback(void *data)
1411 (void)data;
1412 LOGFQUEUE("audio >| audio Q_AUDIO_FLUSH");
1413 queue_post(&audio_queue, Q_AUDIO_FLUSH, 0);
1416 static void buffering_handle_finished_callback(int *data)
1418 logf("handle %d finished buffering", *data);
1420 if (*data == tracks[track_widx].id3_hid)
1422 /* The metadata handle for the last loaded track has been buffered.
1423 We can ask the audio thread to load the rest of the track's data. */
1424 LOGFQUEUE("audio >| audio Q_AUDIO_FINISH_LOAD");
1425 queue_post(&audio_queue, Q_AUDIO_FINISH_LOAD, 0);
1427 else
1429 /* This is most likely an audio handle, so we strip the useless
1430 trailing tags that are left. */
1431 strip_tags(*data);
1436 /* --- Audio thread --- */
1438 static bool audio_have_tracks(void)
1440 return (audio_track_count() != 0);
1443 static int audio_free_track_count(void)
1445 /* Used tracks + free tracks adds up to MAX_TRACK - 1 */
1446 return MAX_TRACK - 1 - audio_track_count();
1449 int audio_track_count(void)
1451 /* Calculate difference from track_ridx to track_widx
1452 * taking into account a possible wrap-around. */
1453 return (MAX_TRACK + track_widx - track_ridx) & MAX_TRACK_MASK;
1456 long audio_filebufused(void)
1458 return (long) buf_used();
1461 /* Update track info after successful a codec track change */
1462 static void audio_update_trackinfo(void)
1464 /* Load the curent track's metadata into curtrack_id3 */
1465 if (CUR_TI->id3_hid >= 0)
1466 copy_mp3entry(&curtrack_id3, bufgetid3(CUR_TI->id3_hid));
1468 /* Reset current position */
1469 curtrack_id3.elapsed = 0;
1470 curtrack_id3.offset = 0;
1472 /* Update the codec API */
1473 ci.filesize = CUR_TI->filesize;
1474 ci.id3 = &curtrack_id3;
1475 ci.curpos = 0;
1476 ci.taginfo_ready = &CUR_TI->taginfo_ready;
1479 /* Clear tracks between write and read, non inclusive */
1480 static void audio_clear_track_entries(void)
1482 int cur_idx = track_widx;
1484 logf("Clearing tracks:%d/%d", track_ridx, track_widx);
1486 /* Loop over all tracks from write-to-read */
1487 while (1)
1489 cur_idx = (cur_idx + 1) & MAX_TRACK_MASK;
1491 if (cur_idx == track_ridx)
1492 break;
1494 clear_track_info(&tracks[cur_idx]);
1498 /* Clear all tracks */
1499 static bool audio_release_tracks(void)
1501 int i, cur_idx;
1503 logf("releasing all tracks");
1505 for(i = 0; i < MAX_TRACK; i++)
1507 cur_idx = (track_ridx + i) & MAX_TRACK_MASK;
1508 if (!clear_track_info(&tracks[cur_idx]))
1509 return false;
1512 return true;
1515 static bool audio_loadcodec(bool start_play)
1517 int prev_track;
1518 char codec_path[MAX_PATH]; /* Full path to codec */
1520 if (tracks[track_widx].id3_hid < 0) {
1521 return false;
1524 const char * codec_fn =
1525 get_codec_filename(bufgetid3(tracks[track_widx].id3_hid)->codectype);
1526 if (codec_fn == NULL)
1527 return false;
1529 tracks[track_widx].codec_hid = -1;
1531 if (start_play)
1533 /* Load the codec directly from disk and save some memory. */
1534 track_ridx = track_widx;
1535 ci.filesize = CUR_TI->filesize;
1536 ci.id3 = &curtrack_id3;
1537 ci.taginfo_ready = &CUR_TI->taginfo_ready;
1538 ci.curpos = 0;
1539 LOGFQUEUE("codec > codec Q_CODEC_LOAD_DISK");
1540 queue_post(&codec_queue, Q_CODEC_LOAD_DISK, (intptr_t)codec_fn);
1541 return true;
1543 else
1545 /* If we already have another track than this one buffered */
1546 if (track_widx != track_ridx)
1548 prev_track = (track_widx - 1) & MAX_TRACK_MASK;
1550 /* If the previous codec is the same as this one, there is no need
1551 * to put another copy of it on the file buffer */
1552 if (get_codec_base_type(
1553 bufgetid3(tracks[track_widx].id3_hid)->codectype) ==
1554 get_codec_base_type(
1555 bufgetid3(tracks[prev_track].id3_hid)->codectype)
1556 && audio_codec_loaded)
1558 logf("Reusing prev. codec");
1559 return true;
1564 codec_get_full_path(codec_path, codec_fn);
1566 tracks[track_widx].codec_hid = bufopen(codec_path, 0, TYPE_CODEC);
1567 if (tracks[track_widx].codec_hid < 0)
1568 return false;
1570 logf("Loaded codec");
1572 return true;
1575 /* Load metadata for the next track (with bufopen). The rest of the track
1576 loading will be handled by audio_finish_load_track once the metadata has been
1577 actually loaded by the buffering thread. */
1578 static bool audio_load_track(size_t offset, bool start_play)
1580 const char *trackname;
1581 int fd = -1;
1583 start_play_g = start_play; /* will be read by audio_finish_load_track */
1585 /* Stop buffer filling if there is no free track entries.
1586 Don't fill up the last track entry (we wan't to store next track
1587 metadata there). */
1588 if (!audio_free_track_count())
1590 logf("No free tracks");
1591 return false;
1594 last_peek_offset++;
1595 tracks[track_widx].taginfo_ready = false;
1597 logf("Buffering track:%d/%d", track_widx, track_ridx);
1598 /* Get track name from current playlist read position. */
1599 while ((trackname = playlist_peek(last_peek_offset)) != NULL)
1601 /* Handle broken playlists. */
1602 fd = open(trackname, O_RDONLY);
1603 if (fd < 0)
1605 logf("Open failed");
1606 /* Skip invalid entry from playlist. */
1607 playlist_skip_entry(NULL, last_peek_offset);
1609 else
1610 break;
1613 if (!trackname)
1615 logf("End-of-playlist");
1616 memset(&lasttrack_id3, 0, sizeof(struct mp3entry));
1617 filling = STATE_FINISHED;
1618 return false;
1621 tracks[track_widx].filesize = filesize(fd);
1623 if (offset > tracks[track_widx].filesize)
1624 offset = 0;
1626 /* Set default values */
1627 if (start_play)
1629 buf_set_watermark(AUDIO_DEFAULT_WATERMARK);
1630 dsp_configure(ci.dsp, DSP_RESET, 0);
1631 track_changed = true;
1632 playlist_update_resume_info(audio_current_track());
1635 /* Get track metadata if we don't already have it. */
1636 if (tracks[track_widx].id3_hid < 0)
1638 tracks[track_widx].id3_hid = bufopen(trackname, 0, TYPE_ID3);
1640 if (tracks[track_widx].id3_hid < 0)
1642 /* Buffer is full. */
1643 get_metadata(&lasttrack_id3, fd, trackname);
1644 last_peek_offset--;
1645 close(fd);
1646 logf("buffer is full for now");
1647 filling = STATE_FULL;
1648 return false;
1651 close(fd);
1653 if (track_widx == track_ridx)
1655 buf_request_buffer_handle(tracks[track_widx].id3_hid);
1656 copy_mp3entry(&curtrack_id3, bufgetid3(tracks[track_widx].id3_hid));
1657 curtrack_id3.offset = offset;
1660 if (start_play)
1662 track_changed = true;
1663 playlist_update_resume_info(audio_current_track());
1667 return true;
1670 /* Second part of the track loading: We now have the metadata available, so we
1671 can load the codec, the album art and finally the audio data.
1672 This is called on the audio thread after the buffering thread calls the
1673 buffering_handle_finished_callback callback. */
1674 static void audio_finish_load_track(void)
1676 char msgbuf[80];
1677 size_t file_offset = 0;
1678 size_t offset = 0;
1679 bool start_play = start_play_g;
1681 #if 0
1682 if (cuesheet_is_enabled() && tracks[track_widx].id3.cuesheet_type == 1)
1684 char cuepath[MAX_PATH];
1686 struct cuesheet *cue = start_play ? curr_cue : temp_cue;
1688 if (look_for_cuesheet_file(trackname, cuepath) &&
1689 parse_cuesheet(cuepath, cue))
1691 strcpy((cue)->audio_filename, trackname);
1692 if (start_play)
1693 cue_spoof_id3(curr_cue, &tracks[track_widx].id3);
1696 #endif
1698 if (tracks[track_widx].id3_hid < 0) {
1699 logf("no metatdata");
1700 return;
1703 struct mp3entry *track_id3;
1705 if (track_widx == track_ridx)
1706 track_id3 = &curtrack_id3;
1707 else
1708 track_id3 = bufgetid3(tracks[track_widx].id3_hid);
1710 if (track_id3->length == 0 || track_id3->filesize == 0)
1712 logf("audio_finish_load_track: invalid metadata");
1714 /* Invalid metadata */
1715 bufclose(tracks[track_widx].id3_hid);
1716 tracks[track_widx].id3_hid = -1;
1718 /* Skip invalid entry from playlist. */
1719 playlist_skip_entry(NULL, last_peek_offset--);
1721 /* load next track */
1722 LOGFQUEUE("audio > audio Q_AUDIO_FILL_BUFFER %d", (int)start_play);
1723 queue_post(&audio_queue, Q_AUDIO_FILL_BUFFER, start_play);
1725 return;
1728 #ifdef HAVE_ALBUMART
1729 if (tracks[track_widx].aa_hid < 0 && gui_sync_wps_uses_albumart())
1731 char aa_path[MAX_PATH];
1732 if (find_albumart(track_id3, aa_path, sizeof(aa_path)))
1733 tracks[track_widx].aa_hid = bufopen(aa_path, 0, TYPE_BITMAP);
1735 #endif
1737 /* Load the codec. */
1738 if (!audio_loadcodec(start_play))
1740 if (tracks[track_widx].codec_hid == ERR_BUFFER_FULL)
1742 /* No space for codec on buffer, not an error */
1743 return;
1746 /* This is an error condition, either no codec was found, or reading
1747 * the codec file failed part way through, either way, skip the track */
1748 snprintf(msgbuf, sizeof(msgbuf)-1, "No codec for: %s", track_id3->path);
1749 /* We should not use gui_syncplash from audio thread! */
1750 gui_syncsplash(HZ*2, msgbuf);
1751 /* Skip invalid entry from playlist. */
1752 playlist_skip_entry(NULL, last_peek_offset);
1753 return;
1756 track_id3->elapsed = 0;
1757 offset = track_id3->offset;
1759 enum data_type type = TYPE_PACKET_AUDIO;
1761 switch (track_id3->codectype) {
1762 case AFMT_MPA_L1:
1763 case AFMT_MPA_L2:
1764 case AFMT_MPA_L3:
1765 if (offset > 0) {
1766 file_offset = offset;
1767 track_id3->offset = offset;
1769 break;
1771 case AFMT_WAVPACK:
1772 if (offset > 0) {
1773 file_offset = offset;
1774 track_id3->offset = offset;
1775 track_id3->elapsed = track_id3->length / 2;
1777 break;
1779 case AFMT_OGG_VORBIS:
1780 case AFMT_SPEEX:
1781 case AFMT_FLAC:
1782 case AFMT_PCM_WAV:
1783 case AFMT_A52:
1784 case AFMT_AAC:
1785 case AFMT_MPC:
1786 case AFMT_APE:
1787 case AFMT_WMA:
1788 if (offset > 0)
1789 track_id3->offset = offset;
1790 break;
1792 case AFMT_NSF:
1793 case AFMT_SPC:
1794 case AFMT_SID:
1795 logf("Loading atomic %d",track_id3->codectype);
1796 type = TYPE_ATOMIC_AUDIO;
1797 break;
1800 logf("alt:%s", track_id3->path);
1802 if (file_offset > AUDIO_REBUFFER_GUESS_SIZE)
1803 file_offset -= AUDIO_REBUFFER_GUESS_SIZE;
1804 else if (track_id3->first_frame_offset)
1805 file_offset = track_id3->first_frame_offset;
1806 else
1807 file_offset = 0;
1809 tracks[track_widx].audio_hid = bufopen(track_id3->path, file_offset, type);
1811 if (tracks[track_widx].audio_hid < 0)
1812 return;
1814 /* All required data is now available for the codec. */
1815 tracks[track_widx].taginfo_ready = true;
1817 if (start_play)
1819 ci.curpos=file_offset;
1820 buf_request_buffer_handle(tracks[track_widx].audio_hid);
1823 track_widx = (track_widx + 1) & MAX_TRACK_MASK;
1825 send_event(PLAYBACK_EVENT_TRACK_BUFFER, track_id3);
1827 /* load next track */
1828 LOGFQUEUE("audio > audio Q_AUDIO_FILL_BUFFER");
1829 queue_post(&audio_queue, Q_AUDIO_FILL_BUFFER, 0);
1831 return;
1834 static void audio_fill_file_buffer(bool start_play, size_t offset)
1836 bool had_next_track = audio_next_track() != NULL;
1838 filling = STATE_FILLING;
1839 trigger_cpu_boost();
1841 /* No need to rebuffer if there are track skips pending. */
1842 if (ci.new_track != 0)
1843 return;
1845 /* Must reset the buffer before use if trashed or voice only - voice
1846 file size shouldn't have changed so we can go straight from
1847 BUFFER_STATE_VOICED_ONLY to BUFFER_STATE_INITIALIZED */
1848 if (buffer_state != BUFFER_STATE_INITIALIZED)
1849 audio_reset_buffer();
1851 logf("Starting buffer fill");
1853 if (!start_play)
1854 audio_clear_track_entries();
1856 /* Save the current resume position once. */
1857 playlist_update_resume_info(audio_current_track());
1859 audio_load_track(offset, start_play);
1861 if (!had_next_track && audio_next_track())
1862 track_changed = true;
1865 static void audio_rebuffer(void)
1867 logf("Forcing rebuffer");
1869 clear_track_info(CUR_TI);
1871 /* Reset track pointers */
1872 track_widx = track_ridx;
1873 audio_clear_track_entries();
1875 /* Fill the buffer */
1876 last_peek_offset = -1;
1877 ci.curpos = 0;
1879 if (!CUR_TI->taginfo_ready)
1880 memset(&curtrack_id3, 0, sizeof(struct mp3entry));
1882 audio_fill_file_buffer(false, 0);
1885 /* Called on request from the codec to get a new track. This is the codec part
1886 of the track transition. */
1887 static int audio_check_new_track(void)
1889 int track_count = audio_track_count();
1890 int old_track_ridx = track_ridx;
1891 int i, idx;
1892 bool forward;
1894 /* Now it's good time to send track finish events. */
1895 send_event(PLAYBACK_EVENT_TRACK_FINISH, &curtrack_id3);
1896 if (dir_skip)
1898 dir_skip = false;
1899 if (playlist_next_dir(ci.new_track))
1901 ci.new_track = 0;
1902 audio_rebuffer();
1903 goto skip_done;
1905 else
1907 LOGFQUEUE("audio >|= codec Q_CODEC_REQUEST_FAILED");
1908 return Q_CODEC_REQUEST_FAILED;
1912 if (new_playlist)
1913 ci.new_track = 0;
1915 /* If the playlist isn't that big */
1916 if (automatic_skip)
1918 while (!playlist_check(ci.new_track))
1920 if (ci.new_track >= 0)
1922 LOGFQUEUE("audio >|= codec Q_CODEC_REQUEST_FAILED");
1923 return Q_CODEC_REQUEST_FAILED;
1925 ci.new_track++;
1929 /* Update the playlist */
1930 last_peek_offset -= ci.new_track;
1932 if (playlist_next(ci.new_track) < 0)
1934 LOGFQUEUE("audio >|= codec Q_CODEC_REQUEST_FAILED");
1935 return Q_CODEC_REQUEST_FAILED;
1938 if (new_playlist)
1940 ci.new_track = 1;
1941 new_playlist = false;
1944 /* Save the track metadata to allow the WPS to display it
1945 while PCM finishes playing that track */
1946 copy_mp3entry(&prevtrack_id3, &curtrack_id3);
1948 /* Update the main buffer copy of the track metadata with the one
1949 the codec has been using (for the unbuffer callbacks) */
1950 if (CUR_TI->id3_hid >= 0)
1951 copy_mp3entry(bufgetid3(CUR_TI->id3_hid), &curtrack_id3);
1953 /* Save a pointer to the old track to allow later clearing */
1954 prev_ti = CUR_TI;
1956 for (i = 0; i < ci.new_track; i++)
1958 idx = (track_ridx + i) & MAX_TRACK_MASK;
1959 struct mp3entry *id3 = bufgetid3(tracks[idx].id3_hid);
1960 ssize_t offset = buf_handle_offset(tracks[idx].audio_hid);
1961 if (!id3 || offset < 0 || (unsigned)offset > id3->first_frame_offset)
1963 /* We don't have all the audio data for that track, so clear it,
1964 but keep the metadata. */
1965 if (tracks[idx].audio_hid >= 0 && bufclose(tracks[idx].audio_hid))
1967 tracks[idx].audio_hid = -1;
1968 tracks[idx].filesize = 0;
1973 /* Move to the new track */
1974 track_ridx = (track_ridx + ci.new_track) & MAX_TRACK_MASK;
1976 buf_set_base_handle(CUR_TI->audio_hid);
1978 if (automatic_skip)
1980 wps_offset = -ci.new_track;
1981 track_changed = true;
1984 /* If it is not safe to even skip this many track entries */
1985 if (ci.new_track >= track_count || ci.new_track <= track_count - MAX_TRACK)
1987 ci.new_track = 0;
1988 audio_rebuffer();
1989 goto skip_done;
1992 forward = ci.new_track > 0;
1993 ci.new_track = 0;
1995 /* If the target track is clearly not in memory */
1996 if (CUR_TI->filesize == 0 || !CUR_TI->taginfo_ready)
1998 audio_rebuffer();
1999 goto skip_done;
2002 /* When skipping backwards, it is possible that we've found a track that's
2003 * buffered, but which is around the track-wrap and therefore not the track
2004 * we are looking for */
2005 if (!forward)
2007 int cur_idx = track_ridx;
2008 bool taginfo_ready = true;
2009 /* We've wrapped the buffer backwards if new > old */
2010 bool wrap = track_ridx > old_track_ridx;
2012 while (1)
2014 cur_idx = (cur_idx + 1) & MAX_TRACK_MASK;
2016 /* if we've advanced past the wrap when cur_idx is zeroed */
2017 if (!cur_idx)
2018 wrap = false;
2020 /* if we aren't still on the wrap and we've caught the old track */
2021 if (!(wrap || cur_idx < old_track_ridx))
2022 break;
2024 /* If we hit a track in between without valid tag info, bail */
2025 if (!tracks[cur_idx].taginfo_ready)
2027 taginfo_ready = false;
2028 break;
2031 if (!taginfo_ready)
2033 audio_rebuffer();
2037 skip_done:
2038 audio_update_trackinfo();
2039 LOGFQUEUE("audio >|= codec Q_CODEC_REQUEST_COMPLETE");
2040 return Q_CODEC_REQUEST_COMPLETE;
2043 unsigned long audio_prev_elapsed(void)
2045 return prev_track_elapsed;
2048 static void audio_stop_codec_flush(void)
2050 ci.stop_codec = true;
2051 pcmbuf_pause(true);
2053 while (audio_codec_loaded)
2054 yield();
2056 /* If the audio codec is not loaded any more, and the audio is still
2057 * playing, it is now and _only_ now safe to call this function from the
2058 * audio thread */
2059 if (pcm_is_playing())
2061 pcmbuf_play_stop();
2062 pcmbuf_queue_clear();
2064 pcmbuf_pause(paused);
2067 static void audio_stop_playback(void)
2069 /* If we were playing, save resume information */
2070 if (playing)
2072 struct mp3entry *id3 = NULL;
2074 if (!ci.stop_codec)
2076 /* Set this early, the outside code yields and may allow the codec
2077 to try to wait for a reply on a buffer wait */
2078 ci.stop_codec = true;
2079 id3 = audio_current_track();
2082 /* Save the current playing spot, or NULL if the playlist has ended */
2083 playlist_update_resume_info(id3);
2085 /* TODO: Create auto bookmark too? */
2087 prev_track_elapsed = curtrack_id3.elapsed;
2089 remove_event(EVENT_BUFFER_LOW, buffering_low_buffer_callback);
2092 paused = false;
2093 audio_stop_codec_flush();
2094 playing = false;
2096 filling = STATE_IDLE;
2098 /* Mark all entries null. */
2099 audio_clear_track_entries();
2101 /* Close all tracks */
2102 audio_release_tracks();
2104 memset(&curtrack_id3, 0, sizeof(struct mp3entry));
2107 static void audio_play_start(size_t offset)
2109 int i;
2111 #if INPUT_SRC_CAPS != 0
2112 audio_set_input_source(AUDIO_SRC_PLAYBACK, SRCF_PLAYBACK);
2113 audio_set_output_source(AUDIO_SRC_PLAYBACK);
2114 #endif
2116 /* Wait for any previously playing audio to flush - TODO: Not necessary? */
2117 paused = false;
2118 audio_stop_codec_flush();
2120 track_changed = true;
2122 playing = true;
2124 ci.new_track = 0;
2125 ci.seek_time = 0;
2126 wps_offset = 0;
2128 sound_set_volume(global_settings.volume);
2129 track_widx = track_ridx = 0;
2131 /* Clear all track entries. */
2132 for (i = 0; i < MAX_TRACK; i++) {
2133 clear_track_info(&tracks[i]);
2136 last_peek_offset = -1;
2138 /* Officially playing */
2139 queue_reply(&audio_queue, 1);
2141 #ifndef HAVE_FLASH_STORAGE
2142 set_filebuf_watermark(buffer_margin, 0);
2143 #endif
2145 audio_fill_file_buffer(true, offset);
2147 add_event(EVENT_BUFFER_LOW, false, buffering_low_buffer_callback);
2149 LOGFQUEUE("audio > audio Q_AUDIO_TRACK_CHANGED");
2150 queue_post(&audio_queue, Q_AUDIO_TRACK_CHANGED, 0);
2154 /* Invalidates all but currently playing track. */
2155 static void audio_invalidate_tracks(void)
2157 if (audio_have_tracks())
2159 last_peek_offset = 0;
2160 track_widx = track_ridx;
2162 /* Mark all other entries null (also buffered wrong metadata). */
2163 audio_clear_track_entries();
2165 track_widx = (track_widx + 1) & MAX_TRACK_MASK;
2167 audio_fill_file_buffer(false, 0);
2171 static void audio_new_playlist(void)
2173 /* Prepare to start a new fill from the beginning of the playlist */
2174 last_peek_offset = -1;
2175 if (audio_have_tracks())
2177 if (paused)
2178 skipped_during_pause = true;
2179 track_widx = track_ridx;
2180 audio_clear_track_entries();
2182 track_widx = (track_widx + 1) & MAX_TRACK_MASK;
2184 /* Mark the current track as invalid to prevent skipping back to it */
2185 CUR_TI->taginfo_ready = false;
2188 /* Signal the codec to initiate a track change forward */
2189 new_playlist = true;
2190 ci.new_track = 1;
2192 /* Officially playing */
2193 queue_reply(&audio_queue, 1);
2195 audio_fill_file_buffer(false, 0);
2198 /* Called on manual track skip */
2199 static void audio_initiate_track_change(long direction)
2201 logf("audio_initiate_track_change(%ld)", direction);
2203 ci.new_track += direction;
2204 wps_offset -= direction;
2205 if (paused)
2206 skipped_during_pause = true;
2209 /* Called on manual dir skip */
2210 static void audio_initiate_dir_change(long direction)
2212 dir_skip = true;
2213 ci.new_track = direction;
2214 if (paused)
2215 skipped_during_pause = true;
2218 /* Called when PCM track change is complete */
2219 static void audio_finalise_track_change(void)
2221 logf("audio_finalise_track_change");
2223 if (automatic_skip)
2225 wps_offset = 0;
2226 automatic_skip = false;
2228 /* Invalidate prevtrack_id3 */
2229 prevtrack_id3.path[0] = 0;
2231 if (prev_ti && prev_ti->audio_hid < 0)
2233 /* No audio left so we clear all the track info. */
2234 clear_track_info(prev_ti);
2237 if (prev_ti && prev_ti->id3_hid >= 0)
2239 /* Reset the elapsed time to force the progressbar to be empty if
2240 the user skips back to this track */
2241 bufgetid3(prev_ti->id3_hid)->elapsed = 0;
2245 send_event(PLAYBACK_EVENT_TRACK_CHANGE, &curtrack_id3);
2247 track_changed = true;
2248 playlist_update_resume_info(audio_current_track());
2252 * Layout audio buffer as follows - iram buffer depends on target:
2253 * [|SWAP:iram][|TALK]|MALLOC|FILE|GUARD|PCM|[SWAP:dram[|iram]|]
2255 static void audio_reset_buffer(void)
2257 /* see audio_get_recording_buffer if this is modified */
2258 logf("audio_reset_buffer");
2260 /* If the setup of anything allocated before the file buffer is
2261 changed, do check the adjustments after the buffer_alloc call
2262 as it will likely be affected and need sliding over */
2264 /* Initially set up file buffer as all space available */
2265 malloc_buf = audiobuf + talk_get_bufsize();
2266 /* Align the malloc buf to line size. Especially important to cf
2267 targets that do line reads/writes. */
2268 malloc_buf = (unsigned char *)(((uintptr_t)malloc_buf + 15) & ~15);
2269 filebuf = malloc_buf + MALLOC_BUFSIZE; /* filebuf line align implied */
2270 filebuflen = audiobufend - filebuf;
2272 filebuflen &= ~15;
2274 /* Subtract whatever the pcm buffer says it used plus the guard buffer */
2275 filebuflen -= pcmbuf_init(filebuf + filebuflen) + GUARD_BUFSIZE;
2277 /* Make sure filebuflen is a longword multiple after adjustment - filebuf
2278 will already be line aligned */
2279 filebuflen &= ~3;
2281 buffering_reset(filebuf, filebuflen);
2283 /* Clear any references to the file buffer */
2284 buffer_state = BUFFER_STATE_INITIALIZED;
2286 #if defined(ROCKBOX_HAS_LOGF) && defined(LOGF_ENABLE)
2287 /* Make sure everything adds up - yes, some info is a bit redundant but
2288 aids viewing and the sumation of certain variables should add up to
2289 the location of others. */
2291 size_t pcmbufsize;
2292 const unsigned char *pcmbuf = pcmbuf_get_meminfo(&pcmbufsize);
2293 logf("mabuf: %08X", (unsigned)malloc_buf);
2294 logf("mabufe: %08X", (unsigned)(malloc_buf + MALLOC_BUFSIZE));
2295 logf("fbuf: %08X", (unsigned)filebuf);
2296 logf("fbufe: %08X", (unsigned)(filebuf + filebuflen));
2297 logf("gbuf: %08X", (unsigned)(filebuf + filebuflen));
2298 logf("gbufe: %08X", (unsigned)(filebuf + filebuflen + GUARD_BUFSIZE));
2299 logf("pcmb: %08X", (unsigned)pcmbuf);
2300 logf("pcmbe: %08X", (unsigned)(pcmbuf + pcmbufsize));
2302 #endif
2305 static void audio_thread(void)
2307 struct queue_event ev;
2309 pcm_postinit();
2311 audio_thread_ready = true;
2313 while (1)
2315 if (filling != STATE_FILLING) {
2316 cancel_cpu_boost();
2319 if (!pcmbuf_queue_scan(&ev))
2320 queue_wait_w_tmo(&audio_queue, &ev, HZ/2);
2322 switch (ev.id) {
2324 case Q_AUDIO_FILL_BUFFER:
2325 LOGFQUEUE("audio < Q_AUDIO_FILL_BUFFER %d", (int)ev.data);
2326 audio_fill_file_buffer((bool)ev.data, 0);
2327 break;
2329 case Q_AUDIO_FINISH_LOAD:
2330 LOGFQUEUE("audio < Q_AUDIO_FINISH_LOAD");
2331 audio_finish_load_track();
2332 break;
2334 case Q_AUDIO_PLAY:
2335 LOGFQUEUE("audio < Q_AUDIO_PLAY");
2336 if (playing && ev.data <= 0)
2337 audio_new_playlist();
2338 else
2340 audio_stop_playback();
2341 audio_play_start((size_t)ev.data);
2343 break;
2345 case Q_AUDIO_STOP:
2346 LOGFQUEUE("audio < Q_AUDIO_STOP");
2347 if (playing)
2348 audio_stop_playback();
2349 if (ev.data != 0)
2350 queue_clear(&audio_queue);
2351 break;
2353 case Q_AUDIO_PAUSE:
2354 LOGFQUEUE("audio < Q_AUDIO_PAUSE");
2355 if (!(bool) ev.data && skipped_during_pause && !pcmbuf_is_crossfade_active())
2356 pcmbuf_play_stop(); /* Flush old track on resume after skip */
2357 skipped_during_pause = false;
2358 if (!playing)
2359 break;
2360 pcmbuf_pause((bool)ev.data);
2361 paused = (bool)ev.data;
2362 break;
2364 case Q_AUDIO_SKIP:
2365 LOGFQUEUE("audio < Q_AUDIO_SKIP");
2366 audio_initiate_track_change((long)ev.data);
2367 break;
2369 case Q_AUDIO_PRE_FF_REWIND:
2370 LOGFQUEUE("audio < Q_AUDIO_PRE_FF_REWIND");
2371 if (!playing)
2372 break;
2373 pcmbuf_pause(true);
2374 break;
2376 case Q_AUDIO_FF_REWIND:
2377 LOGFQUEUE("audio < Q_AUDIO_FF_REWIND");
2378 if (!playing)
2379 break;
2380 if (automatic_skip)
2382 /* An automatic track skip is in progress. Finalize it,
2383 then go back to the previous track */
2384 audio_finalise_track_change();
2385 ci.new_track = -1;
2387 ci.seek_time = (long)ev.data+1;
2388 break;
2390 case Q_AUDIO_CHECK_NEW_TRACK:
2391 LOGFQUEUE("audio < Q_AUDIO_CHECK_NEW_TRACK");
2392 queue_reply(&audio_queue, audio_check_new_track());
2393 break;
2395 case Q_AUDIO_DIR_SKIP:
2396 LOGFQUEUE("audio < Q_AUDIO_DIR_SKIP");
2397 audio_initiate_dir_change(ev.data);
2398 break;
2400 case Q_AUDIO_FLUSH:
2401 LOGFQUEUE("audio < Q_AUDIO_FLUSH");
2402 audio_invalidate_tracks();
2403 break;
2405 case Q_AUDIO_TRACK_CHANGED:
2406 /* PCM track change done */
2407 LOGFQUEUE("audio < Q_AUDIO_TRACK_CHANGED");
2408 audio_finalise_track_change();
2409 break;
2411 #ifndef SIMULATOR
2412 case SYS_USB_CONNECTED:
2413 LOGFQUEUE("audio < SYS_USB_CONNECTED");
2414 if (playing)
2415 audio_stop_playback();
2416 #ifdef PLAYBACK_VOICE
2417 voice_stop();
2418 #endif
2419 usb_acknowledge(SYS_USB_CONNECTED_ACK);
2420 usb_wait_for_disconnect(&audio_queue);
2422 /* Mark all entries null. */
2423 audio_clear_track_entries();
2425 /* release tracks to make sure all handles are closed */
2426 audio_release_tracks();
2427 break;
2428 #endif
2430 case SYS_TIMEOUT:
2431 LOGFQUEUE_SYS_TIMEOUT("audio < SYS_TIMEOUT");
2432 break;
2434 default:
2435 LOGFQUEUE("audio < default");
2436 break;
2437 } /* end switch */
2438 } /* end while */
2441 /* Initialize the audio system - called from init() in main.c.
2442 * Last function because of all the references to internal symbols
2444 void audio_init(void)
2446 struct thread_entry *audio_thread_p;
2448 /* Can never do this twice */
2449 if (audio_is_initialized)
2451 logf("audio: already initialized");
2452 return;
2455 logf("audio: initializing");
2457 /* Initialize queues before giving control elsewhere in case it likes
2458 to send messages. Thread creation will be delayed however so nothing
2459 starts running until ready if something yields such as talk_init. */
2460 queue_init(&audio_queue, true);
2461 queue_init(&codec_queue, false);
2462 queue_init(&pcmbuf_queue, false);
2464 pcm_init();
2466 /* Initialize codec api. */
2467 ci.read_filebuf = codec_filebuf_callback;
2468 ci.pcmbuf_insert = codec_pcmbuf_insert_callback;
2469 ci.get_codec_memory = codec_get_memory_callback;
2470 ci.request_buffer = codec_request_buffer_callback;
2471 ci.advance_buffer = codec_advance_buffer_callback;
2472 ci.advance_buffer_loc = codec_advance_buffer_loc_callback;
2473 ci.request_next_track = codec_request_next_track_callback;
2474 ci.seek_buffer = codec_seek_buffer_callback;
2475 ci.seek_complete = codec_seek_complete_callback;
2476 ci.set_elapsed = codec_set_elapsed_callback;
2477 ci.set_offset = codec_set_offset_callback;
2478 ci.configure = codec_configure_callback;
2479 ci.discard_codec = codec_discard_codec_callback;
2480 ci.dsp = (struct dsp_config *)dsp_configure(NULL, DSP_MYDSP,
2481 CODEC_IDX_AUDIO);
2483 /* initialize the buffer */
2484 filebuf = audiobuf;
2486 /* audio_reset_buffer must to know the size of voice buffer so init
2487 talk first */
2488 talk_init();
2490 codec_thread_p = create_thread(
2491 codec_thread, codec_stack, sizeof(codec_stack),
2492 CREATE_THREAD_FROZEN,
2493 codec_thread_name IF_PRIO(, PRIORITY_PLAYBACK)
2494 IF_COP(, CPU));
2496 queue_enable_queue_send(&codec_queue, &codec_queue_sender_list,
2497 codec_thread_p);
2499 audio_thread_p = create_thread(audio_thread, audio_stack,
2500 sizeof(audio_stack), CREATE_THREAD_FROZEN,
2501 audio_thread_name IF_PRIO(, PRIORITY_USER_INTERFACE)
2502 IF_COP(, CPU));
2504 queue_enable_queue_send(&audio_queue, &audio_queue_sender_list,
2505 audio_thread_p);
2507 #ifdef PLAYBACK_VOICE
2508 voice_thread_init();
2509 #endif
2511 /* Set crossfade setting for next buffer init which should be about... */
2512 pcmbuf_crossfade_enable(global_settings.crossfade);
2514 /* initialize the buffering system */
2516 buffering_init();
2517 /* ...now! Set up the buffers */
2518 audio_reset_buffer();
2520 int i;
2521 for(i = 0; i < MAX_TRACK; i++)
2523 tracks[i].audio_hid = -1;
2524 tracks[i].id3_hid = -1;
2525 tracks[i].codec_hid = -1;
2526 #ifdef HAVE_ALBUMART
2527 tracks[i].aa_hid = -1;
2528 #endif
2531 add_event(EVENT_HANDLE_REBUFFER, false, buffering_handle_rebuffer_callback);
2532 add_event(EVENT_HANDLE_FINISHED, false, buffering_handle_finished_callback);
2534 /* Probably safe to say */
2535 audio_is_initialized = true;
2537 sound_settings_apply();
2538 #ifndef HAVE_FLASH_STORAGE
2539 audio_set_buffer_margin(global_settings.buffer_margin);
2540 #endif
2542 /* it's safe to let the threads run now */
2543 #ifdef PLAYBACK_VOICE
2544 voice_thread_resume();
2545 #endif
2546 thread_thaw(codec_thread_p);
2547 thread_thaw(audio_thread_p);
2549 } /* audio_init */
2551 void audio_wait_for_init(void)
2553 /* audio thread will only set this once after it finished the final
2554 * audio hardware init so this little construct is safe - even
2555 * cross-core. */
2556 while (!audio_thread_ready)
2558 sleep(0);