Make basic cache functions into calls, and get rid of CACHE_FUNCTION_WRAPPERS and...
[kugel-rb.git] / apps / playback.c
blobdeaebfbdf0cdbb2d93c98fecdd0629332489e9f1
1 /***************************************************************************
2 * __________ __ ___.
3 * Open \______ \ ____ ____ | | _\_ |__ _______ ___
4 * Source | _// _ \_/ ___\| |/ /| __ \ / _ \ \/ /
5 * Jukebox | | ( <_> ) \___| < | \_\ ( <_> > < <
6 * Firmware |____|_ /\____/ \___ >__|_ \|___ /\____/__/\_ \
7 * \/ \/ \/ \/ \/
8 * $Id$
10 * Copyright (C) 2005-2007 Miika Pekkarinen
11 * Copyright (C) 2007-2008 Nicolas Pennequin
13 * This program is free software; you can redistribute it and/or
14 * modify it under the terms of the GNU General Public License
15 * as published by the Free Software Foundation; either version 2
16 * of the License, or (at your option) any later version.
18 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
19 * KIND, either express or implied.
21 ****************************************************************************/
23 /* TODO: Pause should be handled in here, rather than PCMBUF so that voice can
24 * play whilst audio is paused */
26 #include <stdio.h>
27 #include <string.h>
28 #include <stdlib.h>
29 #include <ctype.h>
31 #include "system.h"
32 #include "thread.h"
33 #include "file.h"
34 #include "panic.h"
35 #include "memory.h"
36 #include "lcd.h"
37 #include "font.h"
38 #include "button.h"
39 #include "kernel.h"
40 #include "tree.h"
41 #include "debug.h"
42 #include "sprintf.h"
43 #include "settings.h"
44 #include "codecs.h"
45 #include "audio.h"
46 #include "buffering.h"
47 #include "appevents.h"
48 #include "voice_thread.h"
49 #include "mp3_playback.h"
50 #include "usb.h"
51 #include "status.h"
52 #include "storage.h"
53 #include "screens.h"
54 #include "playlist.h"
55 #include "playback.h"
56 #include "pcmbuf.h"
57 #include "buffer.h"
58 #include "dsp.h"
59 #include "abrepeat.h"
60 #include "cuesheet.h"
61 #ifdef HAVE_TAGCACHE
62 #include "tagcache.h"
63 #endif
64 #ifdef HAVE_LCD_BITMAP
65 #include "icons.h"
66 #include "peakmeter.h"
67 #include "action.h"
68 #include "albumart.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 #include "pcm_record.h"
83 #endif
85 #ifdef IPOD_ACCESSORY_PROTOCOL
86 #include "iap.h"
87 #endif
89 #define PLAYBACK_VOICE
91 /* amount of guess-space to allow for codecs that must hunt and peck
92 * for their correct seeek target, 32k seems a good size */
93 #define AUDIO_REBUFFER_GUESS_SIZE (1024*32)
95 /* Define LOGF_ENABLE to enable logf output in this file */
96 /*#define LOGF_ENABLE*/
97 #include "logf.h"
99 /* macros to enable logf for queues
100 logging on SYS_TIMEOUT can be disabled */
101 #ifdef SIMULATOR
102 /* Define this for logf output of all queuing except SYS_TIMEOUT */
103 #define PLAYBACK_LOGQUEUES
104 /* Define this to logf SYS_TIMEOUT messages */
105 /*#define PLAYBACK_LOGQUEUES_SYS_TIMEOUT*/
106 #endif
108 #ifdef PLAYBACK_LOGQUEUES
109 #define LOGFQUEUE logf
110 #else
111 #define LOGFQUEUE(...)
112 #endif
114 #ifdef PLAYBACK_LOGQUEUES_SYS_TIMEOUT
115 #define LOGFQUEUE_SYS_TIMEOUT logf
116 #else
117 #define LOGFQUEUE_SYS_TIMEOUT(...)
118 #endif
121 /* Define one constant that includes recording related functionality */
122 #if defined(HAVE_RECORDING) && !defined(SIMULATOR)
123 #define AUDIO_HAVE_RECORDING
124 #endif
126 enum {
127 Q_NULL = 0,
128 Q_AUDIO_PLAY = 1,
129 Q_AUDIO_STOP,
130 Q_AUDIO_PAUSE,
131 Q_AUDIO_SKIP,
132 Q_AUDIO_PRE_FF_REWIND,
133 Q_AUDIO_FF_REWIND,
134 Q_AUDIO_CHECK_NEW_TRACK,
135 Q_AUDIO_FLUSH,
136 Q_AUDIO_TRACK_CHANGED,
137 Q_AUDIO_DIR_SKIP,
138 Q_AUDIO_POSTINIT,
139 Q_AUDIO_FILL_BUFFER,
140 Q_AUDIO_FINISH_LOAD,
141 Q_CODEC_REQUEST_COMPLETE,
142 Q_CODEC_REQUEST_FAILED,
144 Q_CODEC_LOAD,
145 Q_CODEC_LOAD_DISK,
147 #ifdef AUDIO_HAVE_RECORDING
148 Q_ENCODER_LOAD_DISK,
149 Q_ENCODER_RECORD,
150 #endif
152 Q_CODEC_DO_CALLBACK,
155 enum filling_state {
156 STATE_IDLE, /* audio is stopped: nothing to do */
157 STATE_FILLING, /* adding tracks to the buffer */
158 STATE_FULL, /* can't add any more tracks */
159 STATE_END_OF_PLAYLIST, /* all remaining tracks have been added */
160 STATE_FINISHED, /* all remaining tracks are fully buffered */
163 #define MAX_TRACK 128
165 #define MAX_TRACK_MASK (MAX_TRACK-1)
167 /* As defined in plugins/lib/xxx2wav.h */
168 #define GUARD_BUFSIZE (32*1024)
170 /* As defined in plugin.lds */
171 #if defined(CPU_PP)
172 #define CODEC_IRAM_ORIGIN ((unsigned char *)0x4000c000)
173 #define CODEC_IRAM_SIZE ((size_t)0xc000)
174 #elif defined(IAUDIO_X5) || defined(IAUDIO_M5)
175 #define CODEC_IRAM_ORIGIN ((unsigned char *)0x10010000)
176 #define CODEC_IRAM_SIZE ((size_t)0x10000)
177 #else
178 #define CODEC_IRAM_ORIGIN ((unsigned char *)0x1000c000)
179 #define CODEC_IRAM_SIZE ((size_t)0xc000)
180 #endif
182 bool audio_is_initialized = false;
183 static bool audio_thread_ready SHAREDBSS_ATTR = false;
185 /* Variables are commented with the threads that use them: *
186 * A=audio, C=codec, V=voice. A suffix of - indicates that *
187 * the variable is read but not updated on that thread. */
188 /* TBD: Split out "audio" and "playback" (ie. calling) threads */
190 /* Main state control */
191 static volatile bool audio_codec_loaded SHAREDBSS_ATTR = false; /* Codec loaded? (C/A-) */
192 static volatile bool playing SHAREDBSS_ATTR = false; /* Is audio playing? (A) */
193 static volatile bool paused SHAREDBSS_ATTR = false; /* Is audio paused? (A/C-) */
195 /* Ring buffer where compressed audio and codecs are loaded */
196 static unsigned char *filebuf = NULL; /* Start of buffer (A/C-) */
197 static unsigned char *malloc_buf = NULL; /* Start of malloc buffer (A/C-) */
198 /* FIXME: make filebuflen static */
199 size_t filebuflen = 0; /* Size of buffer (A/C-) */
200 /* FIXME: make buf_ridx (C/A-) */
202 /* Possible arrangements of the buffer */
203 static int buffer_state = AUDIOBUF_STATE_TRASHED; /* Buffer state */
205 /* Used to keep the WPS up-to-date during track transtition */
206 static struct mp3entry prevtrack_id3;
208 /* Used to provide the codec with a pointer */
209 static struct mp3entry curtrack_id3;
211 /* Used to make next track info available while playing last track on buffer */
212 static struct mp3entry lasttrack_id3;
214 /* Track info structure about songs in the file buffer (A/C-) */
215 struct track_info {
216 int audio_hid; /* The ID for the track's buffer handle */
217 int id3_hid; /* The ID for the track's metadata handle */
218 int codec_hid; /* The ID for the track's codec handle */
219 #ifdef HAVE_ALBUMART
220 int aa_hid; /* The ID for the track's album art handle */
221 #endif
223 size_t filesize; /* File total length */
225 bool taginfo_ready; /* Is metadata read */
228 static struct track_info tracks[MAX_TRACK];
229 static volatile int track_ridx = 0; /* Track being decoded (A/C-) */
230 static int track_widx = 0; /* Track being buffered (A) */
232 #define CUR_TI (&tracks[track_ridx]) /* Playing track info pointer (A/C-) */
233 static struct track_info *prev_ti = NULL; /* Pointer to the previously played
234 track */
236 /* Set by the audio thread when the current track information has updated
237 * and the WPS may need to update its cached information */
238 static bool track_changed = false;
240 /* Information used only for filling the buffer */
241 /* Playlist steps from playing track to next track to be buffered (A) */
242 static int last_peek_offset = 0;
244 /* Scrobbler support */
245 static unsigned long prev_track_elapsed = 0; /* Previous track elapsed time (C/A-)*/
247 static enum filling_state filling;
249 /* Track change controls */
250 static bool automatic_skip = false; /* Who initiated in-progress skip? (C/A-) */
251 static bool dir_skip = false; /* Is a directory skip pending? (A) */
252 static bool new_playlist = false; /* Are we starting a new playlist? (A) */
253 static int wps_offset = 0; /* Pending track change offset, to keep WPS responsive (A) */
254 static bool skipped_during_pause = false; /* Do we need to clear the PCM buffer when playback resumes (A) */
256 static bool start_play_g = false; /* Used by audio_load_track to notify
257 audio_finish_load_track about start_play */
259 /* True when a track load is in progress, i.e. audio_load_track() has returned
260 * but audio_finish_load_track() hasn't been called yet. Used to avoid allowing
261 * audio_load_track() to get called twice in a row, which would cause problems.
263 static bool track_load_started = false;
265 /* Set to true if the codec thread should send an audio stop request
266 * (typically because the end of the playlist has been reached).
268 static bool codec_requested_stop = false;
270 #ifdef HAVE_DISK_STORAGE
271 static size_t buffer_margin = 0; /* Buffer margin aka anti-skip buffer (A/C-) */
272 #endif
274 /* Multiple threads */
275 /* Set the watermark to trigger buffer fill (A/C) */
276 static void set_filebuf_watermark(void);
278 /* Audio thread */
279 static struct event_queue audio_queue SHAREDBSS_ATTR;
280 static struct queue_sender_list audio_queue_sender_list SHAREDBSS_ATTR;
281 static long audio_stack[(DEFAULT_STACK_SIZE + 0x1000)/sizeof(long)];
282 static const char audio_thread_name[] = "audio";
284 static void audio_thread(void);
285 static void audio_initiate_track_change(long direction);
286 static bool audio_have_tracks(void);
287 static void audio_reset_buffer(void);
288 static void audio_stop_playback(void);
290 /* Codec thread */
291 extern struct codec_api ci;
292 static struct event_queue codec_queue SHAREDBSS_ATTR;
293 static struct queue_sender_list codec_queue_sender_list;
294 static long codec_stack[(DEFAULT_STACK_SIZE + 0x2000)/sizeof(long)]
295 IBSS_ATTR;
296 static const char codec_thread_name[] = "codec";
297 unsigned int codec_thread_id; /* For modifying thread priority later. */
299 /* PCM buffer messaging */
300 static struct event_queue pcmbuf_queue SHAREDBSS_ATTR;
302 /* Function to be called by pcm buffer callbacks.
303 * Permissible Context(s): Audio interrupt
305 static void pcmbuf_callback_queue_post(long id, intptr_t data)
307 /* No lock since we're already in audio interrupt context */
308 queue_post(&pcmbuf_queue, id, data);
311 /* Scan the pcmbuf queue and return true if a message pulled.
312 * Permissible Context(s): Thread
314 static bool pcmbuf_queue_scan(struct queue_event *ev)
316 if (!queue_empty(&pcmbuf_queue))
318 /* Transfer message to audio queue */
319 pcm_play_lock();
320 /* Pull message - never, ever any blocking call! */
321 queue_wait_w_tmo(&pcmbuf_queue, ev, 0);
322 pcm_play_unlock();
323 return true;
326 return false;
329 /* Clear the pcmbuf queue of messages
330 * Permissible Context(s): Thread
332 static void pcmbuf_queue_clear(void)
334 pcm_play_lock();
335 queue_clear(&pcmbuf_queue);
336 pcm_play_unlock();
339 /* --- Helper functions --- */
341 static struct mp3entry *bufgetid3(int handle_id)
343 if (handle_id < 0)
344 return NULL;
346 struct mp3entry *id3;
347 ssize_t ret = bufgetdata(handle_id, 0, (void *)&id3);
349 if (ret < 0 || ret != sizeof(struct mp3entry))
350 return NULL;
352 return id3;
355 static bool clear_track_info(struct track_info *track)
357 /* bufclose returns true if the handle is not found, or if it is closed
358 * successfully, so these checks are safe on non-existant handles */
359 if (!track)
360 return false;
362 if (track->codec_hid >= 0) {
363 if (bufclose(track->codec_hid))
364 track->codec_hid = -1;
365 else
366 return false;
369 if (track->id3_hid >= 0) {
370 if (bufclose(track->id3_hid))
371 track->id3_hid = -1;
372 else
373 return false;
376 if (track->audio_hid >= 0) {
377 if (bufclose(track->audio_hid))
378 track->audio_hid = -1;
379 else
380 return false;
383 #ifdef HAVE_ALBUMART
384 if (track->aa_hid >= 0) {
385 if (bufclose(track->aa_hid))
386 track->aa_hid = -1;
387 else
388 return false;
390 #endif
392 track->filesize = 0;
393 track->taginfo_ready = false;
395 return true;
398 /* --- External interfaces --- */
400 /* This sends a stop message and the audio thread will dump all it's
401 subsequenct messages */
402 void audio_hard_stop(void)
404 /* Stop playback */
405 LOGFQUEUE("audio >| audio Q_AUDIO_STOP: 1");
406 queue_send(&audio_queue, Q_AUDIO_STOP, 1);
407 #ifdef PLAYBACK_VOICE
408 voice_stop();
409 #endif
412 bool audio_restore_playback(int type)
414 switch (type)
416 case AUDIO_WANT_PLAYBACK:
417 if (buffer_state != AUDIOBUF_STATE_INITIALIZED)
418 audio_reset_buffer();
419 return true;
420 case AUDIO_WANT_VOICE:
421 if (buffer_state == AUDIOBUF_STATE_TRASHED)
422 audio_reset_buffer();
423 return true;
424 default:
425 return false;
429 unsigned char *audio_get_buffer(bool talk_buf, size_t *buffer_size)
431 unsigned char *buf, *end;
433 if (audio_is_initialized)
435 audio_hard_stop();
437 /* else buffer_state will be AUDIOBUF_STATE_TRASHED at this point */
439 if (buffer_size == NULL)
441 /* Special case for talk_init to use since it already knows it's
442 trashed */
443 buffer_state = AUDIOBUF_STATE_TRASHED;
444 return NULL;
447 if (talk_buf || buffer_state == AUDIOBUF_STATE_TRASHED
448 || !talk_voice_required())
450 logf("get buffer: talk, audio");
451 /* Ok to use everything from audiobuf to audiobufend - voice is loaded,
452 the talk buffer is not needed because voice isn't being used, or
453 could be AUDIOBUF_STATE_TRASHED already. If state is
454 AUDIOBUF_STATE_VOICED_ONLY, no problem as long as memory isn't written
455 without the caller knowing what's going on. Changing certain settings
456 may move it to a worse condition but the memory in use by something
457 else will remain undisturbed.
459 if (buffer_state != AUDIOBUF_STATE_TRASHED)
461 talk_buffer_steal();
462 buffer_state = AUDIOBUF_STATE_TRASHED;
465 buf = audiobuf;
466 end = audiobufend;
468 else
470 /* Safe to just return this if already AUDIOBUF_STATE_VOICED_ONLY or
471 still AUDIOBUF_STATE_INITIALIZED */
472 /* Skip talk buffer and move pcm buffer to end to maximize available
473 contiguous memory - no audio running means voice will not need the
474 swap space */
475 logf("get buffer: audio");
476 buf = audiobuf + talk_get_bufsize();
477 end = audiobufend - pcmbuf_init(audiobufend);
478 buffer_state = AUDIOBUF_STATE_VOICED_ONLY;
481 *buffer_size = end - buf;
483 return buf;
486 int audio_buffer_state(void)
488 return buffer_state;
491 #ifdef HAVE_RECORDING
492 unsigned char *audio_get_recording_buffer(size_t *buffer_size)
494 /* Stop audio, voice and obtain all available buffer space */
495 audio_hard_stop();
496 talk_buffer_steal();
498 unsigned char *end = audiobufend;
499 buffer_state = AUDIOBUF_STATE_TRASHED;
500 *buffer_size = end - audiobuf;
502 return (unsigned char *)audiobuf;
505 bool audio_load_encoder(int afmt)
507 #ifndef SIMULATOR
508 const char *enc_fn = get_codec_filename(afmt | CODEC_TYPE_ENCODER);
509 if (!enc_fn)
510 return false;
512 audio_remove_encoder();
513 ci.enc_codec_loaded = 0; /* clear any previous error condition */
515 LOGFQUEUE("codec > Q_ENCODER_LOAD_DISK");
516 queue_post(&codec_queue, Q_ENCODER_LOAD_DISK, (intptr_t)enc_fn);
518 while (ci.enc_codec_loaded == 0)
519 yield();
521 logf("codec loaded: %d", ci.enc_codec_loaded);
523 return ci.enc_codec_loaded > 0;
524 #else
525 (void)afmt;
526 return true;
527 #endif
528 } /* audio_load_encoder */
530 void audio_remove_encoder(void)
532 #ifndef SIMULATOR
533 /* force encoder codec unload (if currently loaded) */
534 if (ci.enc_codec_loaded <= 0)
535 return;
537 ci.stop_encoder = true;
538 while (ci.enc_codec_loaded > 0)
539 yield();
540 #endif
541 } /* audio_remove_encoder */
543 #endif /* HAVE_RECORDING */
545 #ifdef HAVE_ALBUMART
546 int audio_current_aa_hid(void)
548 int cur_idx;
549 int offset = ci.new_track + wps_offset;
551 cur_idx = track_ridx + offset;
552 cur_idx &= MAX_TRACK_MASK;
554 return tracks[cur_idx].aa_hid;
556 #endif
558 struct mp3entry* audio_current_track(void)
560 const char *filename;
561 static struct mp3entry temp_id3;
562 struct playlist_track_info trackinfo;
563 int cur_idx;
564 int offset = ci.new_track + wps_offset;
566 cur_idx = (track_ridx + offset) & MAX_TRACK_MASK;
568 if (cur_idx == track_ridx && *curtrack_id3.path)
570 /* The usual case */
571 return &curtrack_id3;
573 else if (automatic_skip && offset == -1 && *prevtrack_id3.path)
575 /* We're in a track transition. The codec has moved on to the nex track,
576 but the audio being played is still the same (now previous) track.
577 prevtrack_id3.elapsed is being updated in an ISR by
578 codec_pcmbuf_position_callback */
579 return &prevtrack_id3;
581 else if (tracks[cur_idx].id3_hid >= 0)
583 /* Get the ID3 metadata from the main buffer */
584 struct mp3entry *ret = bufgetid3(tracks[cur_idx].id3_hid);
585 if (ret) return ret;
588 /* We didn't find the ID3 metadata, so we fill temp_id3 with the little info
589 we have and return that. */
591 memset(&temp_id3, 0, sizeof(struct mp3entry));
593 playlist_get_track_info(NULL, playlist_next(0)+wps_offset, &trackinfo);
594 filename = trackinfo.filename;
595 if (!filename)
596 filename = "No file!";
598 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
599 if (tagcache_fill_tags(&temp_id3, filename))
600 return &temp_id3;
601 #endif
603 strncpy(temp_id3.path, filename, sizeof(temp_id3.path)-1);
604 temp_id3.title = strrchr(temp_id3.path, '/');
605 if (!temp_id3.title)
606 temp_id3.title = &temp_id3.path[0];
607 else
608 temp_id3.title++;
610 return &temp_id3;
613 struct mp3entry* audio_next_track(void)
615 int next_idx;
616 int offset = ci.new_track + wps_offset;
618 if (!audio_have_tracks())
619 return NULL;
621 if (wps_offset == -1 && *prevtrack_id3.path)
623 /* We're in a track transition. The next track for the WPS is the one
624 currently being decoded. */
625 return &curtrack_id3;
628 next_idx = (track_ridx + offset + 1) & MAX_TRACK_MASK;
630 if (tracks[next_idx].id3_hid >= 0)
631 return bufgetid3(tracks[next_idx].id3_hid);
633 if (next_idx == track_widx)
635 /* The next track hasn't been buffered yet, so we return the static
636 version of its metadata. */
637 return &lasttrack_id3;
640 return NULL;
643 bool audio_has_changed_track(void)
645 if (track_changed)
647 #ifdef IPOD_ACCESSORY_PROTOCOL
648 iap_track_changed();
649 #endif
650 track_changed = false;
651 return true;
654 return false;
657 void audio_play(long offset)
659 logf("audio_play");
661 #ifdef PLAYBACK_VOICE
662 /* Truncate any existing voice output so we don't have spelling
663 * etc. over the first part of the played track */
664 talk_force_shutup();
665 #endif
667 /* Start playback */
668 LOGFQUEUE("audio >| audio Q_AUDIO_PLAY: %ld", offset);
669 /* Don't return until playback has actually started */
670 queue_send(&audio_queue, Q_AUDIO_PLAY, offset);
673 void audio_stop(void)
675 /* Stop playback */
676 LOGFQUEUE("audio >| audio Q_AUDIO_STOP");
677 /* Don't return until playback has actually stopped */
678 queue_send(&audio_queue, Q_AUDIO_STOP, 0);
681 void audio_pause(void)
683 LOGFQUEUE("audio >| audio Q_AUDIO_PAUSE");
684 /* Don't return until playback has actually paused */
685 queue_send(&audio_queue, Q_AUDIO_PAUSE, true);
688 void audio_resume(void)
690 LOGFQUEUE("audio >| audio Q_AUDIO_PAUSE resume");
691 /* Don't return until playback has actually resumed */
692 queue_send(&audio_queue, Q_AUDIO_PAUSE, false);
695 void audio_skip(int direction)
697 if (playlist_check(ci.new_track + wps_offset + direction))
699 if (global_settings.beep)
700 pcmbuf_beep(2000, 100, 2500*global_settings.beep);
702 LOGFQUEUE("audio > audio Q_AUDIO_SKIP %d", direction);
703 queue_post(&audio_queue, Q_AUDIO_SKIP, direction);
704 /* Update wps while our message travels inside deep playback queues. */
705 wps_offset += direction;
706 track_changed = true;
708 else
710 /* No more tracks. */
711 if (global_settings.beep)
712 pcmbuf_beep(1000, 100, 1500*global_settings.beep);
716 void audio_next(void)
718 audio_skip(1);
721 void audio_prev(void)
723 audio_skip(-1);
726 void audio_next_dir(void)
728 LOGFQUEUE("audio > audio Q_AUDIO_DIR_SKIP 1");
729 queue_post(&audio_queue, Q_AUDIO_DIR_SKIP, 1);
732 void audio_prev_dir(void)
734 LOGFQUEUE("audio > audio Q_AUDIO_DIR_SKIP -1");
735 queue_post(&audio_queue, Q_AUDIO_DIR_SKIP, -1);
738 void audio_pre_ff_rewind(void)
740 LOGFQUEUE("audio > audio Q_AUDIO_PRE_FF_REWIND");
741 queue_post(&audio_queue, Q_AUDIO_PRE_FF_REWIND, 0);
744 void audio_ff_rewind(long newpos)
746 LOGFQUEUE("audio > audio Q_AUDIO_FF_REWIND");
747 queue_post(&audio_queue, Q_AUDIO_FF_REWIND, newpos);
750 void audio_flush_and_reload_tracks(void)
752 LOGFQUEUE("audio > audio Q_AUDIO_FLUSH");
753 queue_post(&audio_queue, Q_AUDIO_FLUSH, 0);
756 void audio_error_clear(void)
758 #ifdef AUDIO_HAVE_RECORDING
759 pcm_rec_error_clear();
760 #endif
763 int audio_status(void)
765 int ret = 0;
767 if (playing)
768 ret |= AUDIO_STATUS_PLAY;
770 if (paused)
771 ret |= AUDIO_STATUS_PAUSE;
773 #ifdef HAVE_RECORDING
774 /* Do this here for constitency with mpeg.c version */
775 ret |= pcm_rec_status();
776 #endif
778 return ret;
781 int audio_get_file_pos(void)
783 return 0;
786 #ifdef HAVE_DISK_STORAGE
787 void audio_set_buffer_margin(int setting)
789 static const int lookup[] = {5, 15, 30, 60, 120, 180, 300, 600};
790 buffer_margin = lookup[setting];
791 logf("buffer margin: %ld", (long)buffer_margin);
792 set_filebuf_watermark();
794 #endif
796 /* Take necessary steps to enable or disable the crossfade setting */
797 void audio_set_crossfade(int enable)
799 size_t offset;
800 bool was_playing;
801 size_t size;
803 /* Tell it the next setting to use */
804 pcmbuf_crossfade_enable(enable);
806 /* Return if size hasn't changed or this is too early to determine
807 which in the second case there's no way we could be playing
808 anything at all */
809 if (pcmbuf_is_same_size())
811 /* This function is a copout and just syncs some variables -
812 to be removed at a later date */
813 pcmbuf_crossfade_enable_finished();
814 return;
817 offset = 0;
818 was_playing = playing;
820 /* Playback has to be stopped before changing the buffer size */
821 if (was_playing)
823 /* Store the track resume position */
824 offset = curtrack_id3.offset;
827 /* Blast it - audio buffer will have to be setup again next time
828 something plays */
829 audio_get_buffer(true, &size);
831 /* Restart playback if audio was running previously */
832 if (was_playing)
833 audio_play(offset);
836 /* --- Routines called from multiple threads --- */
838 static void set_filebuf_watermark(void)
840 if (!filebuf)
841 return; /* Audio buffers not yet set up */
843 #ifdef HAVE_FLASH_STORAGE
844 int seconds = 1;
845 #else
846 int seconds;
847 int spinup = ata_spinup_time();
848 if (spinup)
849 seconds = (spinup / HZ) + 1;
850 else
851 seconds = 5;
852 #endif
854 /* bitrate of last track in buffer dictates watermark */
855 struct mp3entry* id3 = NULL;
856 if (tracks[track_widx].taginfo_ready)
857 id3 = bufgetid3(tracks[track_widx].id3_hid);
858 else
859 id3 = bufgetid3(tracks[track_widx-1].id3_hid);
860 if (!id3) {
861 logf("fwmark: No id3 for last track (r%d/w%d), aborting!", track_ridx, track_widx);
862 return;
864 size_t bytes = id3->bitrate * (1000/8) * seconds;
865 buf_set_watermark(bytes);
866 logf("fwmark: %d", bytes);
869 const char *get_codec_filename(int cod_spec)
871 const char *fname;
873 #ifdef HAVE_RECORDING
874 /* Can choose decoder or encoder if one available */
875 int type = cod_spec & CODEC_TYPE_MASK;
876 int afmt = cod_spec & CODEC_AFMT_MASK;
878 if ((unsigned)afmt >= AFMT_NUM_CODECS)
879 type = AFMT_UNKNOWN | (type & CODEC_TYPE_MASK);
881 fname = (type == CODEC_TYPE_ENCODER) ?
882 audio_formats[afmt].codec_enc_root_fn :
883 audio_formats[afmt].codec_root_fn;
885 logf("%s: %d - %s",
886 (type == CODEC_TYPE_ENCODER) ? "Encoder" : "Decoder",
887 afmt, fname ? fname : "<unknown>");
888 #else /* !HAVE_RECORDING */
889 /* Always decoder */
890 if ((unsigned)cod_spec >= AFMT_NUM_CODECS)
891 cod_spec = AFMT_UNKNOWN;
892 fname = audio_formats[cod_spec].codec_root_fn;
893 logf("Codec: %d - %s", cod_spec, fname ? fname : "<unknown>");
894 #endif /* HAVE_RECORDING */
896 return fname;
897 } /* get_codec_filename */
899 /* --- Codec thread --- */
900 static bool codec_pcmbuf_insert_callback(
901 const void *ch1, const void *ch2, int count)
903 const char *src[2] = { ch1, ch2 };
905 while (count > 0)
907 int out_count = dsp_output_count(ci.dsp, count);
908 int inp_count;
909 char *dest;
911 /* Prevent audio from a previous track from playing */
912 if (ci.new_track || ci.stop_codec)
913 return true;
915 while ((dest = pcmbuf_request_buffer(&out_count)) == NULL)
917 cancel_cpu_boost();
918 sleep(1);
919 if (ci.seek_time || ci.new_track || ci.stop_codec)
920 return true;
923 /* Get the real input_size for output_size bytes, guarding
924 * against resampling buffer overflows. */
925 inp_count = dsp_input_count(ci.dsp, out_count);
927 if (inp_count <= 0)
928 return true;
930 /* Input size has grown, no error, just don't write more than length */
931 if (inp_count > count)
932 inp_count = count;
934 out_count = dsp_process(ci.dsp, dest, src, inp_count);
936 if (out_count <= 0)
937 return true;
939 pcmbuf_write_complete(out_count);
941 count -= inp_count;
944 return true;
945 } /* codec_pcmbuf_insert_callback */
947 static void* codec_get_buffer(size_t *size)
949 if (codec_size >= CODEC_SIZE)
950 return NULL;
951 *size = CODEC_SIZE - codec_size;
952 return &codecbuf[codec_size];
955 /* Between the codec and PCM track change, we need to keep updating the
956 "elapsed" value of the previous (to the codec, but current to the
957 user/PCM/WPS) track, so that the progressbar reaches the end.
958 During that transition, the WPS will display prevtrack_id3. */
959 static void codec_pcmbuf_position_callback(size_t size) ICODE_ATTR;
960 static void codec_pcmbuf_position_callback(size_t size)
962 /* This is called from an ISR, so be quick */
963 unsigned int time = size * 1000 / 4 / NATIVE_FREQUENCY +
964 prevtrack_id3.elapsed;
966 if (time >= prevtrack_id3.length)
968 pcmbuf_set_position_callback(NULL);
969 prevtrack_id3.elapsed = prevtrack_id3.length;
971 else
972 prevtrack_id3.elapsed = time;
975 static void codec_set_elapsed_callback(unsigned int value)
977 unsigned int latency;
978 if (ci.seek_time)
979 return;
981 #ifdef AB_REPEAT_ENABLE
982 ab_position_report(value);
983 #endif
985 latency = pcmbuf_get_latency();
986 if (value < latency)
987 curtrack_id3.elapsed = 0;
988 else if (value - latency > curtrack_id3.elapsed ||
989 value - latency < curtrack_id3.elapsed - 2)
991 curtrack_id3.elapsed = value - latency;
995 static void codec_set_offset_callback(size_t value)
997 unsigned int latency;
999 if (ci.seek_time)
1000 return;
1002 latency = pcmbuf_get_latency() * curtrack_id3.bitrate / 8;
1003 if (value < latency)
1004 curtrack_id3.offset = 0;
1005 else
1006 curtrack_id3.offset = value - latency;
1009 static void codec_advance_buffer_counters(size_t amount)
1011 bufadvance(CUR_TI->audio_hid, amount);
1012 ci.curpos += amount;
1015 /* copy up-to size bytes into ptr and return the actual size copied */
1016 static size_t codec_filebuf_callback(void *ptr, size_t size)
1018 ssize_t copy_n;
1020 if (ci.stop_codec || !playing)
1021 return 0;
1023 copy_n = bufread(CUR_TI->audio_hid, size, ptr);
1025 /* Nothing requested OR nothing left */
1026 if (copy_n == 0)
1027 return 0;
1029 /* Update read and other position pointers */
1030 codec_advance_buffer_counters(copy_n);
1032 /* Return the actual amount of data copied to the buffer */
1033 return copy_n;
1034 } /* codec_filebuf_callback */
1036 static void* codec_request_buffer_callback(size_t *realsize, size_t reqsize)
1038 size_t copy_n = reqsize;
1039 ssize_t ret;
1040 void *ptr;
1042 if (!playing)
1044 *realsize = 0;
1045 return NULL;
1048 ret = bufgetdata(CUR_TI->audio_hid, reqsize, &ptr);
1049 if (ret >= 0)
1050 copy_n = MIN((size_t)ret, reqsize);
1052 if (copy_n == 0)
1054 *realsize = 0;
1055 return NULL;
1058 *realsize = copy_n;
1060 return ptr;
1061 } /* codec_request_buffer_callback */
1063 static int get_codec_base_type(int type)
1065 switch (type) {
1066 case AFMT_MPA_L1:
1067 case AFMT_MPA_L2:
1068 case AFMT_MPA_L3:
1069 return AFMT_MPA_L3;
1072 return type;
1075 static void codec_advance_buffer_callback(size_t amount)
1077 codec_advance_buffer_counters(amount);
1078 codec_set_offset_callback(ci.curpos);
1081 static void codec_advance_buffer_loc_callback(void *ptr)
1083 size_t amount = buf_get_offset(CUR_TI->audio_hid, ptr);
1084 codec_advance_buffer_callback(amount);
1087 static void codec_seek_complete_callback(void)
1089 logf("seek_complete");
1090 if (pcm_is_paused())
1092 /* If this is not a seamless seek, clear the buffer */
1093 pcmbuf_play_stop();
1094 dsp_configure(ci.dsp, DSP_FLUSH, 0);
1096 /* If playback was not 'deliberately' paused, unpause now */
1097 if (!paused)
1098 pcmbuf_pause(false);
1100 ci.seek_time = 0;
1103 static bool codec_seek_buffer_callback(size_t newpos)
1105 logf("codec_seek_buffer_callback");
1107 int ret = bufseek(CUR_TI->audio_hid, newpos);
1108 if (ret == 0) {
1109 ci.curpos = newpos;
1110 return true;
1112 else {
1113 return false;
1117 static void codec_configure_callback(int setting, intptr_t value)
1119 switch (setting) {
1120 default:
1121 if (!dsp_configure(ci.dsp, setting, value))
1122 { logf("Illegal key:%d", setting); }
1126 static void codec_track_changed(void)
1128 LOGFQUEUE("codec > audio Q_AUDIO_TRACK_CHANGED");
1129 queue_post(&audio_queue, Q_AUDIO_TRACK_CHANGED, 0);
1132 static void codec_pcmbuf_track_changed_callback(void)
1134 pcmbuf_set_position_callback(NULL);
1135 pcmbuf_callback_queue_post(Q_AUDIO_TRACK_CHANGED, 0);
1138 static void codec_discard_codec_callback(void)
1140 if (CUR_TI->codec_hid >= 0)
1142 bufclose(CUR_TI->codec_hid);
1143 CUR_TI->codec_hid = -1;
1147 static inline void codec_gapless_track_change(void)
1149 /* callback keeps the progress bar moving while the pcmbuf empties */
1150 pcmbuf_set_position_callback(codec_pcmbuf_position_callback);
1151 /* set the pcmbuf callback for when the track really changes */
1152 pcmbuf_set_event_handler(codec_pcmbuf_track_changed_callback);
1155 static inline void codec_crossfade_track_change(void)
1157 /* Initiate automatic crossfade mode */
1158 pcmbuf_crossfade_init(false);
1159 /* Notify the wps that the track change starts now */
1160 codec_track_changed();
1163 static void codec_track_skip_done(bool was_manual)
1165 /* Manual track change (always crossfade or flush audio). */
1166 if (was_manual)
1168 pcmbuf_crossfade_init(true);
1169 LOGFQUEUE("codec > audio Q_AUDIO_TRACK_CHANGED");
1170 queue_post(&audio_queue, Q_AUDIO_TRACK_CHANGED, 0);
1172 /* Automatic track change w/crossfade, if not in "Track Skip Only" mode. */
1173 else if (pcmbuf_is_crossfade_enabled() && !pcmbuf_is_crossfade_active()
1174 && global_settings.crossfade != CROSSFADE_ENABLE_TRACKSKIP)
1176 if (global_settings.crossfade == CROSSFADE_ENABLE_SHUFFLE_AND_TRACKSKIP)
1178 if (global_settings.playlist_shuffle)
1179 /* shuffle mode is on, so crossfade: */
1180 codec_crossfade_track_change();
1181 else
1182 /* shuffle mode is off, so do a gapless track change */
1183 codec_gapless_track_change();
1185 else
1186 /* normal crossfade: */
1187 codec_crossfade_track_change();
1189 else
1190 /* normal gapless playback. */
1191 codec_gapless_track_change();
1194 static bool codec_load_next_track(void)
1196 intptr_t result = Q_CODEC_REQUEST_FAILED;
1198 prev_track_elapsed = curtrack_id3.elapsed;
1200 #ifdef AB_REPEAT_ENABLE
1201 ab_end_of_track_report();
1202 #endif
1204 logf("Request new track");
1206 if (ci.new_track == 0)
1208 ci.new_track++;
1209 automatic_skip = true;
1212 if (!ci.stop_codec)
1214 trigger_cpu_boost();
1215 LOGFQUEUE("codec >| audio Q_AUDIO_CHECK_NEW_TRACK");
1216 result = queue_send(&audio_queue, Q_AUDIO_CHECK_NEW_TRACK, 0);
1219 switch (result)
1221 case Q_CODEC_REQUEST_COMPLETE:
1222 LOGFQUEUE("codec |< Q_CODEC_REQUEST_COMPLETE");
1223 codec_track_skip_done(!automatic_skip);
1224 return true;
1226 case Q_CODEC_REQUEST_FAILED:
1227 LOGFQUEUE("codec |< Q_CODEC_REQUEST_FAILED");
1228 ci.new_track = 0;
1229 ci.stop_codec = true;
1230 codec_requested_stop = true;
1231 return false;
1233 default:
1234 LOGFQUEUE("codec |< default");
1235 ci.stop_codec = true;
1236 codec_requested_stop = true;
1237 return false;
1241 static bool codec_request_next_track_callback(void)
1243 int prev_codectype;
1245 if (ci.stop_codec || !playing)
1246 return false;
1248 prev_codectype = get_codec_base_type(curtrack_id3.codectype);
1250 if (!codec_load_next_track())
1251 return false;
1253 /* Seek to the beginning of the new track because if the struct
1254 mp3entry was buffered, "elapsed" might not be zero (if the track has
1255 been played already but not unbuffered) */
1256 codec_seek_buffer_callback(curtrack_id3.first_frame_offset);
1258 /* Check if the next codec is the same file. */
1259 if (prev_codectype == get_codec_base_type(curtrack_id3.codectype))
1261 logf("New track loaded");
1262 codec_discard_codec_callback();
1263 return true;
1265 else
1267 logf("New codec:%d/%d", curtrack_id3.codectype, prev_codectype);
1268 return false;
1272 static void codec_thread(void)
1274 struct queue_event ev;
1275 int status;
1277 while (1) {
1278 status = 0;
1280 if (!pcmbuf_is_crossfade_active()) {
1281 cancel_cpu_boost();
1284 queue_wait(&codec_queue, &ev);
1285 codec_requested_stop = false;
1287 switch (ev.id) {
1288 case Q_CODEC_LOAD_DISK:
1289 LOGFQUEUE("codec < Q_CODEC_LOAD_DISK");
1290 queue_reply(&codec_queue, 1);
1291 audio_codec_loaded = true;
1292 ci.stop_codec = false;
1293 status = codec_load_file((const char *)ev.data, &ci);
1294 break;
1296 case Q_CODEC_LOAD:
1297 LOGFQUEUE("codec < Q_CODEC_LOAD");
1298 if (CUR_TI->codec_hid < 0) {
1299 logf("Codec slot is empty!");
1300 /* Wait for the pcm buffer to go empty */
1301 while (pcm_is_playing())
1302 yield();
1303 /* This must be set to prevent an infinite loop */
1304 ci.stop_codec = true;
1305 LOGFQUEUE("codec > codec Q_AUDIO_PLAY");
1306 queue_post(&codec_queue, Q_AUDIO_PLAY, 0);
1307 break;
1310 audio_codec_loaded = true;
1311 ci.stop_codec = false;
1312 status = codec_load_buf(CUR_TI->codec_hid, &ci);
1313 break;
1315 case Q_CODEC_DO_CALLBACK:
1316 LOGFQUEUE("codec < Q_CODEC_DO_CALLBACK");
1317 queue_reply(&codec_queue, 1);
1318 if ((void*)ev.data != NULL)
1320 cpucache_invalidate();
1321 ((void (*)(void))ev.data)();
1322 cpucache_flush();
1324 break;
1326 #ifdef AUDIO_HAVE_RECORDING
1327 case Q_ENCODER_LOAD_DISK:
1328 LOGFQUEUE("codec < Q_ENCODER_LOAD_DISK");
1329 audio_codec_loaded = false; /* Not audio codec! */
1330 logf("loading encoder");
1331 ci.stop_encoder = false;
1332 status = codec_load_file((const char *)ev.data, &ci);
1333 logf("encoder stopped");
1334 break;
1335 #endif /* AUDIO_HAVE_RECORDING */
1337 default:
1338 LOGFQUEUE("codec < default");
1341 if (audio_codec_loaded)
1343 if (ci.stop_codec)
1345 status = CODEC_OK;
1346 if (!playing)
1347 pcmbuf_play_stop();
1350 audio_codec_loaded = false;
1353 switch (ev.id) {
1354 case Q_CODEC_LOAD_DISK:
1355 case Q_CODEC_LOAD:
1356 LOGFQUEUE("codec < Q_CODEC_LOAD");
1357 if (playing)
1359 if (ci.new_track || status != CODEC_OK)
1361 if (!ci.new_track)
1363 logf("Codec failure");
1364 splash(HZ*2, "Codec failure");
1367 if (!codec_load_next_track())
1369 LOGFQUEUE("codec > audio Q_AUDIO_STOP");
1370 /* End of playlist */
1371 queue_post(&audio_queue, Q_AUDIO_STOP, 0);
1372 break;
1375 else
1377 logf("Codec finished");
1378 if (ci.stop_codec)
1380 /* Wait for the audio to stop playing before
1381 * triggering the WPS exit */
1382 while(pcm_is_playing())
1384 curtrack_id3.elapsed =
1385 curtrack_id3.length - pcmbuf_get_latency();
1386 sleep(1);
1389 if (codec_requested_stop)
1391 LOGFQUEUE("codec > audio Q_AUDIO_STOP");
1392 queue_post(&audio_queue, Q_AUDIO_STOP, 0);
1394 break;
1398 if (CUR_TI->codec_hid >= 0)
1400 LOGFQUEUE("codec > codec Q_CODEC_LOAD");
1401 queue_post(&codec_queue, Q_CODEC_LOAD, 0);
1403 else
1405 const char *codec_fn =
1406 get_codec_filename(curtrack_id3.codectype);
1407 if (codec_fn)
1409 LOGFQUEUE("codec > codec Q_CODEC_LOAD_DISK");
1410 queue_post(&codec_queue, Q_CODEC_LOAD_DISK,
1411 (intptr_t)codec_fn);
1415 break;
1417 #ifdef AUDIO_HAVE_RECORDING
1418 case Q_ENCODER_LOAD_DISK:
1419 LOGFQUEUE("codec < Q_ENCODER_LOAD_DISK");
1421 if (status == CODEC_OK)
1422 break;
1424 logf("Encoder failure");
1425 splash(HZ*2, "Encoder failure");
1427 if (ci.enc_codec_loaded < 0)
1428 break;
1430 logf("Encoder failed to load");
1431 ci.enc_codec_loaded = -1;
1432 break;
1433 #endif /* AUDIO_HAVE_RECORDING */
1435 default:
1436 LOGFQUEUE("codec < default");
1438 } /* end switch */
1442 /* Borrow the codec thread and return the ID */
1443 void codec_thread_do_callback(void (*fn)(void), unsigned int *id)
1445 /* Set id before telling thread to call something; it may be
1446 * needed before this function returns. */
1447 if (id != NULL)
1448 *id = codec_thread_id;
1450 /* Codec thread will signal just before entering callback */
1451 LOGFQUEUE("codec >| Q_CODEC_DO_CALLBACK");
1452 queue_send(&codec_queue, Q_CODEC_DO_CALLBACK, (intptr_t)fn);
1455 /* --- Buffering callbacks --- */
1457 static void buffering_low_buffer_callback(void *data)
1459 (void)data;
1460 logf("low buffer callback");
1462 if (filling == STATE_FULL || filling == STATE_END_OF_PLAYLIST) {
1463 /* force a refill */
1464 LOGFQUEUE("buffering > audio Q_AUDIO_FILL_BUFFER");
1465 queue_post(&audio_queue, Q_AUDIO_FILL_BUFFER, 0);
1469 static void buffering_handle_rebuffer_callback(void *data)
1471 (void)data;
1472 LOGFQUEUE("audio >| audio Q_AUDIO_FLUSH");
1473 queue_post(&audio_queue, Q_AUDIO_FLUSH, 0);
1476 static void buffering_handle_finished_callback(int *data)
1478 logf("handle %d finished buffering", *data);
1480 if (*data == tracks[track_widx].id3_hid)
1482 /* The metadata handle for the last loaded track has been buffered.
1483 We can ask the audio thread to load the rest of the track's data. */
1484 LOGFQUEUE("audio >| audio Q_AUDIO_FINISH_LOAD");
1485 queue_post(&audio_queue, Q_AUDIO_FINISH_LOAD, 0);
1487 else
1489 /* This is most likely an audio handle, so we strip the useless
1490 trailing tags that are left. */
1491 strip_tags(*data);
1493 if (*data == tracks[track_widx-1].audio_hid
1494 && filling == STATE_END_OF_PLAYLIST)
1496 /* This was the last track in the playlist.
1497 We now have all the data we need. */
1498 logf("last track finished buffering");
1499 filling = STATE_FINISHED;
1505 /* --- Audio thread --- */
1507 static bool audio_have_tracks(void)
1509 return (audio_track_count() != 0);
1512 static int audio_free_track_count(void)
1514 /* Used tracks + free tracks adds up to MAX_TRACK - 1 */
1515 return MAX_TRACK - 1 - audio_track_count();
1518 int audio_track_count(void)
1520 /* Calculate difference from track_ridx to track_widx
1521 * taking into account a possible wrap-around. */
1522 return (MAX_TRACK + track_widx - track_ridx) & MAX_TRACK_MASK;
1525 long audio_filebufused(void)
1527 return (long) buf_used();
1530 /* Update track info after successful a codec track change */
1531 static void audio_update_trackinfo(void)
1533 /* Load the curent track's metadata into curtrack_id3 */
1534 if (CUR_TI->id3_hid >= 0)
1535 copy_mp3entry(&curtrack_id3, bufgetid3(CUR_TI->id3_hid));
1537 /* Reset current position */
1538 curtrack_id3.elapsed = 0;
1539 curtrack_id3.offset = 0;
1541 /* Update the codec API */
1542 ci.filesize = CUR_TI->filesize;
1543 ci.id3 = &curtrack_id3;
1544 ci.curpos = 0;
1545 ci.taginfo_ready = &CUR_TI->taginfo_ready;
1548 /* Clear tracks between write and read, non inclusive */
1549 static void audio_clear_track_entries(void)
1551 int cur_idx = track_widx;
1553 logf("Clearing tracks:%d/%d", track_ridx, track_widx);
1555 /* Loop over all tracks from write-to-read */
1556 while (1)
1558 cur_idx = (cur_idx + 1) & MAX_TRACK_MASK;
1560 if (cur_idx == track_ridx)
1561 break;
1563 clear_track_info(&tracks[cur_idx]);
1567 /* Clear all tracks */
1568 static bool audio_release_tracks(void)
1570 int i, cur_idx;
1572 logf("releasing all tracks");
1574 for(i = 0; i < MAX_TRACK; i++)
1576 cur_idx = (track_ridx + i) & MAX_TRACK_MASK;
1577 if (!clear_track_info(&tracks[cur_idx]))
1578 return false;
1581 return true;
1584 static bool audio_loadcodec(bool start_play)
1586 int prev_track;
1587 char codec_path[MAX_PATH]; /* Full path to codec */
1588 const struct mp3entry *id3, *prev_id3;
1590 if (tracks[track_widx].id3_hid < 0) {
1591 return false;
1594 id3 = bufgetid3(tracks[track_widx].id3_hid);
1595 if (!id3)
1596 return false;
1598 const char *codec_fn = get_codec_filename(id3->codectype);
1599 if (codec_fn == NULL)
1600 return false;
1602 tracks[track_widx].codec_hid = -1;
1604 if (start_play)
1606 /* Load the codec directly from disk and save some memory. */
1607 track_ridx = track_widx;
1608 ci.filesize = CUR_TI->filesize;
1609 ci.id3 = &curtrack_id3;
1610 ci.taginfo_ready = &CUR_TI->taginfo_ready;
1611 ci.curpos = 0;
1612 LOGFQUEUE("codec > codec Q_CODEC_LOAD_DISK");
1613 queue_post(&codec_queue, Q_CODEC_LOAD_DISK, (intptr_t)codec_fn);
1614 return true;
1616 else
1618 /* If we already have another track than this one buffered */
1619 if (track_widx != track_ridx)
1621 prev_track = (track_widx - 1) & MAX_TRACK_MASK;
1623 id3 = bufgetid3(tracks[track_widx].id3_hid);
1624 prev_id3 = bufgetid3(tracks[prev_track].id3_hid);
1626 /* If the previous codec is the same as this one, there is no need
1627 * to put another copy of it on the file buffer */
1628 if (id3 && prev_id3 &&
1629 get_codec_base_type(id3->codectype) ==
1630 get_codec_base_type(prev_id3->codectype)
1631 && audio_codec_loaded)
1633 logf("Reusing prev. codec");
1634 return true;
1639 codec_get_full_path(codec_path, codec_fn);
1641 tracks[track_widx].codec_hid = bufopen(codec_path, 0, TYPE_CODEC);
1642 if (tracks[track_widx].codec_hid < 0)
1643 return false;
1645 logf("Loaded codec");
1647 return true;
1650 /* Load metadata for the next track (with bufopen). The rest of the track
1651 loading will be handled by audio_finish_load_track once the metadata has been
1652 actually loaded by the buffering thread. */
1653 static bool audio_load_track(size_t offset, bool start_play)
1655 const char *trackname;
1656 int fd = -1;
1658 if (track_load_started) {
1659 /* There is already a track load in progress, so track_widx hasn't been
1660 incremented yet. Loading another track would overwrite the one that
1661 hasn't finished loading. */
1662 logf("audio_load_track(): a track load is already in progress");
1663 return false;
1666 start_play_g = start_play; /* will be read by audio_finish_load_track */
1668 /* Stop buffer filling if there is no free track entries.
1669 Don't fill up the last track entry (we wan't to store next track
1670 metadata there). */
1671 if (!audio_free_track_count())
1673 logf("No free tracks");
1674 return false;
1677 last_peek_offset++;
1678 tracks[track_widx].taginfo_ready = false;
1680 logf("Buffering track:%d/%d", track_widx, track_ridx);
1681 /* Get track name from current playlist read position. */
1682 while ((trackname = playlist_peek(last_peek_offset)) != NULL)
1684 /* Handle broken playlists. */
1685 fd = open(trackname, O_RDONLY);
1686 if (fd < 0)
1688 logf("Open failed");
1689 /* Skip invalid entry from playlist. */
1690 playlist_skip_entry(NULL, last_peek_offset);
1692 else
1693 break;
1696 if (!trackname)
1698 logf("End-of-playlist");
1699 memset(&lasttrack_id3, 0, sizeof(struct mp3entry));
1700 filling = STATE_END_OF_PLAYLIST;
1702 if (curtrack_id3.length == 0 && curtrack_id3.filesize == 0)
1704 /* Stop playback if no valid track was found. */
1705 audio_stop_playback();
1708 return false;
1711 tracks[track_widx].filesize = filesize(fd);
1713 if (offset > tracks[track_widx].filesize)
1714 offset = 0;
1716 /* Set default values */
1717 if (start_play)
1719 buf_set_watermark(filebuflen/2);
1720 dsp_configure(ci.dsp, DSP_RESET, 0);
1721 track_changed = true;
1722 playlist_update_resume_info(audio_current_track());
1725 /* Get track metadata if we don't already have it. */
1726 if (tracks[track_widx].id3_hid < 0)
1728 tracks[track_widx].id3_hid = bufopen(trackname, 0, TYPE_ID3);
1730 if (tracks[track_widx].id3_hid < 0)
1732 /* Buffer is full. */
1733 get_metadata(&lasttrack_id3, fd, trackname);
1734 last_peek_offset--;
1735 close(fd);
1736 logf("buffer is full for now");
1737 filling = STATE_FULL;
1738 return false;
1741 if (track_widx == track_ridx)
1743 /* TODO: Superfluos buffering call? */
1744 buf_request_buffer_handle(tracks[track_widx].id3_hid);
1745 copy_mp3entry(&curtrack_id3, bufgetid3(tracks[track_widx].id3_hid));
1746 curtrack_id3.offset = offset;
1749 if (start_play)
1751 track_changed = true;
1752 playlist_update_resume_info(audio_current_track());
1756 close(fd);
1757 track_load_started = true; /* Remember that we've started loading a track */
1758 return true;
1761 /* Second part of the track loading: We now have the metadata available, so we
1762 can load the codec, the album art and finally the audio data.
1763 This is called on the audio thread after the buffering thread calls the
1764 buffering_handle_finished_callback callback. */
1765 static void audio_finish_load_track(void)
1767 size_t file_offset = 0;
1768 size_t offset = 0;
1769 bool start_play = start_play_g;
1771 track_load_started = false;
1773 if (tracks[track_widx].id3_hid < 0) {
1774 logf("no metatdata");
1775 return;
1778 struct mp3entry *track_id3;
1780 if (track_widx == track_ridx)
1781 track_id3 = &curtrack_id3;
1782 else
1783 track_id3 = bufgetid3(tracks[track_widx].id3_hid);
1785 if (track_id3->length == 0 && track_id3->filesize == 0)
1787 logf("audio_finish_load_track: invalid metadata");
1789 /* Invalid metadata */
1790 bufclose(tracks[track_widx].id3_hid);
1791 tracks[track_widx].id3_hid = -1;
1793 /* Skip invalid entry from playlist. */
1794 playlist_skip_entry(NULL, last_peek_offset--);
1796 /* load next track */
1797 LOGFQUEUE("audio > audio Q_AUDIO_FILL_BUFFER %d", (int)start_play);
1798 queue_post(&audio_queue, Q_AUDIO_FILL_BUFFER, start_play);
1800 return;
1803 #ifdef HAVE_ALBUMART
1804 if (tracks[track_widx].aa_hid < 0 && gui_sync_wps_uses_albumart())
1806 char aa_path[MAX_PATH];
1807 if (find_albumart(track_id3, aa_path, sizeof(aa_path)))
1808 tracks[track_widx].aa_hid = bufopen(aa_path, 0, TYPE_BITMAP);
1810 #endif
1812 /* Load the codec. */
1813 if (!audio_loadcodec(start_play))
1815 if (tracks[track_widx].codec_hid == ERR_BUFFER_FULL)
1817 /* No space for codec on buffer, not an error */
1818 return;
1821 /* This is an error condition, either no codec was found, or reading
1822 * the codec file failed part way through, either way, skip the track */
1823 /* FIXME: We should not use splashf from audio thread! */
1824 splashf(HZ*2, "No codec for: %s", track_id3->path);
1825 /* Skip invalid entry from playlist. */
1826 playlist_skip_entry(NULL, last_peek_offset);
1827 return;
1830 track_id3->elapsed = 0;
1831 offset = track_id3->offset;
1833 enum data_type type = TYPE_PACKET_AUDIO;
1835 switch (track_id3->codectype) {
1836 case AFMT_MPA_L1:
1837 case AFMT_MPA_L2:
1838 case AFMT_MPA_L3:
1839 if (offset > 0) {
1840 file_offset = offset;
1841 track_id3->offset = offset;
1843 break;
1845 case AFMT_WAVPACK:
1846 if (offset > 0) {
1847 file_offset = offset;
1848 track_id3->offset = offset;
1849 track_id3->elapsed = track_id3->length / 2;
1851 break;
1853 case AFMT_OGG_VORBIS:
1854 case AFMT_SPEEX:
1855 case AFMT_FLAC:
1856 case AFMT_PCM_WAV:
1857 case AFMT_A52:
1858 case AFMT_AAC:
1859 case AFMT_MPC:
1860 case AFMT_APE:
1861 case AFMT_WMA:
1862 if (offset > 0)
1863 track_id3->offset = offset;
1864 break;
1866 case AFMT_NSF:
1867 case AFMT_SPC:
1868 case AFMT_SID:
1869 logf("Loading atomic %d",track_id3->codectype);
1870 type = TYPE_ATOMIC_AUDIO;
1871 break;
1874 logf("alt:%s", track_id3->path);
1876 if (file_offset > AUDIO_REBUFFER_GUESS_SIZE)
1877 file_offset -= AUDIO_REBUFFER_GUESS_SIZE;
1878 else if (track_id3->first_frame_offset)
1879 file_offset = track_id3->first_frame_offset;
1880 else
1881 file_offset = 0;
1883 tracks[track_widx].audio_hid = bufopen(track_id3->path, file_offset, type);
1885 if (tracks[track_widx].audio_hid < 0)
1886 return;
1888 /* All required data is now available for the codec. */
1889 tracks[track_widx].taginfo_ready = true;
1891 if (start_play)
1893 ci.curpos=file_offset;
1894 buf_request_buffer_handle(tracks[track_widx].audio_hid);
1897 track_widx = (track_widx + 1) & MAX_TRACK_MASK;
1899 send_event(PLAYBACK_EVENT_TRACK_BUFFER, track_id3);
1901 /* load next track */
1902 LOGFQUEUE("audio > audio Q_AUDIO_FILL_BUFFER");
1903 queue_post(&audio_queue, Q_AUDIO_FILL_BUFFER, 0);
1905 return;
1908 static void audio_fill_file_buffer(bool start_play, size_t offset)
1910 bool had_next_track = audio_next_track() != NULL;
1912 filling = STATE_FILLING;
1913 trigger_cpu_boost();
1915 /* No need to rebuffer if there are track skips pending. */
1916 if (ci.new_track != 0)
1917 return;
1919 /* Must reset the buffer before use if trashed or voice only - voice
1920 file size shouldn't have changed so we can go straight from
1921 AUDIOBUF_STATE_VOICED_ONLY to AUDIOBUF_STATE_INITIALIZED */
1922 if (buffer_state != AUDIOBUF_STATE_INITIALIZED)
1923 audio_reset_buffer();
1925 logf("Starting buffer fill");
1927 if (!start_play)
1928 audio_clear_track_entries();
1930 /* Save the current resume position once. */
1931 playlist_update_resume_info(audio_current_track());
1933 audio_load_track(offset, start_play);
1935 if (!had_next_track && audio_next_track())
1936 track_changed = true;
1939 static void audio_rebuffer(void)
1941 logf("Forcing rebuffer");
1943 clear_track_info(CUR_TI);
1945 /* Reset track pointers */
1946 track_widx = track_ridx;
1947 audio_clear_track_entries();
1949 /* Reset a possibly interrupted track load */
1950 track_load_started = false;
1952 /* Fill the buffer */
1953 last_peek_offset = -1;
1954 ci.curpos = 0;
1956 if (!CUR_TI->taginfo_ready)
1957 memset(&curtrack_id3, 0, sizeof(struct mp3entry));
1959 audio_fill_file_buffer(false, 0);
1962 /* Called on request from the codec to get a new track. This is the codec part
1963 of the track transition. */
1964 static int audio_check_new_track(void)
1966 int track_count = audio_track_count();
1967 int old_track_ridx = track_ridx;
1968 int i, idx;
1969 bool forward;
1971 /* Now it's good time to send track finish events. */
1972 send_event(PLAYBACK_EVENT_TRACK_FINISH, &curtrack_id3);
1973 if (dir_skip)
1975 dir_skip = false;
1976 /* regardless of the return value we need to rebuffer.
1977 if it fails the old playlist will resume, else the
1978 next dir will start playing */
1979 playlist_next_dir(ci.new_track);
1980 ci.new_track = 0;
1981 audio_rebuffer();
1982 goto skip_done;
1985 if (new_playlist)
1986 ci.new_track = 0;
1988 /* If the playlist isn't that big */
1989 if (automatic_skip)
1991 while (!playlist_check(ci.new_track))
1993 if (ci.new_track >= 0)
1995 LOGFQUEUE("audio >|= codec Q_CODEC_REQUEST_FAILED");
1996 return Q_CODEC_REQUEST_FAILED;
1998 ci.new_track++;
2002 /* Update the playlist */
2003 last_peek_offset -= ci.new_track;
2005 if (playlist_next(ci.new_track) < 0)
2007 LOGFQUEUE("audio >|= codec Q_CODEC_REQUEST_FAILED");
2008 return Q_CODEC_REQUEST_FAILED;
2011 if (new_playlist)
2013 ci.new_track = 1;
2014 new_playlist = false;
2017 /* Save the track metadata to allow the WPS to display it
2018 while PCM finishes playing that track */
2019 copy_mp3entry(&prevtrack_id3, &curtrack_id3);
2021 /* Update the main buffer copy of the track metadata with the one
2022 the codec has been using (for the unbuffer callbacks) */
2023 if (CUR_TI->id3_hid >= 0)
2024 copy_mp3entry(bufgetid3(CUR_TI->id3_hid), &curtrack_id3);
2026 /* Save a pointer to the old track to allow later clearing */
2027 prev_ti = CUR_TI;
2029 for (i = 0; i < ci.new_track; i++)
2031 idx = (track_ridx + i) & MAX_TRACK_MASK;
2032 struct mp3entry *id3 = bufgetid3(tracks[idx].id3_hid);
2033 ssize_t offset = buf_handle_offset(tracks[idx].audio_hid);
2034 if (!id3 || offset < 0 || (unsigned)offset > id3->first_frame_offset)
2036 /* We don't have all the audio data for that track, so clear it,
2037 but keep the metadata. */
2038 if (tracks[idx].audio_hid >= 0 && bufclose(tracks[idx].audio_hid))
2040 tracks[idx].audio_hid = -1;
2041 tracks[idx].filesize = 0;
2046 /* Move to the new track */
2047 track_ridx = (track_ridx + ci.new_track) & MAX_TRACK_MASK;
2049 buf_set_base_handle(CUR_TI->audio_hid);
2051 if (automatic_skip)
2053 wps_offset = -ci.new_track;
2054 track_changed = true;
2057 /* If it is not safe to even skip this many track entries */
2058 if (ci.new_track >= track_count || ci.new_track <= track_count - MAX_TRACK)
2060 ci.new_track = 0;
2061 audio_rebuffer();
2062 goto skip_done;
2065 forward = ci.new_track > 0;
2066 ci.new_track = 0;
2068 /* If the target track is clearly not in memory */
2069 if (CUR_TI->filesize == 0 || !CUR_TI->taginfo_ready)
2071 audio_rebuffer();
2072 goto skip_done;
2075 /* When skipping backwards, it is possible that we've found a track that's
2076 * buffered, but which is around the track-wrap and therefore not the track
2077 * we are looking for */
2078 if (!forward)
2080 int cur_idx = track_ridx;
2081 bool taginfo_ready = true;
2082 /* We've wrapped the buffer backwards if new > old */
2083 bool wrap = track_ridx > old_track_ridx;
2085 while (1)
2087 cur_idx = (cur_idx + 1) & MAX_TRACK_MASK;
2089 /* if we've advanced past the wrap when cur_idx is zeroed */
2090 if (!cur_idx)
2091 wrap = false;
2093 /* if we aren't still on the wrap and we've caught the old track */
2094 if (!(wrap || cur_idx < old_track_ridx))
2095 break;
2097 /* If we hit a track in between without valid tag info, bail */
2098 if (!tracks[cur_idx].taginfo_ready)
2100 taginfo_ready = false;
2101 break;
2104 if (!taginfo_ready)
2106 audio_rebuffer();
2110 skip_done:
2111 audio_update_trackinfo();
2112 LOGFQUEUE("audio >|= codec Q_CODEC_REQUEST_COMPLETE");
2113 return Q_CODEC_REQUEST_COMPLETE;
2116 unsigned long audio_prev_elapsed(void)
2118 return prev_track_elapsed;
2121 static void audio_stop_codec_flush(void)
2123 ci.stop_codec = true;
2124 pcmbuf_pause(true);
2126 while (audio_codec_loaded)
2127 yield();
2129 /* If the audio codec is not loaded any more, and the audio is still
2130 * playing, it is now and _only_ now safe to call this function from the
2131 * audio thread */
2132 if (pcm_is_playing())
2134 pcmbuf_play_stop();
2135 pcmbuf_queue_clear();
2137 pcmbuf_pause(paused);
2140 static void audio_stop_playback(void)
2142 /* If we were playing, save resume information */
2143 if (playing)
2145 struct mp3entry *id3 = NULL;
2147 if (!ci.stop_codec)
2149 /* Set this early, the outside code yields and may allow the codec
2150 to try to wait for a reply on a buffer wait */
2151 ci.stop_codec = true;
2152 id3 = audio_current_track();
2155 /* Save the current playing spot, or NULL if the playlist has ended */
2156 playlist_update_resume_info(id3);
2158 /* TODO: Create auto bookmark too? */
2160 prev_track_elapsed = curtrack_id3.elapsed;
2162 remove_event(BUFFER_EVENT_BUFFER_LOW, buffering_low_buffer_callback);
2165 audio_stop_codec_flush();
2166 paused = false;
2167 playing = false;
2168 track_load_started = false;
2170 filling = STATE_IDLE;
2172 /* Mark all entries null. */
2173 audio_clear_track_entries();
2175 /* Close all tracks */
2176 audio_release_tracks();
2178 memset(&curtrack_id3, 0, sizeof(struct mp3entry));
2181 static void audio_play_start(size_t offset)
2183 int i;
2185 #if INPUT_SRC_CAPS != 0
2186 audio_set_input_source(AUDIO_SRC_PLAYBACK, SRCF_PLAYBACK);
2187 audio_set_output_source(AUDIO_SRC_PLAYBACK);
2188 #endif
2190 /* Wait for any previously playing audio to flush - TODO: Not necessary? */
2191 paused = false;
2192 audio_stop_codec_flush();
2194 track_changed = true;
2196 playing = true;
2197 track_load_started = false;
2199 ci.new_track = 0;
2200 ci.seek_time = 0;
2201 wps_offset = 0;
2203 sound_set_volume(global_settings.volume);
2204 track_widx = track_ridx = 0;
2206 /* Clear all track entries. */
2207 for (i = 0; i < MAX_TRACK; i++) {
2208 clear_track_info(&tracks[i]);
2211 last_peek_offset = -1;
2213 /* Officially playing */
2214 queue_reply(&audio_queue, 1);
2216 audio_fill_file_buffer(true, offset);
2218 add_event(BUFFER_EVENT_BUFFER_LOW, false, buffering_low_buffer_callback);
2220 LOGFQUEUE("audio > audio Q_AUDIO_TRACK_CHANGED");
2221 queue_post(&audio_queue, Q_AUDIO_TRACK_CHANGED, 0);
2225 /* Invalidates all but currently playing track. */
2226 static void audio_invalidate_tracks(void)
2228 if (audio_have_tracks())
2230 last_peek_offset = 0;
2231 track_widx = track_ridx;
2233 /* Mark all other entries null (also buffered wrong metadata). */
2234 audio_clear_track_entries();
2236 track_widx = (track_widx + 1) & MAX_TRACK_MASK;
2238 audio_fill_file_buffer(false, 0);
2242 static void audio_new_playlist(void)
2244 /* Prepare to start a new fill from the beginning of the playlist */
2245 last_peek_offset = -1;
2246 if (audio_have_tracks())
2248 if (paused)
2249 skipped_during_pause = true;
2250 track_widx = track_ridx;
2251 audio_clear_track_entries();
2253 track_widx = (track_widx + 1) & MAX_TRACK_MASK;
2255 /* Mark the current track as invalid to prevent skipping back to it */
2256 CUR_TI->taginfo_ready = false;
2259 /* Signal the codec to initiate a track change forward */
2260 new_playlist = true;
2261 ci.new_track = 1;
2263 /* Officially playing */
2264 queue_reply(&audio_queue, 1);
2266 audio_fill_file_buffer(false, 0);
2269 /* Called on manual track skip */
2270 static void audio_initiate_track_change(long direction)
2272 logf("audio_initiate_track_change(%ld)", direction);
2274 ci.new_track += direction;
2275 wps_offset -= direction;
2276 if (paused)
2277 skipped_during_pause = true;
2280 /* Called on manual dir skip */
2281 static void audio_initiate_dir_change(long direction)
2283 dir_skip = true;
2284 ci.new_track = direction;
2285 if (paused)
2286 skipped_during_pause = true;
2289 /* Called when PCM track change is complete */
2290 static void audio_finalise_track_change(void)
2292 logf("audio_finalise_track_change");
2294 if (automatic_skip)
2296 wps_offset = 0;
2297 automatic_skip = false;
2299 /* Invalidate prevtrack_id3 */
2300 prevtrack_id3.path[0] = 0;
2302 if (prev_ti && prev_ti->audio_hid < 0)
2304 /* No audio left so we clear all the track info. */
2305 clear_track_info(prev_ti);
2308 if (prev_ti && prev_ti->id3_hid >= 0)
2310 /* Reset the elapsed time to force the progressbar to be empty if
2311 the user skips back to this track */
2312 bufgetid3(prev_ti->id3_hid)->elapsed = 0;
2316 send_event(PLAYBACK_EVENT_TRACK_CHANGE, &curtrack_id3);
2318 track_changed = true;
2319 playlist_update_resume_info(audio_current_track());
2323 * Layout audio buffer as follows - iram buffer depends on target:
2324 * [|SWAP:iram][|TALK]|FILE|GUARD|PCM|[SWAP:dram[|iram]|]
2326 static void audio_reset_buffer(void)
2328 /* see audio_get_recording_buffer if this is modified */
2329 logf("audio_reset_buffer");
2331 /* If the setup of anything allocated before the file buffer is
2332 changed, do check the adjustments after the buffer_alloc call
2333 as it will likely be affected and need sliding over */
2335 /* Initially set up file buffer as all space available */
2336 malloc_buf = audiobuf + talk_get_bufsize();
2337 /* Align the malloc buf to line size. Especially important to cf
2338 targets that do line reads/writes. */
2339 malloc_buf = (unsigned char *)(((uintptr_t)malloc_buf + 15) & ~15);
2340 filebuf = malloc_buf; /* filebuf line align implied */
2341 filebuflen = audiobufend - filebuf;
2343 filebuflen &= ~15;
2345 /* Subtract whatever the pcm buffer says it used plus the guard buffer */
2346 const size_t pcmbuf_size = pcmbuf_init(filebuf + filebuflen) +GUARD_BUFSIZE;
2348 #ifdef DEBUG
2349 if(pcmbuf_size > filebuflen)
2350 panicf("Not enough memory for pcmbuf_init() : %d > %d",
2351 (int)pcmbuf_size, (int)filebuflen);
2352 #endif
2354 filebuflen -= pcmbuf_size;
2356 /* Make sure filebuflen is a longword multiple after adjustment - filebuf
2357 will already be line aligned */
2358 filebuflen &= ~3;
2360 buffering_reset(filebuf, filebuflen);
2362 /* Clear any references to the file buffer */
2363 buffer_state = AUDIOBUF_STATE_INITIALIZED;
2365 #if defined(ROCKBOX_HAS_LOGF) && defined(LOGF_ENABLE)
2366 /* Make sure everything adds up - yes, some info is a bit redundant but
2367 aids viewing and the sumation of certain variables should add up to
2368 the location of others. */
2370 size_t pcmbufsize;
2371 const unsigned char *pcmbuf = pcmbuf_get_meminfo(&pcmbufsize);
2372 logf("mabuf: %08X", (unsigned)malloc_buf);
2373 logf("fbuf: %08X", (unsigned)filebuf);
2374 logf("fbufe: %08X", (unsigned)(filebuf + filebuflen));
2375 logf("gbuf: %08X", (unsigned)(filebuf + filebuflen));
2376 logf("gbufe: %08X", (unsigned)(filebuf + filebuflen + GUARD_BUFSIZE));
2377 logf("pcmb: %08X", (unsigned)pcmbuf);
2378 logf("pcmbe: %08X", (unsigned)(pcmbuf + pcmbufsize));
2380 #endif
2383 static void audio_thread(void)
2385 struct queue_event ev;
2387 pcm_postinit();
2389 audio_thread_ready = true;
2391 while (1)
2393 if (filling != STATE_FILLING) {
2394 cancel_cpu_boost();
2397 if (!pcmbuf_queue_scan(&ev))
2398 queue_wait_w_tmo(&audio_queue, &ev, HZ/2);
2400 switch (ev.id) {
2402 case Q_AUDIO_FILL_BUFFER:
2403 LOGFQUEUE("audio < Q_AUDIO_FILL_BUFFER %d", (int)ev.data);
2404 audio_fill_file_buffer((bool)ev.data, 0);
2405 set_filebuf_watermark();
2406 break;
2408 case Q_AUDIO_FINISH_LOAD:
2409 LOGFQUEUE("audio < Q_AUDIO_FINISH_LOAD");
2410 audio_finish_load_track();
2411 break;
2413 case Q_AUDIO_PLAY:
2414 LOGFQUEUE("audio < Q_AUDIO_PLAY");
2415 if (playing && ev.data <= 0)
2416 audio_new_playlist();
2417 else
2419 audio_stop_playback();
2420 audio_play_start((size_t)ev.data);
2422 break;
2424 case Q_AUDIO_STOP:
2425 LOGFQUEUE("audio < Q_AUDIO_STOP");
2426 if (playing)
2427 audio_stop_playback();
2428 if (ev.data != 0)
2429 queue_clear(&audio_queue);
2430 break;
2432 case Q_AUDIO_PAUSE:
2433 LOGFQUEUE("audio < Q_AUDIO_PAUSE");
2434 if (!(bool) ev.data && skipped_during_pause && !pcmbuf_is_crossfade_active())
2435 pcmbuf_play_stop(); /* Flush old track on resume after skip */
2436 skipped_during_pause = false;
2437 if (!playing)
2438 break;
2439 pcmbuf_pause((bool)ev.data);
2440 paused = (bool)ev.data;
2441 break;
2443 case Q_AUDIO_SKIP:
2444 LOGFQUEUE("audio < Q_AUDIO_SKIP");
2445 audio_initiate_track_change((long)ev.data);
2446 break;
2448 case Q_AUDIO_PRE_FF_REWIND:
2449 LOGFQUEUE("audio < Q_AUDIO_PRE_FF_REWIND");
2450 if (!playing)
2451 break;
2452 pcmbuf_pause(true);
2453 break;
2455 case Q_AUDIO_FF_REWIND:
2456 LOGFQUEUE("audio < Q_AUDIO_FF_REWIND");
2457 if (!playing)
2458 break;
2459 if (automatic_skip)
2461 /* An automatic track skip is in progress. Finalize it,
2462 then go back to the previous track */
2463 audio_finalise_track_change();
2464 ci.new_track = -1;
2466 ci.seek_time = (long)ev.data+1;
2467 break;
2469 case Q_AUDIO_CHECK_NEW_TRACK:
2470 LOGFQUEUE("audio < Q_AUDIO_CHECK_NEW_TRACK");
2471 queue_reply(&audio_queue, audio_check_new_track());
2472 break;
2474 case Q_AUDIO_DIR_SKIP:
2475 LOGFQUEUE("audio < Q_AUDIO_DIR_SKIP");
2476 audio_initiate_dir_change(ev.data);
2477 break;
2479 case Q_AUDIO_FLUSH:
2480 LOGFQUEUE("audio < Q_AUDIO_FLUSH");
2481 audio_invalidate_tracks();
2482 break;
2484 case Q_AUDIO_TRACK_CHANGED:
2485 /* PCM track change done */
2486 LOGFQUEUE("audio < Q_AUDIO_TRACK_CHANGED");
2487 audio_finalise_track_change();
2488 break;
2490 #ifndef SIMULATOR
2491 case SYS_USB_CONNECTED:
2492 LOGFQUEUE("audio < SYS_USB_CONNECTED");
2493 if (playing)
2494 audio_stop_playback();
2495 #ifdef PLAYBACK_VOICE
2496 voice_stop();
2497 #endif
2498 usb_acknowledge(SYS_USB_CONNECTED_ACK);
2499 usb_wait_for_disconnect(&audio_queue);
2501 /* Mark all entries null. */
2502 audio_clear_track_entries();
2504 /* release tracks to make sure all handles are closed */
2505 audio_release_tracks();
2506 break;
2507 #endif
2509 case SYS_TIMEOUT:
2510 LOGFQUEUE_SYS_TIMEOUT("audio < SYS_TIMEOUT");
2511 break;
2513 default:
2514 LOGFQUEUE("audio < default");
2515 break;
2516 } /* end switch */
2517 } /* end while */
2520 /* Initialize the audio system - called from init() in main.c.
2521 * Last function because of all the references to internal symbols
2523 void audio_init(void)
2525 unsigned int audio_thread_id;
2527 /* Can never do this twice */
2528 if (audio_is_initialized)
2530 logf("audio: already initialized");
2531 return;
2534 logf("audio: initializing");
2536 /* Initialize queues before giving control elsewhere in case it likes
2537 to send messages. Thread creation will be delayed however so nothing
2538 starts running until ready if something yields such as talk_init. */
2539 queue_init(&audio_queue, true);
2540 queue_init(&codec_queue, false);
2541 queue_init(&pcmbuf_queue, false);
2543 pcm_init();
2545 /* Initialize codec api. */
2546 ci.read_filebuf = codec_filebuf_callback;
2547 ci.pcmbuf_insert = codec_pcmbuf_insert_callback;
2548 ci.codec_get_buffer = codec_get_buffer;
2549 ci.request_buffer = codec_request_buffer_callback;
2550 ci.advance_buffer = codec_advance_buffer_callback;
2551 ci.advance_buffer_loc = codec_advance_buffer_loc_callback;
2552 ci.request_next_track = codec_request_next_track_callback;
2553 ci.seek_buffer = codec_seek_buffer_callback;
2554 ci.seek_complete = codec_seek_complete_callback;
2555 ci.set_elapsed = codec_set_elapsed_callback;
2556 ci.set_offset = codec_set_offset_callback;
2557 ci.configure = codec_configure_callback;
2558 ci.discard_codec = codec_discard_codec_callback;
2559 ci.dsp = (struct dsp_config *)dsp_configure(NULL, DSP_MYDSP,
2560 CODEC_IDX_AUDIO);
2562 /* initialize the buffer */
2563 filebuf = audiobuf;
2565 /* audio_reset_buffer must to know the size of voice buffer so init
2566 talk first */
2567 talk_init();
2569 codec_thread_id = create_thread(
2570 codec_thread, codec_stack, sizeof(codec_stack),
2571 CREATE_THREAD_FROZEN,
2572 codec_thread_name IF_PRIO(, PRIORITY_PLAYBACK)
2573 IF_COP(, CPU));
2575 queue_enable_queue_send(&codec_queue, &codec_queue_sender_list,
2576 codec_thread_id);
2578 audio_thread_id = create_thread(audio_thread, audio_stack,
2579 sizeof(audio_stack), CREATE_THREAD_FROZEN,
2580 audio_thread_name IF_PRIO(, PRIORITY_USER_INTERFACE)
2581 IF_COP(, CPU));
2583 queue_enable_queue_send(&audio_queue, &audio_queue_sender_list,
2584 audio_thread_id);
2586 #ifdef PLAYBACK_VOICE
2587 voice_thread_init();
2588 #endif
2590 /* Set crossfade setting for next buffer init which should be about... */
2591 pcmbuf_crossfade_enable(global_settings.crossfade);
2593 /* initialize the buffering system */
2595 buffering_init();
2596 /* ...now! Set up the buffers */
2597 audio_reset_buffer();
2599 int i;
2600 for(i = 0; i < MAX_TRACK; i++)
2602 tracks[i].audio_hid = -1;
2603 tracks[i].id3_hid = -1;
2604 tracks[i].codec_hid = -1;
2605 #ifdef HAVE_ALBUMART
2606 tracks[i].aa_hid = -1;
2607 #endif
2610 add_event(BUFFER_EVENT_REBUFFER, false, buffering_handle_rebuffer_callback);
2611 add_event(BUFFER_EVENT_FINISHED, false, buffering_handle_finished_callback);
2613 /* Probably safe to say */
2614 audio_is_initialized = true;
2616 sound_settings_apply();
2617 #ifdef HAVE_DISK_STORAGE
2618 audio_set_buffer_margin(global_settings.buffer_margin);
2619 #endif
2621 /* it's safe to let the threads run now */
2622 #ifdef PLAYBACK_VOICE
2623 voice_thread_resume();
2624 #endif
2625 thread_thaw(codec_thread_id);
2626 thread_thaw(audio_thread_id);
2628 } /* audio_init */
2630 bool audio_is_thread_ready(void)
2632 return audio_thread_ready;