Fix test_codec for r19704 (prefix removed from plugin API).
[kugel-rb.git] / apps / playback.c
blobe81b32dbf9447bcae43146e645ca7dd38cb49b54
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 /* default point to start buffer refill */
92 #define AUDIO_DEFAULT_WATERMARK (1024*512)
93 /* amount of guess-space to allow for codecs that must hunt and peck
94 * for their correct seeek target, 32k seems a good size */
95 #define AUDIO_REBUFFER_GUESS_SIZE (1024*32)
97 /* Define LOGF_ENABLE to enable logf output in this file */
98 /*#define LOGF_ENABLE*/
99 #include "logf.h"
101 /* macros to enable logf for queues
102 logging on SYS_TIMEOUT can be disabled */
103 #ifdef SIMULATOR
104 /* Define this for logf output of all queuing except SYS_TIMEOUT */
105 #define PLAYBACK_LOGQUEUES
106 /* Define this to logf SYS_TIMEOUT messages */
107 /*#define PLAYBACK_LOGQUEUES_SYS_TIMEOUT*/
108 #endif
110 #ifdef PLAYBACK_LOGQUEUES
111 #define LOGFQUEUE logf
112 #else
113 #define LOGFQUEUE(...)
114 #endif
116 #ifdef PLAYBACK_LOGQUEUES_SYS_TIMEOUT
117 #define LOGFQUEUE_SYS_TIMEOUT logf
118 #else
119 #define LOGFQUEUE_SYS_TIMEOUT(...)
120 #endif
123 /* Define one constant that includes recording related functionality */
124 #if defined(HAVE_RECORDING) && !defined(SIMULATOR)
125 #define AUDIO_HAVE_RECORDING
126 #endif
128 enum {
129 Q_NULL = 0,
130 Q_AUDIO_PLAY = 1,
131 Q_AUDIO_STOP,
132 Q_AUDIO_PAUSE,
133 Q_AUDIO_SKIP,
134 Q_AUDIO_PRE_FF_REWIND,
135 Q_AUDIO_FF_REWIND,
136 Q_AUDIO_CHECK_NEW_TRACK,
137 Q_AUDIO_FLUSH,
138 Q_AUDIO_TRACK_CHANGED,
139 Q_AUDIO_DIR_SKIP,
140 Q_AUDIO_POSTINIT,
141 Q_AUDIO_FILL_BUFFER,
142 Q_AUDIO_FINISH_LOAD,
143 Q_CODEC_REQUEST_COMPLETE,
144 Q_CODEC_REQUEST_FAILED,
146 Q_CODEC_LOAD,
147 Q_CODEC_LOAD_DISK,
149 #ifdef AUDIO_HAVE_RECORDING
150 Q_ENCODER_LOAD_DISK,
151 Q_ENCODER_RECORD,
152 #endif
154 Q_CODEC_DO_CALLBACK,
157 enum filling_state {
158 STATE_IDLE, /* audio is stopped: nothing to do */
159 STATE_FILLING, /* adding tracks to the buffer */
160 STATE_FULL, /* can't add any more tracks */
161 STATE_END_OF_PLAYLIST, /* all remaining tracks have been added */
162 STATE_FINISHED, /* all remaining tracks are fully buffered */
165 #if MEM > 1
166 #define MAX_TRACK 128
167 #else
168 #define MAX_TRACK 32
169 #endif
171 #define MAX_TRACK_MASK (MAX_TRACK-1)
173 /* As defined in plugins/lib/xxx2wav.h */
174 #if MEM > 1
175 #define GUARD_BUFSIZE (32*1024)
176 #else
177 #define GUARD_BUFSIZE (8*1024)
178 #endif
180 /* As defined in plugin.lds */
181 #if defined(CPU_PP)
182 #define CODEC_IRAM_ORIGIN ((unsigned char *)0x4000c000)
183 #define CODEC_IRAM_SIZE ((size_t)0xc000)
184 #elif defined(IAUDIO_X5) || defined(IAUDIO_M5)
185 #define CODEC_IRAM_ORIGIN ((unsigned char *)0x10010000)
186 #define CODEC_IRAM_SIZE ((size_t)0x10000)
187 #else
188 #define CODEC_IRAM_ORIGIN ((unsigned char *)0x1000c000)
189 #define CODEC_IRAM_SIZE ((size_t)0xc000)
190 #endif
192 bool audio_is_initialized = false;
193 static bool audio_thread_ready SHAREDBSS_ATTR = false;
195 /* Variables are commented with the threads that use them: *
196 * A=audio, C=codec, V=voice. A suffix of - indicates that *
197 * the variable is read but not updated on that thread. */
198 /* TBD: Split out "audio" and "playback" (ie. calling) threads */
200 /* Main state control */
201 static volatile bool audio_codec_loaded SHAREDBSS_ATTR = false; /* Codec loaded? (C/A-) */
202 static volatile bool playing SHAREDBSS_ATTR = false; /* Is audio playing? (A) */
203 static volatile bool paused SHAREDBSS_ATTR = false; /* Is audio paused? (A/C-) */
205 /* Ring buffer where compressed audio and codecs are loaded */
206 static unsigned char *filebuf = NULL; /* Start of buffer (A/C-) */
207 static unsigned char *malloc_buf = NULL; /* Start of malloc buffer (A/C-) */
208 /* FIXME: make filebuflen static */
209 size_t filebuflen = 0; /* Size of buffer (A/C-) */
210 /* FIXME: make buf_ridx (C/A-) */
212 /* Possible arrangements of the buffer */
213 static int buffer_state = AUDIOBUF_STATE_TRASHED; /* Buffer state */
215 /* Used to keep the WPS up-to-date during track transtition */
216 static struct mp3entry prevtrack_id3;
218 /* Used to provide the codec with a pointer */
219 static struct mp3entry curtrack_id3;
221 /* Used to make next track info available while playing last track on buffer */
222 static struct mp3entry lasttrack_id3;
224 /* Track info structure about songs in the file buffer (A/C-) */
225 struct track_info {
226 int audio_hid; /* The ID for the track's buffer handle */
227 int id3_hid; /* The ID for the track's metadata handle */
228 int codec_hid; /* The ID for the track's codec handle */
229 #ifdef HAVE_ALBUMART
230 int aa_hid; /* The ID for the track's album art handle */
231 #endif
233 size_t filesize; /* File total length */
235 bool taginfo_ready; /* Is metadata read */
238 static struct track_info tracks[MAX_TRACK];
239 static volatile int track_ridx = 0; /* Track being decoded (A/C-) */
240 static int track_widx = 0; /* Track being buffered (A) */
242 #define CUR_TI (&tracks[track_ridx]) /* Playing track info pointer (A/C-) */
243 static struct track_info *prev_ti = NULL; /* Pointer to the previously played
244 track */
246 /* Set by the audio thread when the current track information has updated
247 * and the WPS may need to update its cached information */
248 static bool track_changed = false;
250 /* Information used only for filling the buffer */
251 /* Playlist steps from playing track to next track to be buffered (A) */
252 static int last_peek_offset = 0;
254 /* Scrobbler support */
255 static unsigned long prev_track_elapsed = 0; /* Previous track elapsed time (C/A-)*/
257 static enum filling_state filling;
259 /* Track change controls */
260 static bool automatic_skip = false; /* Who initiated in-progress skip? (C/A-) */
261 static bool dir_skip = false; /* Is a directory skip pending? (A) */
262 static bool new_playlist = false; /* Are we starting a new playlist? (A) */
263 static int wps_offset = 0; /* Pending track change offset, to keep WPS responsive (A) */
264 static bool skipped_during_pause = false; /* Do we need to clear the PCM buffer when playback resumes (A) */
266 static bool start_play_g = false; /* Used by audio_load_track to notify
267 audio_finish_load_track about start_play */
269 /* True when a track load is in progress, i.e. audio_load_track() has returned
270 * but audio_finish_load_track() hasn't been called yet. Used to avoid allowing
271 * audio_load_track() to get called twice in a row, which would cause problems.
273 static bool track_load_started = false;
275 /* Set to true if the codec thread should send an audio stop request
276 * (typically because the end of the playlist has been reached).
278 static bool codec_requested_stop = false;
280 static size_t buffer_margin = 0; /* Buffer margin aka anti-skip buffer (A/C-) */
282 /* Multiple threads */
283 /* Set the watermark to trigger buffer fill (A/C) FIXME */
284 static void set_filebuf_watermark(int seconds, size_t max);
286 /* Audio thread */
287 static struct event_queue audio_queue SHAREDBSS_ATTR;
288 static struct queue_sender_list audio_queue_sender_list SHAREDBSS_ATTR;
289 static long audio_stack[(DEFAULT_STACK_SIZE + 0x1000)/sizeof(long)];
290 static const char audio_thread_name[] = "audio";
292 static void audio_thread(void);
293 static void audio_initiate_track_change(long direction);
294 static bool audio_have_tracks(void);
295 static void audio_reset_buffer(void);
296 static void audio_stop_playback(void);
298 /* Codec thread */
299 extern struct codec_api ci;
300 static struct event_queue codec_queue SHAREDBSS_ATTR;
301 static struct queue_sender_list codec_queue_sender_list;
302 static long codec_stack[(DEFAULT_STACK_SIZE + 0x2000)/sizeof(long)]
303 IBSS_ATTR;
304 static const char codec_thread_name[] = "codec";
305 unsigned int codec_thread_id; /* For modifying thread priority later. */
307 /* PCM buffer messaging */
308 static struct event_queue pcmbuf_queue SHAREDBSS_ATTR;
310 /* Function to be called by pcm buffer callbacks.
311 * Permissible Context(s): Audio interrupt
313 static void pcmbuf_callback_queue_post(long id, intptr_t data)
315 /* No lock since we're already in audio interrupt context */
316 queue_post(&pcmbuf_queue, id, data);
319 /* Scan the pcmbuf queue and return true if a message pulled.
320 * Permissible Context(s): Thread
322 static bool pcmbuf_queue_scan(struct queue_event *ev)
324 if (!queue_empty(&pcmbuf_queue))
326 /* Transfer message to audio queue */
327 pcm_play_lock();
328 /* Pull message - never, ever any blocking call! */
329 queue_wait_w_tmo(&pcmbuf_queue, ev, 0);
330 pcm_play_unlock();
331 return true;
334 return false;
337 /* Clear the pcmbuf queue of messages
338 * Permissible Context(s): Thread
340 static void pcmbuf_queue_clear(void)
342 pcm_play_lock();
343 queue_clear(&pcmbuf_queue);
344 pcm_play_unlock();
347 /* --- Helper functions --- */
349 static struct mp3entry *bufgetid3(int handle_id)
351 if (handle_id < 0)
352 return NULL;
354 struct mp3entry *id3;
355 ssize_t ret = bufgetdata(handle_id, 0, (void *)&id3);
357 if (ret < 0 || ret != sizeof(struct mp3entry))
358 return NULL;
360 return id3;
363 static bool clear_track_info(struct track_info *track)
365 /* bufclose returns true if the handle is not found, or if it is closed
366 * successfully, so these checks are safe on non-existant handles */
367 if (!track)
368 return false;
370 if (track->codec_hid >= 0) {
371 if (bufclose(track->codec_hid))
372 track->codec_hid = -1;
373 else
374 return false;
377 if (track->id3_hid >= 0) {
378 if (bufclose(track->id3_hid))
379 track->id3_hid = -1;
380 else
381 return false;
384 if (track->audio_hid >= 0) {
385 if (bufclose(track->audio_hid))
386 track->audio_hid = -1;
387 else
388 return false;
391 #ifdef HAVE_ALBUMART
392 if (track->aa_hid >= 0) {
393 if (bufclose(track->aa_hid))
394 track->aa_hid = -1;
395 else
396 return false;
398 #endif
400 track->filesize = 0;
401 track->taginfo_ready = false;
403 return true;
406 /* --- External interfaces --- */
408 /* This sends a stop message and the audio thread will dump all it's
409 subsequenct messages */
410 void audio_hard_stop(void)
412 /* Stop playback */
413 LOGFQUEUE("audio >| audio Q_AUDIO_STOP: 1");
414 queue_send(&audio_queue, Q_AUDIO_STOP, 1);
415 #ifdef PLAYBACK_VOICE
416 voice_stop();
417 #endif
420 bool audio_restore_playback(int type)
422 switch (type)
424 case AUDIO_WANT_PLAYBACK:
425 if (buffer_state != AUDIOBUF_STATE_INITIALIZED)
426 audio_reset_buffer();
427 return true;
428 case AUDIO_WANT_VOICE:
429 if (buffer_state == AUDIOBUF_STATE_TRASHED)
430 audio_reset_buffer();
431 return true;
432 default:
433 return false;
437 unsigned char *audio_get_buffer(bool talk_buf, size_t *buffer_size)
439 unsigned char *buf, *end;
441 if (audio_is_initialized)
443 audio_hard_stop();
445 /* else buffer_state will be AUDIOBUF_STATE_TRASHED at this point */
447 if (buffer_size == NULL)
449 /* Special case for talk_init to use since it already knows it's
450 trashed */
451 buffer_state = AUDIOBUF_STATE_TRASHED;
452 return NULL;
455 if (talk_buf || buffer_state == AUDIOBUF_STATE_TRASHED
456 || !talk_voice_required())
458 logf("get buffer: talk, audio");
459 /* Ok to use everything from audiobuf to audiobufend - voice is loaded,
460 the talk buffer is not needed because voice isn't being used, or
461 could be AUDIOBUF_STATE_TRASHED already. If state is
462 AUDIOBUF_STATE_VOICED_ONLY, no problem as long as memory isn't written
463 without the caller knowing what's going on. Changing certain settings
464 may move it to a worse condition but the memory in use by something
465 else will remain undisturbed.
467 if (buffer_state != AUDIOBUF_STATE_TRASHED)
469 talk_buffer_steal();
470 buffer_state = AUDIOBUF_STATE_TRASHED;
473 buf = audiobuf;
474 end = audiobufend;
476 else
478 /* Safe to just return this if already AUDIOBUF_STATE_VOICED_ONLY or
479 still AUDIOBUF_STATE_INITIALIZED */
480 /* Skip talk buffer and move pcm buffer to end to maximize available
481 contiguous memory - no audio running means voice will not need the
482 swap space */
483 logf("get buffer: audio");
484 buf = audiobuf + talk_get_bufsize();
485 end = audiobufend - pcmbuf_init(audiobufend);
486 buffer_state = AUDIOBUF_STATE_VOICED_ONLY;
489 *buffer_size = end - buf;
491 return buf;
494 int audio_buffer_state(void)
496 return buffer_state;
499 #ifdef HAVE_RECORDING
500 unsigned char *audio_get_recording_buffer(size_t *buffer_size)
502 /* Stop audio, voice and obtain all available buffer space */
503 audio_hard_stop();
504 talk_buffer_steal();
506 unsigned char *end = audiobufend;
507 buffer_state = AUDIOBUF_STATE_TRASHED;
508 *buffer_size = end - audiobuf;
510 return (unsigned char *)audiobuf;
513 bool audio_load_encoder(int afmt)
515 #ifndef SIMULATOR
516 const char *enc_fn = get_codec_filename(afmt | CODEC_TYPE_ENCODER);
517 if (!enc_fn)
518 return false;
520 audio_remove_encoder();
521 ci.enc_codec_loaded = 0; /* clear any previous error condition */
523 LOGFQUEUE("codec > Q_ENCODER_LOAD_DISK");
524 queue_post(&codec_queue, Q_ENCODER_LOAD_DISK, (intptr_t)enc_fn);
526 while (ci.enc_codec_loaded == 0)
527 yield();
529 logf("codec loaded: %d", ci.enc_codec_loaded);
531 return ci.enc_codec_loaded > 0;
532 #else
533 (void)afmt;
534 return true;
535 #endif
536 } /* audio_load_encoder */
538 void audio_remove_encoder(void)
540 #ifndef SIMULATOR
541 /* force encoder codec unload (if currently loaded) */
542 if (ci.enc_codec_loaded <= 0)
543 return;
545 ci.stop_encoder = true;
546 while (ci.enc_codec_loaded > 0)
547 yield();
548 #endif
549 } /* audio_remove_encoder */
551 #endif /* HAVE_RECORDING */
553 #ifdef HAVE_ALBUMART
554 int audio_current_aa_hid(void)
556 int cur_idx;
557 int offset = ci.new_track + wps_offset;
559 cur_idx = track_ridx + offset;
560 cur_idx &= MAX_TRACK_MASK;
562 return tracks[cur_idx].aa_hid;
564 #endif
566 struct mp3entry* audio_current_track(void)
568 const char *filename;
569 static struct mp3entry temp_id3;
570 struct playlist_track_info trackinfo;
571 int cur_idx;
572 int offset = ci.new_track + wps_offset;
574 cur_idx = (track_ridx + offset) & MAX_TRACK_MASK;
576 if (cur_idx == track_ridx && *curtrack_id3.path)
578 /* The usual case */
579 return &curtrack_id3;
581 else if (automatic_skip && offset == -1 && *prevtrack_id3.path)
583 /* We're in a track transition. The codec has moved on to the nex track,
584 but the audio being played is still the same (now previous) track.
585 prevtrack_id3.elapsed is being updated in an ISR by
586 codec_pcmbuf_position_callback */
587 return &prevtrack_id3;
589 else if (tracks[cur_idx].id3_hid >= 0)
591 /* Get the ID3 metadata from the main buffer */
592 struct mp3entry *ret = bufgetid3(tracks[cur_idx].id3_hid);
593 if (ret) return ret;
596 /* We didn't find the ID3 metadata, so we fill temp_id3 with the little info
597 we have and return that. */
599 memset(&temp_id3, 0, sizeof(struct mp3entry));
601 playlist_get_track_info(NULL, playlist_next(0)+wps_offset, &trackinfo);
602 filename = trackinfo.filename;
603 if (!filename)
604 filename = "No file!";
606 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
607 if (tagcache_fill_tags(&temp_id3, filename))
608 return &temp_id3;
609 #endif
611 strncpy(temp_id3.path, filename, sizeof(temp_id3.path)-1);
612 temp_id3.title = strrchr(temp_id3.path, '/');
613 if (!temp_id3.title)
614 temp_id3.title = &temp_id3.path[0];
615 else
616 temp_id3.title++;
618 return &temp_id3;
621 struct mp3entry* audio_next_track(void)
623 int next_idx;
624 int offset = ci.new_track + wps_offset;
626 if (!audio_have_tracks())
627 return NULL;
629 if (wps_offset == -1 && *prevtrack_id3.path)
631 /* We're in a track transition. The next track for the WPS is the one
632 currently being decoded. */
633 return &curtrack_id3;
636 next_idx = (track_ridx + offset + 1) & MAX_TRACK_MASK;
638 if (tracks[next_idx].id3_hid >= 0)
639 return bufgetid3(tracks[next_idx].id3_hid);
641 if (next_idx == track_widx)
643 /* The next track hasn't been buffered yet, so we return the static
644 version of its metadata. */
645 return &lasttrack_id3;
648 return NULL;
651 bool audio_has_changed_track(void)
653 if (track_changed)
655 #ifdef IPOD_ACCESSORY_PROTOCOL
656 iap_track_changed();
657 #endif
658 track_changed = false;
659 return true;
662 return false;
665 void audio_play(long offset)
667 logf("audio_play");
669 #ifdef PLAYBACK_VOICE
670 /* Truncate any existing voice output so we don't have spelling
671 * etc. over the first part of the played track */
672 talk_force_shutup();
673 #endif
675 /* Start playback */
676 LOGFQUEUE("audio >| audio Q_AUDIO_PLAY: %ld", offset);
677 /* Don't return until playback has actually started */
678 queue_send(&audio_queue, Q_AUDIO_PLAY, offset);
681 void audio_stop(void)
683 /* Stop playback */
684 LOGFQUEUE("audio >| audio Q_AUDIO_STOP");
685 /* Don't return until playback has actually stopped */
686 queue_send(&audio_queue, Q_AUDIO_STOP, 0);
689 void audio_pause(void)
691 LOGFQUEUE("audio >| audio Q_AUDIO_PAUSE");
692 /* Don't return until playback has actually paused */
693 queue_send(&audio_queue, Q_AUDIO_PAUSE, true);
696 void audio_resume(void)
698 LOGFQUEUE("audio >| audio Q_AUDIO_PAUSE resume");
699 /* Don't return until playback has actually resumed */
700 queue_send(&audio_queue, Q_AUDIO_PAUSE, false);
703 void audio_skip(int direction)
705 if (playlist_check(ci.new_track + wps_offset + direction))
707 if (global_settings.beep)
708 pcmbuf_beep(2000, 100, 2500*global_settings.beep);
710 LOGFQUEUE("audio > audio Q_AUDIO_SKIP %d", direction);
711 queue_post(&audio_queue, Q_AUDIO_SKIP, direction);
712 /* Update wps while our message travels inside deep playback queues. */
713 wps_offset += direction;
714 track_changed = true;
716 else
718 /* No more tracks. */
719 if (global_settings.beep)
720 pcmbuf_beep(1000, 100, 1500*global_settings.beep);
724 void audio_next(void)
726 audio_skip(1);
729 void audio_prev(void)
731 audio_skip(-1);
734 void audio_next_dir(void)
736 LOGFQUEUE("audio > audio Q_AUDIO_DIR_SKIP 1");
737 queue_post(&audio_queue, Q_AUDIO_DIR_SKIP, 1);
740 void audio_prev_dir(void)
742 LOGFQUEUE("audio > audio Q_AUDIO_DIR_SKIP -1");
743 queue_post(&audio_queue, Q_AUDIO_DIR_SKIP, -1);
746 void audio_pre_ff_rewind(void)
748 LOGFQUEUE("audio > audio Q_AUDIO_PRE_FF_REWIND");
749 queue_post(&audio_queue, Q_AUDIO_PRE_FF_REWIND, 0);
752 void audio_ff_rewind(long newpos)
754 LOGFQUEUE("audio > audio Q_AUDIO_FF_REWIND");
755 queue_post(&audio_queue, Q_AUDIO_FF_REWIND, newpos);
758 void audio_flush_and_reload_tracks(void)
760 LOGFQUEUE("audio > audio Q_AUDIO_FLUSH");
761 queue_post(&audio_queue, Q_AUDIO_FLUSH, 0);
764 void audio_error_clear(void)
766 #ifdef AUDIO_HAVE_RECORDING
767 pcm_rec_error_clear();
768 #endif
771 int audio_status(void)
773 int ret = 0;
775 if (playing)
776 ret |= AUDIO_STATUS_PLAY;
778 if (paused)
779 ret |= AUDIO_STATUS_PAUSE;
781 #ifdef HAVE_RECORDING
782 /* Do this here for constitency with mpeg.c version */
783 ret |= pcm_rec_status();
784 #endif
786 return ret;
789 int audio_get_file_pos(void)
791 return 0;
794 #ifdef HAVE_DISK_STORAGE
795 void audio_set_buffer_margin(int setting)
797 static const int lookup[] = {5, 15, 30, 60, 120, 180, 300, 600};
798 buffer_margin = lookup[setting];
799 logf("buffer margin: %ld", (long)buffer_margin);
800 set_filebuf_watermark(buffer_margin, 0);
802 #endif
804 /* Take necessary steps to enable or disable the crossfade setting */
805 void audio_set_crossfade(int enable)
807 size_t offset;
808 bool was_playing;
809 size_t size;
811 /* Tell it the next setting to use */
812 pcmbuf_crossfade_enable(enable);
814 /* Return if size hasn't changed or this is too early to determine
815 which in the second case there's no way we could be playing
816 anything at all */
817 if (pcmbuf_is_same_size())
819 /* This function is a copout and just syncs some variables -
820 to be removed at a later date */
821 pcmbuf_crossfade_enable_finished();
822 return;
825 offset = 0;
826 was_playing = playing;
828 /* Playback has to be stopped before changing the buffer size */
829 if (was_playing)
831 /* Store the track resume position */
832 offset = curtrack_id3.offset;
835 /* Blast it - audio buffer will have to be setup again next time
836 something plays */
837 audio_get_buffer(true, &size);
839 /* Restart playback if audio was running previously */
840 if (was_playing)
841 audio_play(offset);
844 /* --- Routines called from multiple threads --- */
846 static void set_filebuf_watermark(int seconds, size_t max)
848 size_t bytes;
850 if (!filebuf)
851 return; /* Audio buffers not yet set up */
853 bytes = seconds?MAX(curtrack_id3.bitrate * seconds * (1000/8), max):max;
854 bytes = MIN(bytes, filebuflen / 2);
855 buf_set_watermark(bytes);
858 const char *get_codec_filename(int cod_spec)
860 const char *fname;
862 #ifdef HAVE_RECORDING
863 /* Can choose decoder or encoder if one available */
864 int type = cod_spec & CODEC_TYPE_MASK;
865 int afmt = cod_spec & CODEC_AFMT_MASK;
867 if ((unsigned)afmt >= AFMT_NUM_CODECS)
868 type = AFMT_UNKNOWN | (type & CODEC_TYPE_MASK);
870 fname = (type == CODEC_TYPE_ENCODER) ?
871 audio_formats[afmt].codec_enc_root_fn :
872 audio_formats[afmt].codec_root_fn;
874 logf("%s: %d - %s",
875 (type == CODEC_TYPE_ENCODER) ? "Encoder" : "Decoder",
876 afmt, fname ? fname : "<unknown>");
877 #else /* !HAVE_RECORDING */
878 /* Always decoder */
879 if ((unsigned)cod_spec >= AFMT_NUM_CODECS)
880 cod_spec = AFMT_UNKNOWN;
881 fname = audio_formats[cod_spec].codec_root_fn;
882 logf("Codec: %d - %s", cod_spec, fname ? fname : "<unknown>");
883 #endif /* HAVE_RECORDING */
885 return fname;
886 } /* get_codec_filename */
888 /* --- Codec thread --- */
889 static bool codec_pcmbuf_insert_callback(
890 const void *ch1, const void *ch2, int count)
892 const char *src[2] = { ch1, ch2 };
894 while (count > 0)
896 int out_count = dsp_output_count(ci.dsp, count);
897 int inp_count;
898 char *dest;
900 /* Prevent audio from a previous track from playing */
901 if (ci.new_track || ci.stop_codec)
902 return true;
904 while ((dest = pcmbuf_request_buffer(&out_count)) == NULL)
906 cancel_cpu_boost();
907 sleep(1);
908 if (ci.seek_time || ci.new_track || ci.stop_codec)
909 return true;
912 /* Get the real input_size for output_size bytes, guarding
913 * against resampling buffer overflows. */
914 inp_count = dsp_input_count(ci.dsp, out_count);
916 if (inp_count <= 0)
917 return true;
919 /* Input size has grown, no error, just don't write more than length */
920 if (inp_count > count)
921 inp_count = count;
923 out_count = dsp_process(ci.dsp, dest, src, inp_count);
925 if (out_count <= 0)
926 return true;
928 pcmbuf_write_complete(out_count);
930 count -= inp_count;
933 return true;
934 } /* codec_pcmbuf_insert_callback */
936 static void* codec_get_buffer(size_t *size)
938 if (codec_size >= CODEC_SIZE)
939 return NULL;
940 *size = CODEC_SIZE - codec_size;
941 return &codecbuf[codec_size];
944 /* Between the codec and PCM track change, we need to keep updating the
945 "elapsed" value of the previous (to the codec, but current to the
946 user/PCM/WPS) track, so that the progressbar reaches the end.
947 During that transition, the WPS will display prevtrack_id3. */
948 static void codec_pcmbuf_position_callback(size_t size) ICODE_ATTR;
949 static void codec_pcmbuf_position_callback(size_t size)
951 /* This is called from an ISR, so be quick */
952 unsigned int time = size * 1000 / 4 / NATIVE_FREQUENCY +
953 prevtrack_id3.elapsed;
955 if (time >= prevtrack_id3.length)
957 pcmbuf_set_position_callback(NULL);
958 prevtrack_id3.elapsed = prevtrack_id3.length;
960 else
961 prevtrack_id3.elapsed = time;
964 static void codec_set_elapsed_callback(unsigned int value)
966 unsigned int latency;
967 if (ci.seek_time)
968 return;
970 #ifdef AB_REPEAT_ENABLE
971 ab_position_report(value);
972 #endif
974 latency = pcmbuf_get_latency();
975 if (value < latency)
976 curtrack_id3.elapsed = 0;
977 else if (value - latency > curtrack_id3.elapsed ||
978 value - latency < curtrack_id3.elapsed - 2)
980 curtrack_id3.elapsed = value - latency;
984 static void codec_set_offset_callback(size_t value)
986 unsigned int latency;
988 if (ci.seek_time)
989 return;
991 latency = pcmbuf_get_latency() * curtrack_id3.bitrate / 8;
992 if (value < latency)
993 curtrack_id3.offset = 0;
994 else
995 curtrack_id3.offset = value - latency;
998 static void codec_advance_buffer_counters(size_t amount)
1000 bufadvance(CUR_TI->audio_hid, amount);
1001 ci.curpos += amount;
1004 /* copy up-to size bytes into ptr and return the actual size copied */
1005 static size_t codec_filebuf_callback(void *ptr, size_t size)
1007 ssize_t copy_n;
1009 if (ci.stop_codec || !playing)
1010 return 0;
1012 copy_n = bufread(CUR_TI->audio_hid, size, ptr);
1014 /* Nothing requested OR nothing left */
1015 if (copy_n == 0)
1016 return 0;
1018 /* Update read and other position pointers */
1019 codec_advance_buffer_counters(copy_n);
1021 /* Return the actual amount of data copied to the buffer */
1022 return copy_n;
1023 } /* codec_filebuf_callback */
1025 static void* codec_request_buffer_callback(size_t *realsize, size_t reqsize)
1027 size_t copy_n = reqsize;
1028 ssize_t ret;
1029 void *ptr;
1031 if (!playing)
1033 *realsize = 0;
1034 return NULL;
1037 ret = bufgetdata(CUR_TI->audio_hid, reqsize, &ptr);
1038 if (ret >= 0)
1039 copy_n = MIN((size_t)ret, reqsize);
1041 if (copy_n == 0)
1043 *realsize = 0;
1044 return NULL;
1047 *realsize = copy_n;
1049 return ptr;
1050 } /* codec_request_buffer_callback */
1052 static int get_codec_base_type(int type)
1054 switch (type) {
1055 case AFMT_MPA_L1:
1056 case AFMT_MPA_L2:
1057 case AFMT_MPA_L3:
1058 return AFMT_MPA_L3;
1061 return type;
1064 static void codec_advance_buffer_callback(size_t amount)
1066 codec_advance_buffer_counters(amount);
1067 codec_set_offset_callback(ci.curpos);
1070 static void codec_advance_buffer_loc_callback(void *ptr)
1072 size_t amount = buf_get_offset(CUR_TI->audio_hid, ptr);
1073 codec_advance_buffer_callback(amount);
1076 static void codec_seek_complete_callback(void)
1078 logf("seek_complete");
1079 if (pcm_is_paused())
1081 /* If this is not a seamless seek, clear the buffer */
1082 pcmbuf_play_stop();
1083 dsp_configure(ci.dsp, DSP_FLUSH, 0);
1085 /* If playback was not 'deliberately' paused, unpause now */
1086 if (!paused)
1087 pcmbuf_pause(false);
1089 ci.seek_time = 0;
1092 static bool codec_seek_buffer_callback(size_t newpos)
1094 logf("codec_seek_buffer_callback");
1096 int ret = bufseek(CUR_TI->audio_hid, newpos);
1097 if (ret == 0) {
1098 ci.curpos = newpos;
1099 return true;
1101 else {
1102 return false;
1106 static void codec_configure_callback(int setting, intptr_t value)
1108 switch (setting) {
1109 case CODEC_SET_FILEBUF_WATERMARK:
1110 set_filebuf_watermark(buffer_margin, value);
1111 break;
1113 default:
1114 if (!dsp_configure(ci.dsp, setting, value))
1115 { logf("Illegal key:%d", setting); }
1119 static void codec_track_changed(void)
1121 LOGFQUEUE("codec > audio Q_AUDIO_TRACK_CHANGED");
1122 queue_post(&audio_queue, Q_AUDIO_TRACK_CHANGED, 0);
1125 static void codec_pcmbuf_track_changed_callback(void)
1127 pcmbuf_set_position_callback(NULL);
1128 pcmbuf_callback_queue_post(Q_AUDIO_TRACK_CHANGED, 0);
1131 static void codec_discard_codec_callback(void)
1133 if (CUR_TI->codec_hid >= 0)
1135 bufclose(CUR_TI->codec_hid);
1136 CUR_TI->codec_hid = -1;
1140 static inline void codec_gapless_track_change(void)
1142 /* callback keeps the progress bar moving while the pcmbuf empties */
1143 pcmbuf_set_position_callback(codec_pcmbuf_position_callback);
1144 /* set the pcmbuf callback for when the track really changes */
1145 pcmbuf_set_event_handler(codec_pcmbuf_track_changed_callback);
1148 static inline void codec_crossfade_track_change(void)
1150 /* Initiate automatic crossfade mode */
1151 pcmbuf_crossfade_init(false);
1152 /* Notify the wps that the track change starts now */
1153 codec_track_changed();
1156 static void codec_track_skip_done(bool was_manual)
1158 /* Manual track change (always crossfade or flush audio). */
1159 if (was_manual)
1161 pcmbuf_crossfade_init(true);
1162 LOGFQUEUE("codec > audio Q_AUDIO_TRACK_CHANGED");
1163 queue_post(&audio_queue, Q_AUDIO_TRACK_CHANGED, 0);
1165 /* Automatic track change w/crossfade, if not in "Track Skip Only" mode. */
1166 else if (pcmbuf_is_crossfade_enabled() && !pcmbuf_is_crossfade_active()
1167 && global_settings.crossfade != CROSSFADE_ENABLE_TRACKSKIP)
1169 if (global_settings.crossfade == CROSSFADE_ENABLE_SHUFFLE_AND_TRACKSKIP)
1171 if (global_settings.playlist_shuffle)
1172 /* shuffle mode is on, so crossfade: */
1173 codec_crossfade_track_change();
1174 else
1175 /* shuffle mode is off, so do a gapless track change */
1176 codec_gapless_track_change();
1178 else
1179 /* normal crossfade: */
1180 codec_crossfade_track_change();
1182 else
1183 /* normal gapless playback. */
1184 codec_gapless_track_change();
1187 static bool codec_load_next_track(void)
1189 intptr_t result = Q_CODEC_REQUEST_FAILED;
1191 prev_track_elapsed = curtrack_id3.elapsed;
1193 #ifdef AB_REPEAT_ENABLE
1194 ab_end_of_track_report();
1195 #endif
1197 logf("Request new track");
1199 if (ci.new_track == 0)
1201 ci.new_track++;
1202 automatic_skip = true;
1205 if (!ci.stop_codec)
1207 trigger_cpu_boost();
1208 LOGFQUEUE("codec >| audio Q_AUDIO_CHECK_NEW_TRACK");
1209 result = queue_send(&audio_queue, Q_AUDIO_CHECK_NEW_TRACK, 0);
1212 switch (result)
1214 case Q_CODEC_REQUEST_COMPLETE:
1215 LOGFQUEUE("codec |< Q_CODEC_REQUEST_COMPLETE");
1216 codec_track_skip_done(!automatic_skip);
1217 return true;
1219 case Q_CODEC_REQUEST_FAILED:
1220 LOGFQUEUE("codec |< Q_CODEC_REQUEST_FAILED");
1221 ci.new_track = 0;
1222 ci.stop_codec = true;
1223 codec_requested_stop = true;
1224 return false;
1226 default:
1227 LOGFQUEUE("codec |< default");
1228 ci.stop_codec = true;
1229 codec_requested_stop = true;
1230 return false;
1234 static bool codec_request_next_track_callback(void)
1236 int prev_codectype;
1238 if (ci.stop_codec || !playing)
1239 return false;
1241 prev_codectype = get_codec_base_type(curtrack_id3.codectype);
1243 if (!codec_load_next_track())
1244 return false;
1246 /* Seek to the beginning of the new track because if the struct
1247 mp3entry was buffered, "elapsed" might not be zero (if the track has
1248 been played already but not unbuffered) */
1249 codec_seek_buffer_callback(curtrack_id3.first_frame_offset);
1251 /* Check if the next codec is the same file. */
1252 if (prev_codectype == get_codec_base_type(curtrack_id3.codectype))
1254 logf("New track loaded");
1255 codec_discard_codec_callback();
1256 return true;
1258 else
1260 logf("New codec:%d/%d", curtrack_id3.codectype, prev_codectype);
1261 return false;
1265 static void codec_thread(void)
1267 struct queue_event ev;
1268 int status;
1270 while (1) {
1271 status = 0;
1273 if (!pcmbuf_is_crossfade_active()) {
1274 cancel_cpu_boost();
1277 queue_wait(&codec_queue, &ev);
1278 codec_requested_stop = false;
1280 switch (ev.id) {
1281 case Q_CODEC_LOAD_DISK:
1282 LOGFQUEUE("codec < Q_CODEC_LOAD_DISK");
1283 queue_reply(&codec_queue, 1);
1284 audio_codec_loaded = true;
1285 ci.stop_codec = false;
1286 status = codec_load_file((const char *)ev.data, &ci);
1287 break;
1289 case Q_CODEC_LOAD:
1290 LOGFQUEUE("codec < Q_CODEC_LOAD");
1291 if (CUR_TI->codec_hid < 0) {
1292 logf("Codec slot is empty!");
1293 /* Wait for the pcm buffer to go empty */
1294 while (pcm_is_playing())
1295 yield();
1296 /* This must be set to prevent an infinite loop */
1297 ci.stop_codec = true;
1298 LOGFQUEUE("codec > codec Q_AUDIO_PLAY");
1299 queue_post(&codec_queue, Q_AUDIO_PLAY, 0);
1300 break;
1303 audio_codec_loaded = true;
1304 ci.stop_codec = false;
1305 status = codec_load_buf(CUR_TI->codec_hid, &ci);
1306 break;
1308 case Q_CODEC_DO_CALLBACK:
1309 LOGFQUEUE("codec < Q_CODEC_DO_CALLBACK");
1310 queue_reply(&codec_queue, 1);
1311 if ((void*)ev.data != NULL)
1313 invalidate_icache();
1314 ((void (*)(void))ev.data)();
1315 flush_icache();
1317 break;
1319 #ifdef AUDIO_HAVE_RECORDING
1320 case Q_ENCODER_LOAD_DISK:
1321 LOGFQUEUE("codec < Q_ENCODER_LOAD_DISK");
1322 audio_codec_loaded = false; /* Not audio codec! */
1323 logf("loading encoder");
1324 ci.stop_encoder = false;
1325 status = codec_load_file((const char *)ev.data, &ci);
1326 logf("encoder stopped");
1327 break;
1328 #endif /* AUDIO_HAVE_RECORDING */
1330 default:
1331 LOGFQUEUE("codec < default");
1334 if (audio_codec_loaded)
1336 if (ci.stop_codec)
1338 status = CODEC_OK;
1339 if (!playing)
1340 pcmbuf_play_stop();
1343 audio_codec_loaded = false;
1346 switch (ev.id) {
1347 case Q_CODEC_LOAD_DISK:
1348 case Q_CODEC_LOAD:
1349 LOGFQUEUE("codec < Q_CODEC_LOAD");
1350 if (playing)
1352 if (ci.new_track || status != CODEC_OK)
1354 if (!ci.new_track)
1356 logf("Codec failure");
1357 splash(HZ*2, "Codec failure");
1360 if (!codec_load_next_track())
1362 LOGFQUEUE("codec > audio Q_AUDIO_STOP");
1363 /* End of playlist */
1364 queue_post(&audio_queue, Q_AUDIO_STOP, 0);
1365 break;
1368 else
1370 logf("Codec finished");
1371 if (ci.stop_codec)
1373 /* Wait for the audio to stop playing before
1374 * triggering the WPS exit */
1375 while(pcm_is_playing())
1377 curtrack_id3.elapsed =
1378 curtrack_id3.length - pcmbuf_get_latency();
1379 sleep(1);
1382 if (codec_requested_stop)
1384 LOGFQUEUE("codec > audio Q_AUDIO_STOP");
1385 queue_post(&audio_queue, Q_AUDIO_STOP, 0);
1387 break;
1391 if (CUR_TI->codec_hid >= 0)
1393 LOGFQUEUE("codec > codec Q_CODEC_LOAD");
1394 queue_post(&codec_queue, Q_CODEC_LOAD, 0);
1396 else
1398 const char *codec_fn =
1399 get_codec_filename(curtrack_id3.codectype);
1400 if (codec_fn)
1402 LOGFQUEUE("codec > codec Q_CODEC_LOAD_DISK");
1403 queue_post(&codec_queue, Q_CODEC_LOAD_DISK,
1404 (intptr_t)codec_fn);
1408 break;
1410 #ifdef AUDIO_HAVE_RECORDING
1411 case Q_ENCODER_LOAD_DISK:
1412 LOGFQUEUE("codec < Q_ENCODER_LOAD_DISK");
1414 if (status == CODEC_OK)
1415 break;
1417 logf("Encoder failure");
1418 splash(HZ*2, "Encoder failure");
1420 if (ci.enc_codec_loaded < 0)
1421 break;
1423 logf("Encoder failed to load");
1424 ci.enc_codec_loaded = -1;
1425 break;
1426 #endif /* AUDIO_HAVE_RECORDING */
1428 default:
1429 LOGFQUEUE("codec < default");
1431 } /* end switch */
1435 /* Borrow the codec thread and return the ID */
1436 void codec_thread_do_callback(void (*fn)(void), unsigned int *id)
1438 /* Set id before telling thread to call something; it may be
1439 * needed before this function returns. */
1440 if (id != NULL)
1441 *id = codec_thread_id;
1443 /* Codec thread will signal just before entering callback */
1444 LOGFQUEUE("codec >| Q_CODEC_DO_CALLBACK");
1445 queue_send(&codec_queue, Q_CODEC_DO_CALLBACK, (intptr_t)fn);
1448 /* --- Buffering callbacks --- */
1450 static void buffering_low_buffer_callback(void *data)
1452 (void)data;
1453 logf("low buffer callback");
1455 if (filling == STATE_FULL || filling == STATE_END_OF_PLAYLIST) {
1456 /* force a refill */
1457 LOGFQUEUE("buffering > audio Q_AUDIO_FILL_BUFFER");
1458 queue_post(&audio_queue, Q_AUDIO_FILL_BUFFER, 0);
1462 static void buffering_handle_rebuffer_callback(void *data)
1464 (void)data;
1465 LOGFQUEUE("audio >| audio Q_AUDIO_FLUSH");
1466 queue_post(&audio_queue, Q_AUDIO_FLUSH, 0);
1469 static void buffering_handle_finished_callback(int *data)
1471 logf("handle %d finished buffering", *data);
1473 if (*data == tracks[track_widx].id3_hid)
1475 /* The metadata handle for the last loaded track has been buffered.
1476 We can ask the audio thread to load the rest of the track's data. */
1477 LOGFQUEUE("audio >| audio Q_AUDIO_FINISH_LOAD");
1478 queue_post(&audio_queue, Q_AUDIO_FINISH_LOAD, 0);
1480 else
1482 /* This is most likely an audio handle, so we strip the useless
1483 trailing tags that are left. */
1484 strip_tags(*data);
1486 if (*data == tracks[track_widx-1].audio_hid
1487 && filling == STATE_END_OF_PLAYLIST)
1489 /* This was the last track in the playlist.
1490 We now have all the data we need. */
1491 logf("last track finished buffering");
1492 filling = STATE_FINISHED;
1498 /* --- Audio thread --- */
1500 static bool audio_have_tracks(void)
1502 return (audio_track_count() != 0);
1505 static int audio_free_track_count(void)
1507 /* Used tracks + free tracks adds up to MAX_TRACK - 1 */
1508 return MAX_TRACK - 1 - audio_track_count();
1511 int audio_track_count(void)
1513 /* Calculate difference from track_ridx to track_widx
1514 * taking into account a possible wrap-around. */
1515 return (MAX_TRACK + track_widx - track_ridx) & MAX_TRACK_MASK;
1518 long audio_filebufused(void)
1520 return (long) buf_used();
1523 /* Update track info after successful a codec track change */
1524 static void audio_update_trackinfo(void)
1526 /* Load the curent track's metadata into curtrack_id3 */
1527 if (CUR_TI->id3_hid >= 0)
1528 copy_mp3entry(&curtrack_id3, bufgetid3(CUR_TI->id3_hid));
1530 /* Reset current position */
1531 curtrack_id3.elapsed = 0;
1532 curtrack_id3.offset = 0;
1534 /* Update the codec API */
1535 ci.filesize = CUR_TI->filesize;
1536 ci.id3 = &curtrack_id3;
1537 ci.curpos = 0;
1538 ci.taginfo_ready = &CUR_TI->taginfo_ready;
1541 /* Clear tracks between write and read, non inclusive */
1542 static void audio_clear_track_entries(void)
1544 int cur_idx = track_widx;
1546 logf("Clearing tracks:%d/%d", track_ridx, track_widx);
1548 /* Loop over all tracks from write-to-read */
1549 while (1)
1551 cur_idx = (cur_idx + 1) & MAX_TRACK_MASK;
1553 if (cur_idx == track_ridx)
1554 break;
1556 clear_track_info(&tracks[cur_idx]);
1560 /* Clear all tracks */
1561 static bool audio_release_tracks(void)
1563 int i, cur_idx;
1565 logf("releasing all tracks");
1567 for(i = 0; i < MAX_TRACK; i++)
1569 cur_idx = (track_ridx + i) & MAX_TRACK_MASK;
1570 if (!clear_track_info(&tracks[cur_idx]))
1571 return false;
1574 return true;
1577 static bool audio_loadcodec(bool start_play)
1579 int prev_track;
1580 char codec_path[MAX_PATH]; /* Full path to codec */
1581 const struct mp3entry *id3, *prev_id3;
1583 if (tracks[track_widx].id3_hid < 0) {
1584 return false;
1587 id3 = bufgetid3(tracks[track_widx].id3_hid);
1588 if (!id3)
1589 return false;
1591 const char *codec_fn = get_codec_filename(id3->codectype);
1592 if (codec_fn == NULL)
1593 return false;
1595 tracks[track_widx].codec_hid = -1;
1597 if (start_play)
1599 /* Load the codec directly from disk and save some memory. */
1600 track_ridx = track_widx;
1601 ci.filesize = CUR_TI->filesize;
1602 ci.id3 = &curtrack_id3;
1603 ci.taginfo_ready = &CUR_TI->taginfo_ready;
1604 ci.curpos = 0;
1605 LOGFQUEUE("codec > codec Q_CODEC_LOAD_DISK");
1606 queue_post(&codec_queue, Q_CODEC_LOAD_DISK, (intptr_t)codec_fn);
1607 return true;
1609 else
1611 /* If we already have another track than this one buffered */
1612 if (track_widx != track_ridx)
1614 prev_track = (track_widx - 1) & MAX_TRACK_MASK;
1616 id3 = bufgetid3(tracks[track_widx].id3_hid);
1617 prev_id3 = bufgetid3(tracks[prev_track].id3_hid);
1619 /* If the previous codec is the same as this one, there is no need
1620 * to put another copy of it on the file buffer */
1621 if (id3 && prev_id3 &&
1622 get_codec_base_type(id3->codectype) ==
1623 get_codec_base_type(prev_id3->codectype)
1624 && audio_codec_loaded)
1626 logf("Reusing prev. codec");
1627 return true;
1632 codec_get_full_path(codec_path, codec_fn);
1634 tracks[track_widx].codec_hid = bufopen(codec_path, 0, TYPE_CODEC);
1635 if (tracks[track_widx].codec_hid < 0)
1636 return false;
1638 logf("Loaded codec");
1640 return true;
1643 /* Load metadata for the next track (with bufopen). The rest of the track
1644 loading will be handled by audio_finish_load_track once the metadata has been
1645 actually loaded by the buffering thread. */
1646 static bool audio_load_track(size_t offset, bool start_play)
1648 const char *trackname;
1649 int fd = -1;
1651 if (track_load_started) {
1652 /* There is already a track load in progress, so track_widx hasn't been
1653 incremented yet. Loading another track would overwrite the one that
1654 hasn't finished loading. */
1655 logf("audio_load_track(): a track load is already in progress");
1656 return false;
1659 start_play_g = start_play; /* will be read by audio_finish_load_track */
1661 /* Stop buffer filling if there is no free track entries.
1662 Don't fill up the last track entry (we wan't to store next track
1663 metadata there). */
1664 if (!audio_free_track_count())
1666 logf("No free tracks");
1667 return false;
1670 last_peek_offset++;
1671 tracks[track_widx].taginfo_ready = false;
1673 logf("Buffering track:%d/%d", track_widx, track_ridx);
1674 /* Get track name from current playlist read position. */
1675 while ((trackname = playlist_peek(last_peek_offset)) != NULL)
1677 /* Handle broken playlists. */
1678 fd = open(trackname, O_RDONLY);
1679 if (fd < 0)
1681 logf("Open failed");
1682 /* Skip invalid entry from playlist. */
1683 playlist_skip_entry(NULL, last_peek_offset);
1685 else
1686 break;
1689 if (!trackname)
1691 logf("End-of-playlist");
1692 memset(&lasttrack_id3, 0, sizeof(struct mp3entry));
1693 filling = STATE_END_OF_PLAYLIST;
1695 if (curtrack_id3.length == 0 && curtrack_id3.filesize == 0)
1697 /* Stop playback if no valid track was found. */
1698 audio_stop_playback();
1701 return false;
1704 tracks[track_widx].filesize = filesize(fd);
1706 if (offset > tracks[track_widx].filesize)
1707 offset = 0;
1709 /* Set default values */
1710 if (start_play)
1712 buf_set_watermark(AUDIO_DEFAULT_WATERMARK);
1713 dsp_configure(ci.dsp, DSP_RESET, 0);
1714 track_changed = true;
1715 playlist_update_resume_info(audio_current_track());
1718 /* Get track metadata if we don't already have it. */
1719 if (tracks[track_widx].id3_hid < 0)
1721 tracks[track_widx].id3_hid = bufopen(trackname, 0, TYPE_ID3);
1723 if (tracks[track_widx].id3_hid < 0)
1725 /* Buffer is full. */
1726 get_metadata(&lasttrack_id3, fd, trackname);
1727 last_peek_offset--;
1728 close(fd);
1729 logf("buffer is full for now");
1730 filling = STATE_FULL;
1731 return false;
1734 if (track_widx == track_ridx)
1736 /* TODO: Superfluos buffering call? */
1737 buf_request_buffer_handle(tracks[track_widx].id3_hid);
1738 copy_mp3entry(&curtrack_id3, bufgetid3(tracks[track_widx].id3_hid));
1739 curtrack_id3.offset = offset;
1742 if (start_play)
1744 track_changed = true;
1745 playlist_update_resume_info(audio_current_track());
1749 close(fd);
1750 track_load_started = true; /* Remember that we've started loading a track */
1751 return true;
1754 /* Second part of the track loading: We now have the metadata available, so we
1755 can load the codec, the album art and finally the audio data.
1756 This is called on the audio thread after the buffering thread calls the
1757 buffering_handle_finished_callback callback. */
1758 static void audio_finish_load_track(void)
1760 size_t file_offset = 0;
1761 size_t offset = 0;
1762 bool start_play = start_play_g;
1764 #if 0
1765 if (cuesheet_is_enabled() && tracks[track_widx].id3.cuesheet_type == 1)
1767 char cuepath[MAX_PATH];
1769 struct cuesheet *cue = start_play ? curr_cue : temp_cue;
1771 if (look_for_cuesheet_file(trackname, cuepath) &&
1772 parse_cuesheet(cuepath, cue))
1774 strcpy((cue)->audio_filename, trackname);
1775 if (start_play)
1776 cue_spoof_id3(curr_cue, &tracks[track_widx].id3);
1779 #endif
1781 track_load_started = false;
1783 if (tracks[track_widx].id3_hid < 0) {
1784 logf("no metatdata");
1785 return;
1788 struct mp3entry *track_id3;
1790 if (track_widx == track_ridx)
1791 track_id3 = &curtrack_id3;
1792 else
1793 track_id3 = bufgetid3(tracks[track_widx].id3_hid);
1795 if (track_id3->length == 0 && track_id3->filesize == 0)
1797 logf("audio_finish_load_track: invalid metadata");
1799 /* Invalid metadata */
1800 bufclose(tracks[track_widx].id3_hid);
1801 tracks[track_widx].id3_hid = -1;
1803 /* Skip invalid entry from playlist. */
1804 playlist_skip_entry(NULL, last_peek_offset--);
1806 /* load next track */
1807 LOGFQUEUE("audio > audio Q_AUDIO_FILL_BUFFER %d", (int)start_play);
1808 queue_post(&audio_queue, Q_AUDIO_FILL_BUFFER, start_play);
1810 return;
1813 #ifdef HAVE_ALBUMART
1814 if (tracks[track_widx].aa_hid < 0 && gui_sync_wps_uses_albumart())
1816 char aa_path[MAX_PATH];
1817 if (find_albumart(track_id3, aa_path, sizeof(aa_path)))
1818 tracks[track_widx].aa_hid = bufopen(aa_path, 0, TYPE_BITMAP);
1820 #endif
1822 /* Load the codec. */
1823 if (!audio_loadcodec(start_play))
1825 if (tracks[track_widx].codec_hid == ERR_BUFFER_FULL)
1827 /* No space for codec on buffer, not an error */
1828 return;
1831 /* This is an error condition, either no codec was found, or reading
1832 * the codec file failed part way through, either way, skip the track */
1833 /* FIXME: We should not use splashf from audio thread! */
1834 splashf(HZ*2, "No codec for: %s", track_id3->path);
1835 /* Skip invalid entry from playlist. */
1836 playlist_skip_entry(NULL, last_peek_offset);
1837 return;
1840 track_id3->elapsed = 0;
1841 offset = track_id3->offset;
1843 enum data_type type = TYPE_PACKET_AUDIO;
1845 switch (track_id3->codectype) {
1846 case AFMT_MPA_L1:
1847 case AFMT_MPA_L2:
1848 case AFMT_MPA_L3:
1849 if (offset > 0) {
1850 file_offset = offset;
1851 track_id3->offset = offset;
1853 break;
1855 case AFMT_WAVPACK:
1856 if (offset > 0) {
1857 file_offset = offset;
1858 track_id3->offset = offset;
1859 track_id3->elapsed = track_id3->length / 2;
1861 break;
1863 case AFMT_OGG_VORBIS:
1864 case AFMT_SPEEX:
1865 case AFMT_FLAC:
1866 case AFMT_PCM_WAV:
1867 case AFMT_A52:
1868 case AFMT_AAC:
1869 case AFMT_MPC:
1870 case AFMT_APE:
1871 case AFMT_WMA:
1872 if (offset > 0)
1873 track_id3->offset = offset;
1874 break;
1876 case AFMT_NSF:
1877 case AFMT_SPC:
1878 case AFMT_SID:
1879 logf("Loading atomic %d",track_id3->codectype);
1880 type = TYPE_ATOMIC_AUDIO;
1881 break;
1884 logf("alt:%s", track_id3->path);
1886 if (file_offset > AUDIO_REBUFFER_GUESS_SIZE)
1887 file_offset -= AUDIO_REBUFFER_GUESS_SIZE;
1888 else if (track_id3->first_frame_offset)
1889 file_offset = track_id3->first_frame_offset;
1890 else
1891 file_offset = 0;
1893 tracks[track_widx].audio_hid = bufopen(track_id3->path, file_offset, type);
1895 if (tracks[track_widx].audio_hid < 0)
1896 return;
1898 /* All required data is now available for the codec. */
1899 tracks[track_widx].taginfo_ready = true;
1901 if (start_play)
1903 ci.curpos=file_offset;
1904 buf_request_buffer_handle(tracks[track_widx].audio_hid);
1907 track_widx = (track_widx + 1) & MAX_TRACK_MASK;
1909 send_event(PLAYBACK_EVENT_TRACK_BUFFER, track_id3);
1911 /* load next track */
1912 LOGFQUEUE("audio > audio Q_AUDIO_FILL_BUFFER");
1913 queue_post(&audio_queue, Q_AUDIO_FILL_BUFFER, 0);
1915 return;
1918 static void audio_fill_file_buffer(bool start_play, size_t offset)
1920 bool had_next_track = audio_next_track() != NULL;
1922 filling = STATE_FILLING;
1923 trigger_cpu_boost();
1925 /* No need to rebuffer if there are track skips pending. */
1926 if (ci.new_track != 0)
1927 return;
1929 /* Must reset the buffer before use if trashed or voice only - voice
1930 file size shouldn't have changed so we can go straight from
1931 AUDIOBUF_STATE_VOICED_ONLY to AUDIOBUF_STATE_INITIALIZED */
1932 if (buffer_state != AUDIOBUF_STATE_INITIALIZED)
1933 audio_reset_buffer();
1935 logf("Starting buffer fill");
1937 if (!start_play)
1938 audio_clear_track_entries();
1940 /* Save the current resume position once. */
1941 playlist_update_resume_info(audio_current_track());
1943 audio_load_track(offset, start_play);
1945 if (!had_next_track && audio_next_track())
1946 track_changed = true;
1949 static void audio_rebuffer(void)
1951 logf("Forcing rebuffer");
1953 clear_track_info(CUR_TI);
1955 /* Reset track pointers */
1956 track_widx = track_ridx;
1957 audio_clear_track_entries();
1959 /* Reset a possibly interrupted track load */
1960 track_load_started = false;
1962 /* Fill the buffer */
1963 last_peek_offset = -1;
1964 ci.curpos = 0;
1966 if (!CUR_TI->taginfo_ready)
1967 memset(&curtrack_id3, 0, sizeof(struct mp3entry));
1969 audio_fill_file_buffer(false, 0);
1972 /* Called on request from the codec to get a new track. This is the codec part
1973 of the track transition. */
1974 static int audio_check_new_track(void)
1976 int track_count = audio_track_count();
1977 int old_track_ridx = track_ridx;
1978 int i, idx;
1979 bool forward;
1981 /* Now it's good time to send track finish events. */
1982 send_event(PLAYBACK_EVENT_TRACK_FINISH, &curtrack_id3);
1983 if (dir_skip)
1985 dir_skip = false;
1986 /* regardless of the return value we need to rebuffer.
1987 if it fails the old playlist will resume, else the
1988 next dir will start playing */
1989 playlist_next_dir(ci.new_track);
1990 ci.new_track = 0;
1991 audio_rebuffer();
1992 goto skip_done;
1995 if (new_playlist)
1996 ci.new_track = 0;
1998 /* If the playlist isn't that big */
1999 if (automatic_skip)
2001 while (!playlist_check(ci.new_track))
2003 if (ci.new_track >= 0)
2005 LOGFQUEUE("audio >|= codec Q_CODEC_REQUEST_FAILED");
2006 return Q_CODEC_REQUEST_FAILED;
2008 ci.new_track++;
2012 /* Update the playlist */
2013 last_peek_offset -= ci.new_track;
2015 if (playlist_next(ci.new_track) < 0)
2017 LOGFQUEUE("audio >|= codec Q_CODEC_REQUEST_FAILED");
2018 return Q_CODEC_REQUEST_FAILED;
2021 if (new_playlist)
2023 ci.new_track = 1;
2024 new_playlist = false;
2027 /* Save the track metadata to allow the WPS to display it
2028 while PCM finishes playing that track */
2029 copy_mp3entry(&prevtrack_id3, &curtrack_id3);
2031 /* Update the main buffer copy of the track metadata with the one
2032 the codec has been using (for the unbuffer callbacks) */
2033 if (CUR_TI->id3_hid >= 0)
2034 copy_mp3entry(bufgetid3(CUR_TI->id3_hid), &curtrack_id3);
2036 /* Save a pointer to the old track to allow later clearing */
2037 prev_ti = CUR_TI;
2039 for (i = 0; i < ci.new_track; i++)
2041 idx = (track_ridx + i) & MAX_TRACK_MASK;
2042 struct mp3entry *id3 = bufgetid3(tracks[idx].id3_hid);
2043 ssize_t offset = buf_handle_offset(tracks[idx].audio_hid);
2044 if (!id3 || offset < 0 || (unsigned)offset > id3->first_frame_offset)
2046 /* We don't have all the audio data for that track, so clear it,
2047 but keep the metadata. */
2048 if (tracks[idx].audio_hid >= 0 && bufclose(tracks[idx].audio_hid))
2050 tracks[idx].audio_hid = -1;
2051 tracks[idx].filesize = 0;
2056 /* Move to the new track */
2057 track_ridx = (track_ridx + ci.new_track) & MAX_TRACK_MASK;
2059 buf_set_base_handle(CUR_TI->audio_hid);
2061 if (automatic_skip)
2063 wps_offset = -ci.new_track;
2064 track_changed = true;
2067 /* If it is not safe to even skip this many track entries */
2068 if (ci.new_track >= track_count || ci.new_track <= track_count - MAX_TRACK)
2070 ci.new_track = 0;
2071 audio_rebuffer();
2072 goto skip_done;
2075 forward = ci.new_track > 0;
2076 ci.new_track = 0;
2078 /* If the target track is clearly not in memory */
2079 if (CUR_TI->filesize == 0 || !CUR_TI->taginfo_ready)
2081 audio_rebuffer();
2082 goto skip_done;
2085 /* When skipping backwards, it is possible that we've found a track that's
2086 * buffered, but which is around the track-wrap and therefore not the track
2087 * we are looking for */
2088 if (!forward)
2090 int cur_idx = track_ridx;
2091 bool taginfo_ready = true;
2092 /* We've wrapped the buffer backwards if new > old */
2093 bool wrap = track_ridx > old_track_ridx;
2095 while (1)
2097 cur_idx = (cur_idx + 1) & MAX_TRACK_MASK;
2099 /* if we've advanced past the wrap when cur_idx is zeroed */
2100 if (!cur_idx)
2101 wrap = false;
2103 /* if we aren't still on the wrap and we've caught the old track */
2104 if (!(wrap || cur_idx < old_track_ridx))
2105 break;
2107 /* If we hit a track in between without valid tag info, bail */
2108 if (!tracks[cur_idx].taginfo_ready)
2110 taginfo_ready = false;
2111 break;
2114 if (!taginfo_ready)
2116 audio_rebuffer();
2120 skip_done:
2121 audio_update_trackinfo();
2122 LOGFQUEUE("audio >|= codec Q_CODEC_REQUEST_COMPLETE");
2123 return Q_CODEC_REQUEST_COMPLETE;
2126 unsigned long audio_prev_elapsed(void)
2128 return prev_track_elapsed;
2131 static void audio_stop_codec_flush(void)
2133 ci.stop_codec = true;
2134 pcmbuf_pause(true);
2136 while (audio_codec_loaded)
2137 yield();
2139 /* If the audio codec is not loaded any more, and the audio is still
2140 * playing, it is now and _only_ now safe to call this function from the
2141 * audio thread */
2142 if (pcm_is_playing())
2144 pcmbuf_play_stop();
2145 pcmbuf_queue_clear();
2147 pcmbuf_pause(paused);
2150 static void audio_stop_playback(void)
2152 /* If we were playing, save resume information */
2153 if (playing)
2155 struct mp3entry *id3 = NULL;
2157 if (!ci.stop_codec)
2159 /* Set this early, the outside code yields and may allow the codec
2160 to try to wait for a reply on a buffer wait */
2161 ci.stop_codec = true;
2162 id3 = audio_current_track();
2165 /* Save the current playing spot, or NULL if the playlist has ended */
2166 playlist_update_resume_info(id3);
2168 /* TODO: Create auto bookmark too? */
2170 prev_track_elapsed = curtrack_id3.elapsed;
2172 remove_event(BUFFER_EVENT_BUFFER_LOW, buffering_low_buffer_callback);
2175 audio_stop_codec_flush();
2176 paused = false;
2177 playing = false;
2178 track_load_started = false;
2180 filling = STATE_IDLE;
2182 /* Mark all entries null. */
2183 audio_clear_track_entries();
2185 /* Close all tracks */
2186 audio_release_tracks();
2188 memset(&curtrack_id3, 0, sizeof(struct mp3entry));
2191 static void audio_play_start(size_t offset)
2193 int i;
2195 #if INPUT_SRC_CAPS != 0
2196 audio_set_input_source(AUDIO_SRC_PLAYBACK, SRCF_PLAYBACK);
2197 audio_set_output_source(AUDIO_SRC_PLAYBACK);
2198 #endif
2200 /* Wait for any previously playing audio to flush - TODO: Not necessary? */
2201 paused = false;
2202 audio_stop_codec_flush();
2204 track_changed = true;
2206 playing = true;
2207 track_load_started = false;
2209 ci.new_track = 0;
2210 ci.seek_time = 0;
2211 wps_offset = 0;
2213 sound_set_volume(global_settings.volume);
2214 track_widx = track_ridx = 0;
2216 /* Clear all track entries. */
2217 for (i = 0; i < MAX_TRACK; i++) {
2218 clear_track_info(&tracks[i]);
2221 last_peek_offset = -1;
2223 /* Officially playing */
2224 queue_reply(&audio_queue, 1);
2226 #ifdef HAVE_DISK_STORAGE
2227 set_filebuf_watermark(buffer_margin, 0);
2228 #endif
2230 audio_fill_file_buffer(true, offset);
2232 add_event(BUFFER_EVENT_BUFFER_LOW, false, buffering_low_buffer_callback);
2234 LOGFQUEUE("audio > audio Q_AUDIO_TRACK_CHANGED");
2235 queue_post(&audio_queue, Q_AUDIO_TRACK_CHANGED, 0);
2239 /* Invalidates all but currently playing track. */
2240 static void audio_invalidate_tracks(void)
2242 if (audio_have_tracks())
2244 last_peek_offset = 0;
2245 track_widx = track_ridx;
2247 /* Mark all other entries null (also buffered wrong metadata). */
2248 audio_clear_track_entries();
2250 track_widx = (track_widx + 1) & MAX_TRACK_MASK;
2252 audio_fill_file_buffer(false, 0);
2256 static void audio_new_playlist(void)
2258 /* Prepare to start a new fill from the beginning of the playlist */
2259 last_peek_offset = -1;
2260 if (audio_have_tracks())
2262 if (paused)
2263 skipped_during_pause = true;
2264 track_widx = track_ridx;
2265 audio_clear_track_entries();
2267 track_widx = (track_widx + 1) & MAX_TRACK_MASK;
2269 /* Mark the current track as invalid to prevent skipping back to it */
2270 CUR_TI->taginfo_ready = false;
2273 /* Signal the codec to initiate a track change forward */
2274 new_playlist = true;
2275 ci.new_track = 1;
2277 /* Officially playing */
2278 queue_reply(&audio_queue, 1);
2280 audio_fill_file_buffer(false, 0);
2283 /* Called on manual track skip */
2284 static void audio_initiate_track_change(long direction)
2286 logf("audio_initiate_track_change(%ld)", direction);
2288 ci.new_track += direction;
2289 wps_offset -= direction;
2290 if (paused)
2291 skipped_during_pause = true;
2294 /* Called on manual dir skip */
2295 static void audio_initiate_dir_change(long direction)
2297 dir_skip = true;
2298 ci.new_track = direction;
2299 if (paused)
2300 skipped_during_pause = true;
2303 /* Called when PCM track change is complete */
2304 static void audio_finalise_track_change(void)
2306 logf("audio_finalise_track_change");
2308 if (automatic_skip)
2310 wps_offset = 0;
2311 automatic_skip = false;
2313 /* Invalidate prevtrack_id3 */
2314 prevtrack_id3.path[0] = 0;
2316 if (prev_ti && prev_ti->audio_hid < 0)
2318 /* No audio left so we clear all the track info. */
2319 clear_track_info(prev_ti);
2322 if (prev_ti && prev_ti->id3_hid >= 0)
2324 /* Reset the elapsed time to force the progressbar to be empty if
2325 the user skips back to this track */
2326 bufgetid3(prev_ti->id3_hid)->elapsed = 0;
2330 send_event(PLAYBACK_EVENT_TRACK_CHANGE, &curtrack_id3);
2332 track_changed = true;
2333 playlist_update_resume_info(audio_current_track());
2337 * Layout audio buffer as follows - iram buffer depends on target:
2338 * [|SWAP:iram][|TALK]|FILE|GUARD|PCM|[SWAP:dram[|iram]|]
2340 static void audio_reset_buffer(void)
2342 /* see audio_get_recording_buffer if this is modified */
2343 logf("audio_reset_buffer");
2345 /* If the setup of anything allocated before the file buffer is
2346 changed, do check the adjustments after the buffer_alloc call
2347 as it will likely be affected and need sliding over */
2349 /* Initially set up file buffer as all space available */
2350 malloc_buf = audiobuf + talk_get_bufsize();
2351 /* Align the malloc buf to line size. Especially important to cf
2352 targets that do line reads/writes. */
2353 malloc_buf = (unsigned char *)(((uintptr_t)malloc_buf + 15) & ~15);
2354 filebuf = malloc_buf; /* filebuf line align implied */
2355 filebuflen = audiobufend - filebuf;
2357 filebuflen &= ~15;
2359 /* Subtract whatever the pcm buffer says it used plus the guard buffer */
2360 const size_t pcmbuf_size = pcmbuf_init(filebuf + filebuflen) +GUARD_BUFSIZE;
2361 #ifdef DEBUG
2362 if(pcmbuf_size > filebuflen)
2363 panicf("Not enough memory for pcmbuf_init() : %d > %d",
2364 (int)pcmbuf_size, (int)filebuflen);
2365 #endif
2366 filebuflen -= pcmbuf_size;
2368 /* Make sure filebuflen is a longword multiple after adjustment - filebuf
2369 will already be line aligned */
2370 filebuflen &= ~3;
2372 buffering_reset(filebuf, filebuflen);
2374 /* Clear any references to the file buffer */
2375 buffer_state = AUDIOBUF_STATE_INITIALIZED;
2377 #if defined(ROCKBOX_HAS_LOGF) && defined(LOGF_ENABLE)
2378 /* Make sure everything adds up - yes, some info is a bit redundant but
2379 aids viewing and the sumation of certain variables should add up to
2380 the location of others. */
2382 size_t pcmbufsize;
2383 const unsigned char *pcmbuf = pcmbuf_get_meminfo(&pcmbufsize);
2384 logf("mabuf: %08X", (unsigned)malloc_buf);
2385 logf("fbuf: %08X", (unsigned)filebuf);
2386 logf("fbufe: %08X", (unsigned)(filebuf + filebuflen));
2387 logf("gbuf: %08X", (unsigned)(filebuf + filebuflen));
2388 logf("gbufe: %08X", (unsigned)(filebuf + filebuflen + GUARD_BUFSIZE));
2389 logf("pcmb: %08X", (unsigned)pcmbuf);
2390 logf("pcmbe: %08X", (unsigned)(pcmbuf + pcmbufsize));
2392 #endif
2395 static void audio_thread(void)
2397 struct queue_event ev;
2399 pcm_postinit();
2401 audio_thread_ready = true;
2403 while (1)
2405 if (filling != STATE_FILLING) {
2406 cancel_cpu_boost();
2409 if (!pcmbuf_queue_scan(&ev))
2410 queue_wait_w_tmo(&audio_queue, &ev, HZ/2);
2412 switch (ev.id) {
2414 case Q_AUDIO_FILL_BUFFER:
2415 LOGFQUEUE("audio < Q_AUDIO_FILL_BUFFER %d", (int)ev.data);
2416 audio_fill_file_buffer((bool)ev.data, 0);
2417 break;
2419 case Q_AUDIO_FINISH_LOAD:
2420 LOGFQUEUE("audio < Q_AUDIO_FINISH_LOAD");
2421 audio_finish_load_track();
2422 break;
2424 case Q_AUDIO_PLAY:
2425 LOGFQUEUE("audio < Q_AUDIO_PLAY");
2426 if (playing && ev.data <= 0)
2427 audio_new_playlist();
2428 else
2430 audio_stop_playback();
2431 audio_play_start((size_t)ev.data);
2433 break;
2435 case Q_AUDIO_STOP:
2436 LOGFQUEUE("audio < Q_AUDIO_STOP");
2437 if (playing)
2438 audio_stop_playback();
2439 if (ev.data != 0)
2440 queue_clear(&audio_queue);
2441 break;
2443 case Q_AUDIO_PAUSE:
2444 LOGFQUEUE("audio < Q_AUDIO_PAUSE");
2445 if (!(bool) ev.data && skipped_during_pause && !pcmbuf_is_crossfade_active())
2446 pcmbuf_play_stop(); /* Flush old track on resume after skip */
2447 skipped_during_pause = false;
2448 if (!playing)
2449 break;
2450 pcmbuf_pause((bool)ev.data);
2451 paused = (bool)ev.data;
2452 break;
2454 case Q_AUDIO_SKIP:
2455 LOGFQUEUE("audio < Q_AUDIO_SKIP");
2456 audio_initiate_track_change((long)ev.data);
2457 break;
2459 case Q_AUDIO_PRE_FF_REWIND:
2460 LOGFQUEUE("audio < Q_AUDIO_PRE_FF_REWIND");
2461 if (!playing)
2462 break;
2463 pcmbuf_pause(true);
2464 break;
2466 case Q_AUDIO_FF_REWIND:
2467 LOGFQUEUE("audio < Q_AUDIO_FF_REWIND");
2468 if (!playing)
2469 break;
2470 if (automatic_skip)
2472 /* An automatic track skip is in progress. Finalize it,
2473 then go back to the previous track */
2474 audio_finalise_track_change();
2475 ci.new_track = -1;
2477 ci.seek_time = (long)ev.data+1;
2478 break;
2480 case Q_AUDIO_CHECK_NEW_TRACK:
2481 LOGFQUEUE("audio < Q_AUDIO_CHECK_NEW_TRACK");
2482 queue_reply(&audio_queue, audio_check_new_track());
2483 break;
2485 case Q_AUDIO_DIR_SKIP:
2486 LOGFQUEUE("audio < Q_AUDIO_DIR_SKIP");
2487 audio_initiate_dir_change(ev.data);
2488 break;
2490 case Q_AUDIO_FLUSH:
2491 LOGFQUEUE("audio < Q_AUDIO_FLUSH");
2492 audio_invalidate_tracks();
2493 break;
2495 case Q_AUDIO_TRACK_CHANGED:
2496 /* PCM track change done */
2497 LOGFQUEUE("audio < Q_AUDIO_TRACK_CHANGED");
2498 audio_finalise_track_change();
2499 break;
2501 #ifndef SIMULATOR
2502 case SYS_USB_CONNECTED:
2503 LOGFQUEUE("audio < SYS_USB_CONNECTED");
2504 if (playing)
2505 audio_stop_playback();
2506 #ifdef PLAYBACK_VOICE
2507 voice_stop();
2508 #endif
2509 usb_acknowledge(SYS_USB_CONNECTED_ACK);
2510 usb_wait_for_disconnect(&audio_queue);
2512 /* Mark all entries null. */
2513 audio_clear_track_entries();
2515 /* release tracks to make sure all handles are closed */
2516 audio_release_tracks();
2517 break;
2518 #endif
2520 case SYS_TIMEOUT:
2521 LOGFQUEUE_SYS_TIMEOUT("audio < SYS_TIMEOUT");
2522 break;
2524 default:
2525 LOGFQUEUE("audio < default");
2526 break;
2527 } /* end switch */
2528 } /* end while */
2531 /* Initialize the audio system - called from init() in main.c.
2532 * Last function because of all the references to internal symbols
2534 void audio_init(void)
2536 unsigned int audio_thread_id;
2538 /* Can never do this twice */
2539 if (audio_is_initialized)
2541 logf("audio: already initialized");
2542 return;
2545 logf("audio: initializing");
2547 /* Initialize queues before giving control elsewhere in case it likes
2548 to send messages. Thread creation will be delayed however so nothing
2549 starts running until ready if something yields such as talk_init. */
2550 queue_init(&audio_queue, true);
2551 queue_init(&codec_queue, false);
2552 queue_init(&pcmbuf_queue, false);
2554 pcm_init();
2556 /* Initialize codec api. */
2557 ci.read_filebuf = codec_filebuf_callback;
2558 ci.pcmbuf_insert = codec_pcmbuf_insert_callback;
2559 ci.codec_get_buffer = codec_get_buffer;
2560 ci.request_buffer = codec_request_buffer_callback;
2561 ci.advance_buffer = codec_advance_buffer_callback;
2562 ci.advance_buffer_loc = codec_advance_buffer_loc_callback;
2563 ci.request_next_track = codec_request_next_track_callback;
2564 ci.seek_buffer = codec_seek_buffer_callback;
2565 ci.seek_complete = codec_seek_complete_callback;
2566 ci.set_elapsed = codec_set_elapsed_callback;
2567 ci.set_offset = codec_set_offset_callback;
2568 ci.configure = codec_configure_callback;
2569 ci.discard_codec = codec_discard_codec_callback;
2570 ci.dsp = (struct dsp_config *)dsp_configure(NULL, DSP_MYDSP,
2571 CODEC_IDX_AUDIO);
2573 /* initialize the buffer */
2574 filebuf = audiobuf;
2576 /* audio_reset_buffer must to know the size of voice buffer so init
2577 talk first */
2578 talk_init();
2580 codec_thread_id = create_thread(
2581 codec_thread, codec_stack, sizeof(codec_stack),
2582 CREATE_THREAD_FROZEN,
2583 codec_thread_name IF_PRIO(, PRIORITY_PLAYBACK)
2584 IF_COP(, CPU));
2586 queue_enable_queue_send(&codec_queue, &codec_queue_sender_list,
2587 codec_thread_id);
2589 audio_thread_id = create_thread(audio_thread, audio_stack,
2590 sizeof(audio_stack), CREATE_THREAD_FROZEN,
2591 audio_thread_name IF_PRIO(, PRIORITY_USER_INTERFACE)
2592 IF_COP(, CPU));
2594 queue_enable_queue_send(&audio_queue, &audio_queue_sender_list,
2595 audio_thread_id);
2597 #ifdef PLAYBACK_VOICE
2598 voice_thread_init();
2599 #endif
2601 /* Set crossfade setting for next buffer init which should be about... */
2602 pcmbuf_crossfade_enable(global_settings.crossfade);
2604 /* initialize the buffering system */
2606 buffering_init();
2607 /* ...now! Set up the buffers */
2608 audio_reset_buffer();
2610 int i;
2611 for(i = 0; i < MAX_TRACK; i++)
2613 tracks[i].audio_hid = -1;
2614 tracks[i].id3_hid = -1;
2615 tracks[i].codec_hid = -1;
2616 #ifdef HAVE_ALBUMART
2617 tracks[i].aa_hid = -1;
2618 #endif
2621 add_event(BUFFER_EVENT_REBUFFER, false, buffering_handle_rebuffer_callback);
2622 add_event(BUFFER_EVENT_FINISHED, false, buffering_handle_finished_callback);
2624 /* Probably safe to say */
2625 audio_is_initialized = true;
2627 sound_settings_apply();
2628 #ifdef HAVE_DISK_STORAGE
2629 audio_set_buffer_margin(global_settings.buffer_margin);
2630 #endif
2632 /* it's safe to let the threads run now */
2633 #ifdef PLAYBACK_VOICE
2634 voice_thread_resume();
2635 #endif
2636 thread_thaw(codec_thread_id);
2637 thread_thaw(audio_thread_id);
2639 } /* audio_init */
2641 bool audio_is_thread_ready(void)
2643 return audio_thread_ready;