Fixed m200v4 red build.
[kugel-rb.git] / apps / playback.c
blob0f76666c1ee232ef76b56c5dc5f67ad2e060e6a9
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
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 #if MEM > 1
164 #define MAX_TRACK 128
165 #else
166 #define MAX_TRACK 32
167 #endif
169 #define MAX_TRACK_MASK (MAX_TRACK-1)
171 /* As defined in plugins/lib/xxx2wav.h */
172 #if MEM > 1
173 #define GUARD_BUFSIZE (32*1024)
174 #else
175 #define GUARD_BUFSIZE (8*1024)
176 #endif
178 /* As defined in plugin.lds */
179 #if defined(CPU_PP)
180 #define CODEC_IRAM_ORIGIN ((unsigned char *)0x4000c000)
181 #define CODEC_IRAM_SIZE ((size_t)0xc000)
182 #elif defined(IAUDIO_X5) || defined(IAUDIO_M5)
183 #define CODEC_IRAM_ORIGIN ((unsigned char *)0x10010000)
184 #define CODEC_IRAM_SIZE ((size_t)0x10000)
185 #else
186 #define CODEC_IRAM_ORIGIN ((unsigned char *)0x1000c000)
187 #define CODEC_IRAM_SIZE ((size_t)0xc000)
188 #endif
190 bool audio_is_initialized = false;
191 static bool audio_thread_ready SHAREDBSS_ATTR = false;
193 /* Variables are commented with the threads that use them: *
194 * A=audio, C=codec, V=voice. A suffix of - indicates that *
195 * the variable is read but not updated on that thread. */
196 /* TBD: Split out "audio" and "playback" (ie. calling) threads */
198 /* Main state control */
199 static volatile bool audio_codec_loaded SHAREDBSS_ATTR = false; /* Codec loaded? (C/A-) */
200 static volatile bool playing SHAREDBSS_ATTR = false; /* Is audio playing? (A) */
201 static volatile bool paused SHAREDBSS_ATTR = false; /* Is audio paused? (A/C-) */
203 /* Ring buffer where compressed audio and codecs are loaded */
204 static unsigned char *filebuf = NULL; /* Start of buffer (A/C-) */
205 static unsigned char *malloc_buf = NULL; /* Start of malloc buffer (A/C-) */
206 /* FIXME: make filebuflen static */
207 size_t filebuflen = 0; /* Size of buffer (A/C-) */
208 /* FIXME: make buf_ridx (C/A-) */
210 /* Possible arrangements of the buffer */
211 static int buffer_state = AUDIOBUF_STATE_TRASHED; /* Buffer state */
213 /* Used to keep the WPS up-to-date during track transtition */
214 static struct mp3entry prevtrack_id3;
216 /* Used to provide the codec with a pointer */
217 static struct mp3entry curtrack_id3;
219 /* Used to make next track info available while playing last track on buffer */
220 static struct mp3entry lasttrack_id3;
222 /* Track info structure about songs in the file buffer (A/C-) */
223 struct track_info {
224 int audio_hid; /* The ID for the track's buffer handle */
225 int id3_hid; /* The ID for the track's metadata handle */
226 int codec_hid; /* The ID for the track's codec handle */
227 #ifdef HAVE_ALBUMART
228 int aa_hid; /* The ID for the track's album art handle */
229 #endif
231 size_t filesize; /* File total length */
233 bool taginfo_ready; /* Is metadata read */
236 static struct track_info tracks[MAX_TRACK];
237 static volatile int track_ridx = 0; /* Track being decoded (A/C-) */
238 static int track_widx = 0; /* Track being buffered (A) */
240 #define CUR_TI (&tracks[track_ridx]) /* Playing track info pointer (A/C-) */
241 static struct track_info *prev_ti = NULL; /* Pointer to the previously played
242 track */
244 /* Set by the audio thread when the current track information has updated
245 * and the WPS may need to update its cached information */
246 static bool track_changed = false;
248 /* Information used only for filling the buffer */
249 /* Playlist steps from playing track to next track to be buffered (A) */
250 static int last_peek_offset = 0;
252 /* Scrobbler support */
253 static unsigned long prev_track_elapsed = 0; /* Previous track elapsed time (C/A-)*/
255 static enum filling_state filling;
257 /* Track change controls */
258 static bool automatic_skip = false; /* Who initiated in-progress skip? (C/A-) */
259 static bool dir_skip = false; /* Is a directory skip pending? (A) */
260 static bool new_playlist = false; /* Are we starting a new playlist? (A) */
261 static int wps_offset = 0; /* Pending track change offset, to keep WPS responsive (A) */
262 static bool skipped_during_pause = false; /* Do we need to clear the PCM buffer when playback resumes (A) */
264 static bool start_play_g = false; /* Used by audio_load_track to notify
265 audio_finish_load_track about start_play */
267 /* True when a track load is in progress, i.e. audio_load_track() has returned
268 * but audio_finish_load_track() hasn't been called yet. Used to avoid allowing
269 * audio_load_track() to get called twice in a row, which would cause problems.
271 static bool track_load_started = false;
273 /* Set to true if the codec thread should send an audio stop request
274 * (typically because the end of the playlist has been reached).
276 static bool codec_requested_stop = false;
278 static size_t buffer_margin = 0; /* Buffer margin aka anti-skip buffer (A/C-) */
280 /* Multiple threads */
281 /* Set the watermark to trigger buffer fill (A/C) FIXME */
282 static void set_filebuf_watermark(int seconds, size_t max);
284 /* Audio thread */
285 static struct event_queue audio_queue SHAREDBSS_ATTR;
286 static struct queue_sender_list audio_queue_sender_list SHAREDBSS_ATTR;
287 static long audio_stack[(DEFAULT_STACK_SIZE + 0x1000)/sizeof(long)];
288 static const char audio_thread_name[] = "audio";
290 static void audio_thread(void);
291 static void audio_initiate_track_change(long direction);
292 static bool audio_have_tracks(void);
293 static void audio_reset_buffer(void);
294 static void audio_stop_playback(void);
296 /* Codec thread */
297 extern struct codec_api ci;
298 static struct event_queue codec_queue SHAREDBSS_ATTR;
299 static struct queue_sender_list codec_queue_sender_list;
300 static long codec_stack[(DEFAULT_STACK_SIZE + 0x2000)/sizeof(long)]
301 IBSS_ATTR;
302 static const char codec_thread_name[] = "codec";
303 unsigned int codec_thread_id; /* For modifying thread priority later. */
305 /* PCM buffer messaging */
306 static struct event_queue pcmbuf_queue SHAREDBSS_ATTR;
308 /* Function to be called by pcm buffer callbacks.
309 * Permissible Context(s): Audio interrupt
311 static void pcmbuf_callback_queue_post(long id, intptr_t data)
313 /* No lock since we're already in audio interrupt context */
314 queue_post(&pcmbuf_queue, id, data);
317 /* Scan the pcmbuf queue and return true if a message pulled.
318 * Permissible Context(s): Thread
320 static bool pcmbuf_queue_scan(struct queue_event *ev)
322 if (!queue_empty(&pcmbuf_queue))
324 /* Transfer message to audio queue */
325 pcm_play_lock();
326 /* Pull message - never, ever any blocking call! */
327 queue_wait_w_tmo(&pcmbuf_queue, ev, 0);
328 pcm_play_unlock();
329 return true;
332 return false;
335 /* Clear the pcmbuf queue of messages
336 * Permissible Context(s): Thread
338 static void pcmbuf_queue_clear(void)
340 pcm_play_lock();
341 queue_clear(&pcmbuf_queue);
342 pcm_play_unlock();
345 /* --- Helper functions --- */
347 static struct mp3entry *bufgetid3(int handle_id)
349 if (handle_id < 0)
350 return NULL;
352 struct mp3entry *id3;
353 ssize_t ret = bufgetdata(handle_id, 0, (void *)&id3);
355 if (ret < 0 || ret != sizeof(struct mp3entry))
356 return NULL;
358 return id3;
361 static bool clear_track_info(struct track_info *track)
363 /* bufclose returns true if the handle is not found, or if it is closed
364 * successfully, so these checks are safe on non-existant handles */
365 if (!track)
366 return false;
368 if (track->codec_hid >= 0) {
369 if (bufclose(track->codec_hid))
370 track->codec_hid = -1;
371 else
372 return false;
375 if (track->id3_hid >= 0) {
376 if (bufclose(track->id3_hid))
377 track->id3_hid = -1;
378 else
379 return false;
382 if (track->audio_hid >= 0) {
383 if (bufclose(track->audio_hid))
384 track->audio_hid = -1;
385 else
386 return false;
389 #ifdef HAVE_ALBUMART
390 if (track->aa_hid >= 0) {
391 if (bufclose(track->aa_hid))
392 track->aa_hid = -1;
393 else
394 return false;
396 #endif
398 track->filesize = 0;
399 track->taginfo_ready = false;
401 return true;
404 /* --- External interfaces --- */
406 /* This sends a stop message and the audio thread will dump all it's
407 subsequenct messages */
408 void audio_hard_stop(void)
410 /* Stop playback */
411 LOGFQUEUE("audio >| audio Q_AUDIO_STOP: 1");
412 queue_send(&audio_queue, Q_AUDIO_STOP, 1);
413 #ifdef PLAYBACK_VOICE
414 voice_stop();
415 #endif
418 bool audio_restore_playback(int type)
420 switch (type)
422 case AUDIO_WANT_PLAYBACK:
423 if (buffer_state != AUDIOBUF_STATE_INITIALIZED)
424 audio_reset_buffer();
425 return true;
426 case AUDIO_WANT_VOICE:
427 if (buffer_state == AUDIOBUF_STATE_TRASHED)
428 audio_reset_buffer();
429 return true;
430 default:
431 return false;
435 unsigned char *audio_get_buffer(bool talk_buf, size_t *buffer_size)
437 unsigned char *buf, *end;
439 if (audio_is_initialized)
441 audio_hard_stop();
443 /* else buffer_state will be AUDIOBUF_STATE_TRASHED at this point */
445 if (buffer_size == NULL)
447 /* Special case for talk_init to use since it already knows it's
448 trashed */
449 buffer_state = AUDIOBUF_STATE_TRASHED;
450 return NULL;
453 if (talk_buf || buffer_state == AUDIOBUF_STATE_TRASHED
454 || !talk_voice_required())
456 logf("get buffer: talk, audio");
457 /* Ok to use everything from audiobuf to audiobufend - voice is loaded,
458 the talk buffer is not needed because voice isn't being used, or
459 could be AUDIOBUF_STATE_TRASHED already. If state is
460 AUDIOBUF_STATE_VOICED_ONLY, no problem as long as memory isn't written
461 without the caller knowing what's going on. Changing certain settings
462 may move it to a worse condition but the memory in use by something
463 else will remain undisturbed.
465 if (buffer_state != AUDIOBUF_STATE_TRASHED)
467 talk_buffer_steal();
468 buffer_state = AUDIOBUF_STATE_TRASHED;
471 buf = audiobuf;
472 end = audiobufend;
474 else
476 /* Safe to just return this if already AUDIOBUF_STATE_VOICED_ONLY or
477 still AUDIOBUF_STATE_INITIALIZED */
478 /* Skip talk buffer and move pcm buffer to end to maximize available
479 contiguous memory - no audio running means voice will not need the
480 swap space */
481 logf("get buffer: audio");
482 buf = audiobuf + talk_get_bufsize();
483 end = audiobufend - pcmbuf_init(audiobufend);
484 buffer_state = AUDIOBUF_STATE_VOICED_ONLY;
487 *buffer_size = end - buf;
489 return buf;
492 int audio_buffer_state(void)
494 return buffer_state;
497 #ifdef HAVE_RECORDING
498 unsigned char *audio_get_recording_buffer(size_t *buffer_size)
500 /* Stop audio, voice and obtain all available buffer space */
501 audio_hard_stop();
502 talk_buffer_steal();
504 unsigned char *end = audiobufend;
505 buffer_state = AUDIOBUF_STATE_TRASHED;
506 *buffer_size = end - audiobuf;
508 return (unsigned char *)audiobuf;
511 bool audio_load_encoder(int afmt)
513 #ifndef SIMULATOR
514 const char *enc_fn = get_codec_filename(afmt | CODEC_TYPE_ENCODER);
515 if (!enc_fn)
516 return false;
518 audio_remove_encoder();
519 ci.enc_codec_loaded = 0; /* clear any previous error condition */
521 LOGFQUEUE("codec > Q_ENCODER_LOAD_DISK");
522 queue_post(&codec_queue, Q_ENCODER_LOAD_DISK, (intptr_t)enc_fn);
524 while (ci.enc_codec_loaded == 0)
525 yield();
527 logf("codec loaded: %d", ci.enc_codec_loaded);
529 return ci.enc_codec_loaded > 0;
530 #else
531 (void)afmt;
532 return true;
533 #endif
534 } /* audio_load_encoder */
536 void audio_remove_encoder(void)
538 #ifndef SIMULATOR
539 /* force encoder codec unload (if currently loaded) */
540 if (ci.enc_codec_loaded <= 0)
541 return;
543 ci.stop_encoder = true;
544 while (ci.enc_codec_loaded > 0)
545 yield();
546 #endif
547 } /* audio_remove_encoder */
549 #endif /* HAVE_RECORDING */
551 #ifdef HAVE_ALBUMART
552 int audio_current_aa_hid(void)
554 int cur_idx;
555 int offset = ci.new_track + wps_offset;
557 cur_idx = track_ridx + offset;
558 cur_idx &= MAX_TRACK_MASK;
560 return tracks[cur_idx].aa_hid;
562 #endif
564 struct mp3entry* audio_current_track(void)
566 const char *filename;
567 static struct mp3entry temp_id3;
568 struct playlist_track_info trackinfo;
569 int cur_idx;
570 int offset = ci.new_track + wps_offset;
572 cur_idx = (track_ridx + offset) & MAX_TRACK_MASK;
574 if (cur_idx == track_ridx && *curtrack_id3.path)
576 /* The usual case */
577 return &curtrack_id3;
579 else if (automatic_skip && offset == -1 && *prevtrack_id3.path)
581 /* We're in a track transition. The codec has moved on to the nex track,
582 but the audio being played is still the same (now previous) track.
583 prevtrack_id3.elapsed is being updated in an ISR by
584 codec_pcmbuf_position_callback */
585 return &prevtrack_id3;
587 else if (tracks[cur_idx].id3_hid >= 0)
589 /* Get the ID3 metadata from the main buffer */
590 struct mp3entry *ret = bufgetid3(tracks[cur_idx].id3_hid);
591 if (ret) return ret;
594 /* We didn't find the ID3 metadata, so we fill temp_id3 with the little info
595 we have and return that. */
597 memset(&temp_id3, 0, sizeof(struct mp3entry));
599 playlist_get_track_info(NULL, playlist_next(0)+wps_offset, &trackinfo);
600 filename = trackinfo.filename;
601 if (!filename)
602 filename = "No file!";
604 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
605 if (tagcache_fill_tags(&temp_id3, filename))
606 return &temp_id3;
607 #endif
609 strncpy(temp_id3.path, filename, sizeof(temp_id3.path)-1);
610 temp_id3.title = strrchr(temp_id3.path, '/');
611 if (!temp_id3.title)
612 temp_id3.title = &temp_id3.path[0];
613 else
614 temp_id3.title++;
616 return &temp_id3;
619 struct mp3entry* audio_next_track(void)
621 int next_idx;
622 int offset = ci.new_track + wps_offset;
624 if (!audio_have_tracks())
625 return NULL;
627 if (wps_offset == -1 && *prevtrack_id3.path)
629 /* We're in a track transition. The next track for the WPS is the one
630 currently being decoded. */
631 return &curtrack_id3;
634 next_idx = (track_ridx + offset + 1) & MAX_TRACK_MASK;
636 if (tracks[next_idx].id3_hid >= 0)
637 return bufgetid3(tracks[next_idx].id3_hid);
639 if (next_idx == track_widx)
641 /* The next track hasn't been buffered yet, so we return the static
642 version of its metadata. */
643 return &lasttrack_id3;
646 return NULL;
649 bool audio_has_changed_track(void)
651 if (track_changed)
653 #ifdef IPOD_ACCESSORY_PROTOCOL
654 iap_track_changed();
655 #endif
656 track_changed = false;
657 return true;
660 return false;
663 void audio_play(long offset)
665 logf("audio_play");
667 #ifdef PLAYBACK_VOICE
668 /* Truncate any existing voice output so we don't have spelling
669 * etc. over the first part of the played track */
670 talk_force_shutup();
671 #endif
673 /* Start playback */
674 LOGFQUEUE("audio >| audio Q_AUDIO_PLAY: %ld", offset);
675 /* Don't return until playback has actually started */
676 queue_send(&audio_queue, Q_AUDIO_PLAY, offset);
679 void audio_stop(void)
681 /* Stop playback */
682 LOGFQUEUE("audio >| audio Q_AUDIO_STOP");
683 /* Don't return until playback has actually stopped */
684 queue_send(&audio_queue, Q_AUDIO_STOP, 0);
687 void audio_pause(void)
689 LOGFQUEUE("audio >| audio Q_AUDIO_PAUSE");
690 /* Don't return until playback has actually paused */
691 queue_send(&audio_queue, Q_AUDIO_PAUSE, true);
694 void audio_resume(void)
696 LOGFQUEUE("audio >| audio Q_AUDIO_PAUSE resume");
697 /* Don't return until playback has actually resumed */
698 queue_send(&audio_queue, Q_AUDIO_PAUSE, false);
701 void audio_skip(int direction)
703 if (playlist_check(ci.new_track + wps_offset + direction))
705 if (global_settings.beep)
706 pcmbuf_beep(2000, 100, 2500*global_settings.beep);
708 LOGFQUEUE("audio > audio Q_AUDIO_SKIP %d", direction);
709 queue_post(&audio_queue, Q_AUDIO_SKIP, direction);
710 /* Update wps while our message travels inside deep playback queues. */
711 wps_offset += direction;
712 track_changed = true;
714 else
716 /* No more tracks. */
717 if (global_settings.beep)
718 pcmbuf_beep(1000, 100, 1500*global_settings.beep);
722 void audio_next(void)
724 audio_skip(1);
727 void audio_prev(void)
729 audio_skip(-1);
732 void audio_next_dir(void)
734 LOGFQUEUE("audio > audio Q_AUDIO_DIR_SKIP 1");
735 queue_post(&audio_queue, Q_AUDIO_DIR_SKIP, 1);
738 void audio_prev_dir(void)
740 LOGFQUEUE("audio > audio Q_AUDIO_DIR_SKIP -1");
741 queue_post(&audio_queue, Q_AUDIO_DIR_SKIP, -1);
744 void audio_pre_ff_rewind(void)
746 LOGFQUEUE("audio > audio Q_AUDIO_PRE_FF_REWIND");
747 queue_post(&audio_queue, Q_AUDIO_PRE_FF_REWIND, 0);
750 void audio_ff_rewind(long newpos)
752 LOGFQUEUE("audio > audio Q_AUDIO_FF_REWIND");
753 queue_post(&audio_queue, Q_AUDIO_FF_REWIND, newpos);
756 void audio_flush_and_reload_tracks(void)
758 LOGFQUEUE("audio > audio Q_AUDIO_FLUSH");
759 queue_post(&audio_queue, Q_AUDIO_FLUSH, 0);
762 void audio_error_clear(void)
764 #ifdef AUDIO_HAVE_RECORDING
765 pcm_rec_error_clear();
766 #endif
769 int audio_status(void)
771 int ret = 0;
773 if (playing)
774 ret |= AUDIO_STATUS_PLAY;
776 if (paused)
777 ret |= AUDIO_STATUS_PAUSE;
779 #ifdef HAVE_RECORDING
780 /* Do this here for constitency with mpeg.c version */
781 ret |= pcm_rec_status();
782 #endif
784 return ret;
787 int audio_get_file_pos(void)
789 return 0;
792 #ifdef HAVE_DISK_STORAGE
793 void audio_set_buffer_margin(int setting)
795 static const int lookup[] = {5, 15, 30, 60, 120, 180, 300, 600};
796 buffer_margin = lookup[setting];
797 logf("buffer margin: %ld", (long)buffer_margin);
798 set_filebuf_watermark(buffer_margin, 0);
800 #endif
802 /* Take necessary steps to enable or disable the crossfade setting */
803 void audio_set_crossfade(int enable)
805 size_t offset;
806 bool was_playing;
807 size_t size;
809 /* Tell it the next setting to use */
810 pcmbuf_crossfade_enable(enable);
812 /* Return if size hasn't changed or this is too early to determine
813 which in the second case there's no way we could be playing
814 anything at all */
815 if (pcmbuf_is_same_size())
817 /* This function is a copout and just syncs some variables -
818 to be removed at a later date */
819 pcmbuf_crossfade_enable_finished();
820 return;
823 offset = 0;
824 was_playing = playing;
826 /* Playback has to be stopped before changing the buffer size */
827 if (was_playing)
829 /* Store the track resume position */
830 offset = curtrack_id3.offset;
833 /* Blast it - audio buffer will have to be setup again next time
834 something plays */
835 audio_get_buffer(true, &size);
837 /* Restart playback if audio was running previously */
838 if (was_playing)
839 audio_play(offset);
842 /* --- Routines called from multiple threads --- */
844 static void set_filebuf_watermark(int seconds, size_t max)
846 size_t bytes;
848 if (!filebuf)
849 return; /* Audio buffers not yet set up */
851 bytes = seconds?MAX(curtrack_id3.bitrate * seconds * (1000/8), max):max;
852 bytes = MIN(bytes, filebuflen / 2);
853 buf_set_watermark(bytes);
856 const char *get_codec_filename(int cod_spec)
858 const char *fname;
860 #ifdef HAVE_RECORDING
861 /* Can choose decoder or encoder if one available */
862 int type = cod_spec & CODEC_TYPE_MASK;
863 int afmt = cod_spec & CODEC_AFMT_MASK;
865 if ((unsigned)afmt >= AFMT_NUM_CODECS)
866 type = AFMT_UNKNOWN | (type & CODEC_TYPE_MASK);
868 fname = (type == CODEC_TYPE_ENCODER) ?
869 audio_formats[afmt].codec_enc_root_fn :
870 audio_formats[afmt].codec_root_fn;
872 logf("%s: %d - %s",
873 (type == CODEC_TYPE_ENCODER) ? "Encoder" : "Decoder",
874 afmt, fname ? fname : "<unknown>");
875 #else /* !HAVE_RECORDING */
876 /* Always decoder */
877 if ((unsigned)cod_spec >= AFMT_NUM_CODECS)
878 cod_spec = AFMT_UNKNOWN;
879 fname = audio_formats[cod_spec].codec_root_fn;
880 logf("Codec: %d - %s", cod_spec, fname ? fname : "<unknown>");
881 #endif /* HAVE_RECORDING */
883 return fname;
884 } /* get_codec_filename */
886 /* --- Codec thread --- */
887 static bool codec_pcmbuf_insert_callback(
888 const void *ch1, const void *ch2, int count)
890 const char *src[2] = { ch1, ch2 };
892 while (count > 0)
894 int out_count = dsp_output_count(ci.dsp, count);
895 int inp_count;
896 char *dest;
898 /* Prevent audio from a previous track from playing */
899 if (ci.new_track || ci.stop_codec)
900 return true;
902 while ((dest = pcmbuf_request_buffer(&out_count)) == NULL)
904 cancel_cpu_boost();
905 sleep(1);
906 if (ci.seek_time || ci.new_track || ci.stop_codec)
907 return true;
910 /* Get the real input_size for output_size bytes, guarding
911 * against resampling buffer overflows. */
912 inp_count = dsp_input_count(ci.dsp, out_count);
914 if (inp_count <= 0)
915 return true;
917 /* Input size has grown, no error, just don't write more than length */
918 if (inp_count > count)
919 inp_count = count;
921 out_count = dsp_process(ci.dsp, dest, src, inp_count);
923 if (out_count <= 0)
924 return true;
926 pcmbuf_write_complete(out_count);
928 count -= inp_count;
931 return true;
932 } /* codec_pcmbuf_insert_callback */
934 static void* codec_get_buffer(size_t *size)
936 if (codec_size >= CODEC_SIZE)
937 return NULL;
938 *size = CODEC_SIZE - codec_size;
939 return &codecbuf[codec_size];
942 /* Between the codec and PCM track change, we need to keep updating the
943 "elapsed" value of the previous (to the codec, but current to the
944 user/PCM/WPS) track, so that the progressbar reaches the end.
945 During that transition, the WPS will display prevtrack_id3. */
946 static void codec_pcmbuf_position_callback(size_t size) ICODE_ATTR;
947 static void codec_pcmbuf_position_callback(size_t size)
949 /* This is called from an ISR, so be quick */
950 unsigned int time = size * 1000 / 4 / NATIVE_FREQUENCY +
951 prevtrack_id3.elapsed;
953 if (time >= prevtrack_id3.length)
955 pcmbuf_set_position_callback(NULL);
956 prevtrack_id3.elapsed = prevtrack_id3.length;
958 else
959 prevtrack_id3.elapsed = time;
962 static void codec_set_elapsed_callback(unsigned int value)
964 unsigned int latency;
965 if (ci.seek_time)
966 return;
968 #ifdef AB_REPEAT_ENABLE
969 ab_position_report(value);
970 #endif
972 latency = pcmbuf_get_latency();
973 if (value < latency)
974 curtrack_id3.elapsed = 0;
975 else if (value - latency > curtrack_id3.elapsed ||
976 value - latency < curtrack_id3.elapsed - 2)
978 curtrack_id3.elapsed = value - latency;
982 static void codec_set_offset_callback(size_t value)
984 unsigned int latency;
986 if (ci.seek_time)
987 return;
989 latency = pcmbuf_get_latency() * curtrack_id3.bitrate / 8;
990 if (value < latency)
991 curtrack_id3.offset = 0;
992 else
993 curtrack_id3.offset = value - latency;
996 static void codec_advance_buffer_counters(size_t amount)
998 bufadvance(CUR_TI->audio_hid, amount);
999 ci.curpos += amount;
1002 /* copy up-to size bytes into ptr and return the actual size copied */
1003 static size_t codec_filebuf_callback(void *ptr, size_t size)
1005 ssize_t copy_n;
1007 if (ci.stop_codec || !playing)
1008 return 0;
1010 copy_n = bufread(CUR_TI->audio_hid, size, ptr);
1012 /* Nothing requested OR nothing left */
1013 if (copy_n == 0)
1014 return 0;
1016 /* Update read and other position pointers */
1017 codec_advance_buffer_counters(copy_n);
1019 /* Return the actual amount of data copied to the buffer */
1020 return copy_n;
1021 } /* codec_filebuf_callback */
1023 static void* codec_request_buffer_callback(size_t *realsize, size_t reqsize)
1025 size_t copy_n = reqsize;
1026 ssize_t ret;
1027 void *ptr;
1029 if (!playing)
1031 *realsize = 0;
1032 return NULL;
1035 ret = bufgetdata(CUR_TI->audio_hid, reqsize, &ptr);
1036 if (ret >= 0)
1037 copy_n = MIN((size_t)ret, reqsize);
1039 if (copy_n == 0)
1041 *realsize = 0;
1042 return NULL;
1045 *realsize = copy_n;
1047 return ptr;
1048 } /* codec_request_buffer_callback */
1050 static int get_codec_base_type(int type)
1052 switch (type) {
1053 case AFMT_MPA_L1:
1054 case AFMT_MPA_L2:
1055 case AFMT_MPA_L3:
1056 return AFMT_MPA_L3;
1059 return type;
1062 static void codec_advance_buffer_callback(size_t amount)
1064 codec_advance_buffer_counters(amount);
1065 codec_set_offset_callback(ci.curpos);
1068 static void codec_advance_buffer_loc_callback(void *ptr)
1070 size_t amount = buf_get_offset(CUR_TI->audio_hid, ptr);
1071 codec_advance_buffer_callback(amount);
1074 static void codec_seek_complete_callback(void)
1076 logf("seek_complete");
1077 if (pcm_is_paused())
1079 /* If this is not a seamless seek, clear the buffer */
1080 pcmbuf_play_stop();
1081 dsp_configure(ci.dsp, DSP_FLUSH, 0);
1083 /* If playback was not 'deliberately' paused, unpause now */
1084 if (!paused)
1085 pcmbuf_pause(false);
1087 ci.seek_time = 0;
1090 static bool codec_seek_buffer_callback(size_t newpos)
1092 logf("codec_seek_buffer_callback");
1094 int ret = bufseek(CUR_TI->audio_hid, newpos);
1095 if (ret == 0) {
1096 ci.curpos = newpos;
1097 return true;
1099 else {
1100 return false;
1104 static void codec_configure_callback(int setting, intptr_t value)
1106 switch (setting) {
1107 case CODEC_SET_FILEBUF_WATERMARK:
1108 set_filebuf_watermark(buffer_margin, value);
1109 break;
1111 default:
1112 if (!dsp_configure(ci.dsp, setting, value))
1113 { logf("Illegal key:%d", setting); }
1117 static void codec_track_changed(void)
1119 LOGFQUEUE("codec > audio Q_AUDIO_TRACK_CHANGED");
1120 queue_post(&audio_queue, Q_AUDIO_TRACK_CHANGED, 0);
1123 static void codec_pcmbuf_track_changed_callback(void)
1125 pcmbuf_set_position_callback(NULL);
1126 pcmbuf_callback_queue_post(Q_AUDIO_TRACK_CHANGED, 0);
1129 static void codec_discard_codec_callback(void)
1131 if (CUR_TI->codec_hid >= 0)
1133 bufclose(CUR_TI->codec_hid);
1134 CUR_TI->codec_hid = -1;
1138 static inline void codec_gapless_track_change(void)
1140 /* callback keeps the progress bar moving while the pcmbuf empties */
1141 pcmbuf_set_position_callback(codec_pcmbuf_position_callback);
1142 /* set the pcmbuf callback for when the track really changes */
1143 pcmbuf_set_event_handler(codec_pcmbuf_track_changed_callback);
1146 static inline void codec_crossfade_track_change(void)
1148 /* Initiate automatic crossfade mode */
1149 pcmbuf_crossfade_init(false);
1150 /* Notify the wps that the track change starts now */
1151 codec_track_changed();
1154 static void codec_track_skip_done(bool was_manual)
1156 /* Manual track change (always crossfade or flush audio). */
1157 if (was_manual)
1159 pcmbuf_crossfade_init(true);
1160 LOGFQUEUE("codec > audio Q_AUDIO_TRACK_CHANGED");
1161 queue_post(&audio_queue, Q_AUDIO_TRACK_CHANGED, 0);
1163 /* Automatic track change w/crossfade, if not in "Track Skip Only" mode. */
1164 else if (pcmbuf_is_crossfade_enabled() && !pcmbuf_is_crossfade_active()
1165 && global_settings.crossfade != CROSSFADE_ENABLE_TRACKSKIP)
1167 if (global_settings.crossfade == CROSSFADE_ENABLE_SHUFFLE_AND_TRACKSKIP)
1169 if (global_settings.playlist_shuffle)
1170 /* shuffle mode is on, so crossfade: */
1171 codec_crossfade_track_change();
1172 else
1173 /* shuffle mode is off, so do a gapless track change */
1174 codec_gapless_track_change();
1176 else
1177 /* normal crossfade: */
1178 codec_crossfade_track_change();
1180 else
1181 /* normal gapless playback. */
1182 codec_gapless_track_change();
1185 static bool codec_load_next_track(void)
1187 intptr_t result = Q_CODEC_REQUEST_FAILED;
1189 prev_track_elapsed = curtrack_id3.elapsed;
1191 #ifdef AB_REPEAT_ENABLE
1192 ab_end_of_track_report();
1193 #endif
1195 logf("Request new track");
1197 if (ci.new_track == 0)
1199 ci.new_track++;
1200 automatic_skip = true;
1203 if (!ci.stop_codec)
1205 trigger_cpu_boost();
1206 LOGFQUEUE("codec >| audio Q_AUDIO_CHECK_NEW_TRACK");
1207 result = queue_send(&audio_queue, Q_AUDIO_CHECK_NEW_TRACK, 0);
1210 switch (result)
1212 case Q_CODEC_REQUEST_COMPLETE:
1213 LOGFQUEUE("codec |< Q_CODEC_REQUEST_COMPLETE");
1214 codec_track_skip_done(!automatic_skip);
1215 return true;
1217 case Q_CODEC_REQUEST_FAILED:
1218 LOGFQUEUE("codec |< Q_CODEC_REQUEST_FAILED");
1219 ci.new_track = 0;
1220 ci.stop_codec = true;
1221 codec_requested_stop = true;
1222 return false;
1224 default:
1225 LOGFQUEUE("codec |< default");
1226 ci.stop_codec = true;
1227 codec_requested_stop = true;
1228 return false;
1232 static bool codec_request_next_track_callback(void)
1234 int prev_codectype;
1236 if (ci.stop_codec || !playing)
1237 return false;
1239 prev_codectype = get_codec_base_type(curtrack_id3.codectype);
1241 if (!codec_load_next_track())
1242 return false;
1244 /* Seek to the beginning of the new track because if the struct
1245 mp3entry was buffered, "elapsed" might not be zero (if the track has
1246 been played already but not unbuffered) */
1247 codec_seek_buffer_callback(curtrack_id3.first_frame_offset);
1249 /* Check if the next codec is the same file. */
1250 if (prev_codectype == get_codec_base_type(curtrack_id3.codectype))
1252 logf("New track loaded");
1253 codec_discard_codec_callback();
1254 return true;
1256 else
1258 logf("New codec:%d/%d", curtrack_id3.codectype, prev_codectype);
1259 return false;
1263 static void codec_thread(void)
1265 struct queue_event ev;
1266 int status;
1268 while (1) {
1269 status = 0;
1271 if (!pcmbuf_is_crossfade_active()) {
1272 cancel_cpu_boost();
1275 queue_wait(&codec_queue, &ev);
1276 codec_requested_stop = false;
1278 switch (ev.id) {
1279 case Q_CODEC_LOAD_DISK:
1280 LOGFQUEUE("codec < Q_CODEC_LOAD_DISK");
1281 queue_reply(&codec_queue, 1);
1282 audio_codec_loaded = true;
1283 ci.stop_codec = false;
1284 status = codec_load_file((const char *)ev.data, &ci);
1285 break;
1287 case Q_CODEC_LOAD:
1288 LOGFQUEUE("codec < Q_CODEC_LOAD");
1289 if (CUR_TI->codec_hid < 0) {
1290 logf("Codec slot is empty!");
1291 /* Wait for the pcm buffer to go empty */
1292 while (pcm_is_playing())
1293 yield();
1294 /* This must be set to prevent an infinite loop */
1295 ci.stop_codec = true;
1296 LOGFQUEUE("codec > codec Q_AUDIO_PLAY");
1297 queue_post(&codec_queue, Q_AUDIO_PLAY, 0);
1298 break;
1301 audio_codec_loaded = true;
1302 ci.stop_codec = false;
1303 status = codec_load_buf(CUR_TI->codec_hid, &ci);
1304 break;
1306 #ifdef AUDIO_HAVE_RECORDING
1307 case Q_ENCODER_LOAD_DISK:
1308 LOGFQUEUE("codec < Q_ENCODER_LOAD_DISK");
1309 audio_codec_loaded = false; /* Not audio codec! */
1310 logf("loading encoder");
1311 ci.stop_encoder = false;
1312 status = codec_load_file((const char *)ev.data, &ci);
1313 logf("encoder stopped");
1314 break;
1315 #endif /* AUDIO_HAVE_RECORDING */
1317 default:
1318 LOGFQUEUE("codec < default");
1321 if (audio_codec_loaded)
1323 if (ci.stop_codec)
1325 status = CODEC_OK;
1326 if (!playing)
1327 pcmbuf_play_stop();
1330 audio_codec_loaded = false;
1333 switch (ev.id) {
1334 case Q_CODEC_LOAD_DISK:
1335 case Q_CODEC_LOAD:
1336 LOGFQUEUE("codec < Q_CODEC_LOAD");
1337 if (playing)
1339 if (ci.new_track || status != CODEC_OK)
1341 if (!ci.new_track)
1343 logf("Codec failure");
1344 splash(HZ*2, "Codec failure");
1347 if (!codec_load_next_track())
1349 LOGFQUEUE("codec > audio Q_AUDIO_STOP");
1350 /* End of playlist */
1351 queue_post(&audio_queue, Q_AUDIO_STOP, 0);
1352 break;
1355 else
1357 logf("Codec finished");
1358 if (ci.stop_codec)
1360 /* Wait for the audio to stop playing before
1361 * triggering the WPS exit */
1362 while(pcm_is_playing())
1364 curtrack_id3.elapsed =
1365 curtrack_id3.length - pcmbuf_get_latency();
1366 sleep(1);
1369 if (codec_requested_stop)
1371 LOGFQUEUE("codec > audio Q_AUDIO_STOP");
1372 queue_post(&audio_queue, Q_AUDIO_STOP, 0);
1374 break;
1378 if (CUR_TI->codec_hid >= 0)
1380 LOGFQUEUE("codec > codec Q_CODEC_LOAD");
1381 queue_post(&codec_queue, Q_CODEC_LOAD, 0);
1383 else
1385 const char *codec_fn =
1386 get_codec_filename(curtrack_id3.codectype);
1387 if (codec_fn)
1389 LOGFQUEUE("codec > codec Q_CODEC_LOAD_DISK");
1390 queue_post(&codec_queue, Q_CODEC_LOAD_DISK,
1391 (intptr_t)codec_fn);
1395 break;
1397 #ifdef AUDIO_HAVE_RECORDING
1398 case Q_ENCODER_LOAD_DISK:
1399 LOGFQUEUE("codec < Q_ENCODER_LOAD_DISK");
1401 if (status == CODEC_OK)
1402 break;
1404 logf("Encoder failure");
1405 splash(HZ*2, "Encoder failure");
1407 if (ci.enc_codec_loaded < 0)
1408 break;
1410 logf("Encoder failed to load");
1411 ci.enc_codec_loaded = -1;
1412 break;
1413 #endif /* AUDIO_HAVE_RECORDING */
1415 default:
1416 LOGFQUEUE("codec < default");
1418 } /* end switch */
1423 /* --- Buffering callbacks --- */
1425 static void buffering_low_buffer_callback(void *data)
1427 (void)data;
1428 logf("low buffer callback");
1430 if (filling == STATE_FULL || filling == STATE_END_OF_PLAYLIST) {
1431 /* force a refill */
1432 LOGFQUEUE("buffering > audio Q_AUDIO_FILL_BUFFER");
1433 queue_post(&audio_queue, Q_AUDIO_FILL_BUFFER, 0);
1437 static void buffering_handle_rebuffer_callback(void *data)
1439 (void)data;
1440 LOGFQUEUE("audio >| audio Q_AUDIO_FLUSH");
1441 queue_post(&audio_queue, Q_AUDIO_FLUSH, 0);
1444 static void buffering_handle_finished_callback(int *data)
1446 logf("handle %d finished buffering", *data);
1448 if (*data == tracks[track_widx].id3_hid)
1450 /* The metadata handle for the last loaded track has been buffered.
1451 We can ask the audio thread to load the rest of the track's data. */
1452 LOGFQUEUE("audio >| audio Q_AUDIO_FINISH_LOAD");
1453 queue_post(&audio_queue, Q_AUDIO_FINISH_LOAD, 0);
1455 else
1457 /* This is most likely an audio handle, so we strip the useless
1458 trailing tags that are left. */
1459 strip_tags(*data);
1461 if (*data == tracks[track_widx-1].audio_hid
1462 && filling == STATE_END_OF_PLAYLIST)
1464 /* This was the last track in the playlist.
1465 We now have all the data we need. */
1466 logf("last track finished buffering");
1467 filling = STATE_FINISHED;
1473 /* --- Audio thread --- */
1475 static bool audio_have_tracks(void)
1477 return (audio_track_count() != 0);
1480 static int audio_free_track_count(void)
1482 /* Used tracks + free tracks adds up to MAX_TRACK - 1 */
1483 return MAX_TRACK - 1 - audio_track_count();
1486 int audio_track_count(void)
1488 /* Calculate difference from track_ridx to track_widx
1489 * taking into account a possible wrap-around. */
1490 return (MAX_TRACK + track_widx - track_ridx) & MAX_TRACK_MASK;
1493 long audio_filebufused(void)
1495 return (long) buf_used();
1498 /* Update track info after successful a codec track change */
1499 static void audio_update_trackinfo(void)
1501 /* Load the curent track's metadata into curtrack_id3 */
1502 if (CUR_TI->id3_hid >= 0)
1503 copy_mp3entry(&curtrack_id3, bufgetid3(CUR_TI->id3_hid));
1505 /* Reset current position */
1506 curtrack_id3.elapsed = 0;
1507 curtrack_id3.offset = 0;
1509 /* Update the codec API */
1510 ci.filesize = CUR_TI->filesize;
1511 ci.id3 = &curtrack_id3;
1512 ci.curpos = 0;
1513 ci.taginfo_ready = &CUR_TI->taginfo_ready;
1516 /* Clear tracks between write and read, non inclusive */
1517 static void audio_clear_track_entries(void)
1519 int cur_idx = track_widx;
1521 logf("Clearing tracks:%d/%d", track_ridx, track_widx);
1523 /* Loop over all tracks from write-to-read */
1524 while (1)
1526 cur_idx = (cur_idx + 1) & MAX_TRACK_MASK;
1528 if (cur_idx == track_ridx)
1529 break;
1531 clear_track_info(&tracks[cur_idx]);
1535 /* Clear all tracks */
1536 static bool audio_release_tracks(void)
1538 int i, cur_idx;
1540 logf("releasing all tracks");
1542 for(i = 0; i < MAX_TRACK; i++)
1544 cur_idx = (track_ridx + i) & MAX_TRACK_MASK;
1545 if (!clear_track_info(&tracks[cur_idx]))
1546 return false;
1549 return true;
1552 static bool audio_loadcodec(bool start_play)
1554 int prev_track;
1555 char codec_path[MAX_PATH]; /* Full path to codec */
1556 const struct mp3entry *id3, *prev_id3;
1558 if (tracks[track_widx].id3_hid < 0) {
1559 return false;
1562 id3 = bufgetid3(tracks[track_widx].id3_hid);
1563 if (!id3)
1564 return false;
1566 const char *codec_fn = get_codec_filename(id3->codectype);
1567 if (codec_fn == NULL)
1568 return false;
1570 tracks[track_widx].codec_hid = -1;
1572 if (start_play)
1574 /* Load the codec directly from disk and save some memory. */
1575 track_ridx = track_widx;
1576 ci.filesize = CUR_TI->filesize;
1577 ci.id3 = &curtrack_id3;
1578 ci.taginfo_ready = &CUR_TI->taginfo_ready;
1579 ci.curpos = 0;
1580 LOGFQUEUE("codec > codec Q_CODEC_LOAD_DISK");
1581 queue_post(&codec_queue, Q_CODEC_LOAD_DISK, (intptr_t)codec_fn);
1582 return true;
1584 else
1586 /* If we already have another track than this one buffered */
1587 if (track_widx != track_ridx)
1589 prev_track = (track_widx - 1) & MAX_TRACK_MASK;
1591 id3 = bufgetid3(tracks[track_widx].id3_hid);
1592 prev_id3 = bufgetid3(tracks[prev_track].id3_hid);
1594 /* If the previous codec is the same as this one, there is no need
1595 * to put another copy of it on the file buffer */
1596 if (id3 && prev_id3 &&
1597 get_codec_base_type(id3->codectype) ==
1598 get_codec_base_type(prev_id3->codectype)
1599 && audio_codec_loaded)
1601 logf("Reusing prev. codec");
1602 return true;
1607 codec_get_full_path(codec_path, codec_fn);
1609 tracks[track_widx].codec_hid = bufopen(codec_path, 0, TYPE_CODEC);
1610 if (tracks[track_widx].codec_hid < 0)
1611 return false;
1613 logf("Loaded codec");
1615 return true;
1618 /* Load metadata for the next track (with bufopen). The rest of the track
1619 loading will be handled by audio_finish_load_track once the metadata has been
1620 actually loaded by the buffering thread. */
1621 static bool audio_load_track(size_t offset, bool start_play)
1623 const char *trackname;
1624 int fd = -1;
1626 if (track_load_started) {
1627 /* There is already a track load in progress, so track_widx hasn't been
1628 incremented yet. Loading another track would overwrite the one that
1629 hasn't finished loading. */
1630 logf("audio_load_track(): a track load is already in progress");
1631 return false;
1634 start_play_g = start_play; /* will be read by audio_finish_load_track */
1636 /* Stop buffer filling if there is no free track entries.
1637 Don't fill up the last track entry (we wan't to store next track
1638 metadata there). */
1639 if (!audio_free_track_count())
1641 logf("No free tracks");
1642 return false;
1645 last_peek_offset++;
1646 tracks[track_widx].taginfo_ready = false;
1648 logf("Buffering track:%d/%d", track_widx, track_ridx);
1649 /* Get track name from current playlist read position. */
1650 while ((trackname = playlist_peek(last_peek_offset)) != NULL)
1652 /* Handle broken playlists. */
1653 fd = open(trackname, O_RDONLY);
1654 if (fd < 0)
1656 logf("Open failed");
1657 /* Skip invalid entry from playlist. */
1658 playlist_skip_entry(NULL, last_peek_offset);
1660 else
1661 break;
1664 if (!trackname)
1666 logf("End-of-playlist");
1667 memset(&lasttrack_id3, 0, sizeof(struct mp3entry));
1668 filling = STATE_END_OF_PLAYLIST;
1670 if (curtrack_id3.length == 0 && curtrack_id3.filesize == 0)
1672 /* Stop playback if no valid track was found. */
1673 audio_stop_playback();
1676 return false;
1679 tracks[track_widx].filesize = filesize(fd);
1681 if (offset > tracks[track_widx].filesize)
1682 offset = 0;
1684 /* Set default values */
1685 if (start_play)
1687 buf_set_watermark(AUDIO_DEFAULT_WATERMARK);
1688 dsp_configure(ci.dsp, DSP_RESET, 0);
1689 track_changed = true;
1690 playlist_update_resume_info(audio_current_track());
1693 /* Get track metadata if we don't already have it. */
1694 if (tracks[track_widx].id3_hid < 0)
1696 tracks[track_widx].id3_hid = bufopen(trackname, 0, TYPE_ID3);
1698 if (tracks[track_widx].id3_hid < 0)
1700 /* Buffer is full. */
1701 get_metadata(&lasttrack_id3, fd, trackname);
1702 last_peek_offset--;
1703 close(fd);
1704 logf("buffer is full for now");
1705 filling = STATE_FULL;
1706 return false;
1709 if (track_widx == track_ridx)
1711 /* TODO: Superfluos buffering call? */
1712 buf_request_buffer_handle(tracks[track_widx].id3_hid);
1713 copy_mp3entry(&curtrack_id3, bufgetid3(tracks[track_widx].id3_hid));
1714 curtrack_id3.offset = offset;
1717 if (start_play)
1719 track_changed = true;
1720 playlist_update_resume_info(audio_current_track());
1724 close(fd);
1725 track_load_started = true; /* Remember that we've started loading a track */
1726 return true;
1729 /* Second part of the track loading: We now have the metadata available, so we
1730 can load the codec, the album art and finally the audio data.
1731 This is called on the audio thread after the buffering thread calls the
1732 buffering_handle_finished_callback callback. */
1733 static void audio_finish_load_track(void)
1735 size_t file_offset = 0;
1736 size_t offset = 0;
1737 bool start_play = start_play_g;
1739 #if 0
1740 if (cuesheet_is_enabled() && tracks[track_widx].id3.cuesheet_type == 1)
1742 char cuepath[MAX_PATH];
1744 struct cuesheet *cue = start_play ? curr_cue : temp_cue;
1746 if (look_for_cuesheet_file(trackname, cuepath) &&
1747 parse_cuesheet(cuepath, cue))
1749 strcpy((cue)->audio_filename, trackname);
1750 if (start_play)
1751 cue_spoof_id3(curr_cue, &tracks[track_widx].id3);
1754 #endif
1756 track_load_started = false;
1758 if (tracks[track_widx].id3_hid < 0) {
1759 logf("no metatdata");
1760 return;
1763 struct mp3entry *track_id3;
1765 if (track_widx == track_ridx)
1766 track_id3 = &curtrack_id3;
1767 else
1768 track_id3 = bufgetid3(tracks[track_widx].id3_hid);
1770 if (track_id3->length == 0 && track_id3->filesize == 0)
1772 logf("audio_finish_load_track: invalid metadata");
1774 /* Invalid metadata */
1775 bufclose(tracks[track_widx].id3_hid);
1776 tracks[track_widx].id3_hid = -1;
1778 /* Skip invalid entry from playlist. */
1779 playlist_skip_entry(NULL, last_peek_offset--);
1781 /* load next track */
1782 LOGFQUEUE("audio > audio Q_AUDIO_FILL_BUFFER %d", (int)start_play);
1783 queue_post(&audio_queue, Q_AUDIO_FILL_BUFFER, start_play);
1785 return;
1788 #ifdef HAVE_ALBUMART
1789 if (tracks[track_widx].aa_hid < 0 && gui_sync_wps_uses_albumart())
1791 char aa_path[MAX_PATH];
1792 if (find_albumart(track_id3, aa_path, sizeof(aa_path)))
1793 tracks[track_widx].aa_hid = bufopen(aa_path, 0, TYPE_BITMAP);
1795 #endif
1797 /* Load the codec. */
1798 if (!audio_loadcodec(start_play))
1800 if (tracks[track_widx].codec_hid == ERR_BUFFER_FULL)
1802 /* No space for codec on buffer, not an error */
1803 return;
1806 /* This is an error condition, either no codec was found, or reading
1807 * the codec file failed part way through, either way, skip the track */
1808 /* FIXME: We should not use splashf from audio thread! */
1809 splashf(HZ*2, "No codec for: %s", track_id3->path);
1810 /* Skip invalid entry from playlist. */
1811 playlist_skip_entry(NULL, last_peek_offset);
1812 return;
1815 track_id3->elapsed = 0;
1816 offset = track_id3->offset;
1818 enum data_type type = TYPE_PACKET_AUDIO;
1820 switch (track_id3->codectype) {
1821 case AFMT_MPA_L1:
1822 case AFMT_MPA_L2:
1823 case AFMT_MPA_L3:
1824 if (offset > 0) {
1825 file_offset = offset;
1826 track_id3->offset = offset;
1828 break;
1830 case AFMT_WAVPACK:
1831 if (offset > 0) {
1832 file_offset = offset;
1833 track_id3->offset = offset;
1834 track_id3->elapsed = track_id3->length / 2;
1836 break;
1838 case AFMT_OGG_VORBIS:
1839 case AFMT_SPEEX:
1840 case AFMT_FLAC:
1841 case AFMT_PCM_WAV:
1842 case AFMT_A52:
1843 case AFMT_AAC:
1844 case AFMT_MPC:
1845 case AFMT_APE:
1846 case AFMT_WMA:
1847 if (offset > 0)
1848 track_id3->offset = offset;
1849 break;
1851 case AFMT_NSF:
1852 case AFMT_SPC:
1853 case AFMT_SID:
1854 logf("Loading atomic %d",track_id3->codectype);
1855 type = TYPE_ATOMIC_AUDIO;
1856 break;
1859 logf("alt:%s", track_id3->path);
1861 if (file_offset > AUDIO_REBUFFER_GUESS_SIZE)
1862 file_offset -= AUDIO_REBUFFER_GUESS_SIZE;
1863 else if (track_id3->first_frame_offset)
1864 file_offset = track_id3->first_frame_offset;
1865 else
1866 file_offset = 0;
1868 tracks[track_widx].audio_hid = bufopen(track_id3->path, file_offset, type);
1870 if (tracks[track_widx].audio_hid < 0)
1871 return;
1873 /* All required data is now available for the codec. */
1874 tracks[track_widx].taginfo_ready = true;
1876 if (start_play)
1878 ci.curpos=file_offset;
1879 buf_request_buffer_handle(tracks[track_widx].audio_hid);
1882 track_widx = (track_widx + 1) & MAX_TRACK_MASK;
1884 send_event(PLAYBACK_EVENT_TRACK_BUFFER, track_id3);
1886 /* load next track */
1887 LOGFQUEUE("audio > audio Q_AUDIO_FILL_BUFFER");
1888 queue_post(&audio_queue, Q_AUDIO_FILL_BUFFER, 0);
1890 return;
1893 static void audio_fill_file_buffer(bool start_play, size_t offset)
1895 bool had_next_track = audio_next_track() != NULL;
1897 filling = STATE_FILLING;
1898 trigger_cpu_boost();
1900 /* No need to rebuffer if there are track skips pending. */
1901 if (ci.new_track != 0)
1902 return;
1904 /* Must reset the buffer before use if trashed or voice only - voice
1905 file size shouldn't have changed so we can go straight from
1906 AUDIOBUF_STATE_VOICED_ONLY to AUDIOBUF_STATE_INITIALIZED */
1907 if (buffer_state != AUDIOBUF_STATE_INITIALIZED)
1908 audio_reset_buffer();
1910 logf("Starting buffer fill");
1912 if (!start_play)
1913 audio_clear_track_entries();
1915 /* Save the current resume position once. */
1916 playlist_update_resume_info(audio_current_track());
1918 audio_load_track(offset, start_play);
1920 if (!had_next_track && audio_next_track())
1921 track_changed = true;
1924 static void audio_rebuffer(void)
1926 logf("Forcing rebuffer");
1928 clear_track_info(CUR_TI);
1930 /* Reset track pointers */
1931 track_widx = track_ridx;
1932 audio_clear_track_entries();
1934 /* Reset a possibly interrupted track load */
1935 track_load_started = false;
1937 /* Fill the buffer */
1938 last_peek_offset = -1;
1939 ci.curpos = 0;
1941 if (!CUR_TI->taginfo_ready)
1942 memset(&curtrack_id3, 0, sizeof(struct mp3entry));
1944 audio_fill_file_buffer(false, 0);
1947 /* Called on request from the codec to get a new track. This is the codec part
1948 of the track transition. */
1949 static int audio_check_new_track(void)
1951 int track_count = audio_track_count();
1952 int old_track_ridx = track_ridx;
1953 int i, idx;
1954 bool forward;
1956 /* Now it's good time to send track finish events. */
1957 send_event(PLAYBACK_EVENT_TRACK_FINISH, &curtrack_id3);
1958 if (dir_skip)
1960 dir_skip = false;
1961 /* regardless of the return value we need to rebuffer.
1962 if it fails the old playlist will resume, else the
1963 next dir will start playing */
1964 playlist_next_dir(ci.new_track);
1965 ci.new_track = 0;
1966 audio_rebuffer();
1967 goto skip_done;
1970 if (new_playlist)
1971 ci.new_track = 0;
1973 /* If the playlist isn't that big */
1974 if (automatic_skip)
1976 while (!playlist_check(ci.new_track))
1978 if (ci.new_track >= 0)
1980 LOGFQUEUE("audio >|= codec Q_CODEC_REQUEST_FAILED");
1981 return Q_CODEC_REQUEST_FAILED;
1983 ci.new_track++;
1987 /* Update the playlist */
1988 last_peek_offset -= ci.new_track;
1990 if (playlist_next(ci.new_track) < 0)
1992 LOGFQUEUE("audio >|= codec Q_CODEC_REQUEST_FAILED");
1993 return Q_CODEC_REQUEST_FAILED;
1996 if (new_playlist)
1998 ci.new_track = 1;
1999 new_playlist = false;
2002 /* Save the track metadata to allow the WPS to display it
2003 while PCM finishes playing that track */
2004 copy_mp3entry(&prevtrack_id3, &curtrack_id3);
2006 /* Update the main buffer copy of the track metadata with the one
2007 the codec has been using (for the unbuffer callbacks) */
2008 if (CUR_TI->id3_hid >= 0)
2009 copy_mp3entry(bufgetid3(CUR_TI->id3_hid), &curtrack_id3);
2011 /* Save a pointer to the old track to allow later clearing */
2012 prev_ti = CUR_TI;
2014 for (i = 0; i < ci.new_track; i++)
2016 idx = (track_ridx + i) & MAX_TRACK_MASK;
2017 struct mp3entry *id3 = bufgetid3(tracks[idx].id3_hid);
2018 ssize_t offset = buf_handle_offset(tracks[idx].audio_hid);
2019 if (!id3 || offset < 0 || (unsigned)offset > id3->first_frame_offset)
2021 /* We don't have all the audio data for that track, so clear it,
2022 but keep the metadata. */
2023 if (tracks[idx].audio_hid >= 0 && bufclose(tracks[idx].audio_hid))
2025 tracks[idx].audio_hid = -1;
2026 tracks[idx].filesize = 0;
2031 /* Move to the new track */
2032 track_ridx = (track_ridx + ci.new_track) & MAX_TRACK_MASK;
2034 buf_set_base_handle(CUR_TI->audio_hid);
2036 if (automatic_skip)
2038 wps_offset = -ci.new_track;
2039 track_changed = true;
2042 /* If it is not safe to even skip this many track entries */
2043 if (ci.new_track >= track_count || ci.new_track <= track_count - MAX_TRACK)
2045 ci.new_track = 0;
2046 audio_rebuffer();
2047 goto skip_done;
2050 forward = ci.new_track > 0;
2051 ci.new_track = 0;
2053 /* If the target track is clearly not in memory */
2054 if (CUR_TI->filesize == 0 || !CUR_TI->taginfo_ready)
2056 audio_rebuffer();
2057 goto skip_done;
2060 /* When skipping backwards, it is possible that we've found a track that's
2061 * buffered, but which is around the track-wrap and therefore not the track
2062 * we are looking for */
2063 if (!forward)
2065 int cur_idx = track_ridx;
2066 bool taginfo_ready = true;
2067 /* We've wrapped the buffer backwards if new > old */
2068 bool wrap = track_ridx > old_track_ridx;
2070 while (1)
2072 cur_idx = (cur_idx + 1) & MAX_TRACK_MASK;
2074 /* if we've advanced past the wrap when cur_idx is zeroed */
2075 if (!cur_idx)
2076 wrap = false;
2078 /* if we aren't still on the wrap and we've caught the old track */
2079 if (!(wrap || cur_idx < old_track_ridx))
2080 break;
2082 /* If we hit a track in between without valid tag info, bail */
2083 if (!tracks[cur_idx].taginfo_ready)
2085 taginfo_ready = false;
2086 break;
2089 if (!taginfo_ready)
2091 audio_rebuffer();
2095 skip_done:
2096 audio_update_trackinfo();
2097 LOGFQUEUE("audio >|= codec Q_CODEC_REQUEST_COMPLETE");
2098 return Q_CODEC_REQUEST_COMPLETE;
2101 unsigned long audio_prev_elapsed(void)
2103 return prev_track_elapsed;
2106 static void audio_stop_codec_flush(void)
2108 ci.stop_codec = true;
2109 pcmbuf_pause(true);
2111 while (audio_codec_loaded)
2112 yield();
2114 /* If the audio codec is not loaded any more, and the audio is still
2115 * playing, it is now and _only_ now safe to call this function from the
2116 * audio thread */
2117 if (pcm_is_playing())
2119 pcmbuf_play_stop();
2120 pcmbuf_queue_clear();
2122 pcmbuf_pause(paused);
2125 static void audio_stop_playback(void)
2127 /* If we were playing, save resume information */
2128 if (playing)
2130 struct mp3entry *id3 = NULL;
2132 if (!ci.stop_codec)
2134 /* Set this early, the outside code yields and may allow the codec
2135 to try to wait for a reply on a buffer wait */
2136 ci.stop_codec = true;
2137 id3 = audio_current_track();
2140 /* Save the current playing spot, or NULL if the playlist has ended */
2141 playlist_update_resume_info(id3);
2143 /* TODO: Create auto bookmark too? */
2145 prev_track_elapsed = curtrack_id3.elapsed;
2147 remove_event(BUFFER_EVENT_BUFFER_LOW, buffering_low_buffer_callback);
2150 audio_stop_codec_flush();
2151 paused = false;
2152 playing = false;
2153 track_load_started = false;
2155 filling = STATE_IDLE;
2157 /* Mark all entries null. */
2158 audio_clear_track_entries();
2160 /* Close all tracks */
2161 audio_release_tracks();
2163 memset(&curtrack_id3, 0, sizeof(struct mp3entry));
2166 static void audio_play_start(size_t offset)
2168 int i;
2170 #if INPUT_SRC_CAPS != 0
2171 audio_set_input_source(AUDIO_SRC_PLAYBACK, SRCF_PLAYBACK);
2172 audio_set_output_source(AUDIO_SRC_PLAYBACK);
2173 #endif
2175 /* Wait for any previously playing audio to flush - TODO: Not necessary? */
2176 paused = false;
2177 audio_stop_codec_flush();
2179 track_changed = true;
2181 playing = true;
2182 track_load_started = false;
2184 ci.new_track = 0;
2185 ci.seek_time = 0;
2186 wps_offset = 0;
2188 sound_set_volume(global_settings.volume);
2189 track_widx = track_ridx = 0;
2191 /* Clear all track entries. */
2192 for (i = 0; i < MAX_TRACK; i++) {
2193 clear_track_info(&tracks[i]);
2196 last_peek_offset = -1;
2198 /* Officially playing */
2199 queue_reply(&audio_queue, 1);
2201 #ifdef HAVE_DISK_STORAGE
2202 set_filebuf_watermark(buffer_margin, 0);
2203 #endif
2205 audio_fill_file_buffer(true, offset);
2207 add_event(BUFFER_EVENT_BUFFER_LOW, false, buffering_low_buffer_callback);
2209 LOGFQUEUE("audio > audio Q_AUDIO_TRACK_CHANGED");
2210 queue_post(&audio_queue, Q_AUDIO_TRACK_CHANGED, 0);
2214 /* Invalidates all but currently playing track. */
2215 static void audio_invalidate_tracks(void)
2217 if (audio_have_tracks())
2219 last_peek_offset = 0;
2220 track_widx = track_ridx;
2222 /* Mark all other entries null (also buffered wrong metadata). */
2223 audio_clear_track_entries();
2225 track_widx = (track_widx + 1) & MAX_TRACK_MASK;
2227 audio_fill_file_buffer(false, 0);
2231 static void audio_new_playlist(void)
2233 /* Prepare to start a new fill from the beginning of the playlist */
2234 last_peek_offset = -1;
2235 if (audio_have_tracks())
2237 if (paused)
2238 skipped_during_pause = true;
2239 track_widx = track_ridx;
2240 audio_clear_track_entries();
2242 track_widx = (track_widx + 1) & MAX_TRACK_MASK;
2244 /* Mark the current track as invalid to prevent skipping back to it */
2245 CUR_TI->taginfo_ready = false;
2248 /* Signal the codec to initiate a track change forward */
2249 new_playlist = true;
2250 ci.new_track = 1;
2252 /* Officially playing */
2253 queue_reply(&audio_queue, 1);
2255 audio_fill_file_buffer(false, 0);
2258 /* Called on manual track skip */
2259 static void audio_initiate_track_change(long direction)
2261 logf("audio_initiate_track_change(%ld)", direction);
2263 ci.new_track += direction;
2264 wps_offset -= direction;
2265 if (paused)
2266 skipped_during_pause = true;
2269 /* Called on manual dir skip */
2270 static void audio_initiate_dir_change(long direction)
2272 dir_skip = true;
2273 ci.new_track = direction;
2274 if (paused)
2275 skipped_during_pause = true;
2278 /* Called when PCM track change is complete */
2279 static void audio_finalise_track_change(void)
2281 logf("audio_finalise_track_change");
2283 if (automatic_skip)
2285 wps_offset = 0;
2286 automatic_skip = false;
2288 /* Invalidate prevtrack_id3 */
2289 prevtrack_id3.path[0] = 0;
2291 if (prev_ti && prev_ti->audio_hid < 0)
2293 /* No audio left so we clear all the track info. */
2294 clear_track_info(prev_ti);
2297 if (prev_ti && prev_ti->id3_hid >= 0)
2299 /* Reset the elapsed time to force the progressbar to be empty if
2300 the user skips back to this track */
2301 bufgetid3(prev_ti->id3_hid)->elapsed = 0;
2305 send_event(PLAYBACK_EVENT_TRACK_CHANGE, &curtrack_id3);
2307 track_changed = true;
2308 playlist_update_resume_info(audio_current_track());
2312 * Layout audio buffer as follows - iram buffer depends on target:
2313 * [|SWAP:iram][|TALK]|FILE|GUARD|PCM|[SWAP:dram[|iram]|]
2315 static void audio_reset_buffer(void)
2317 /* see audio_get_recording_buffer if this is modified */
2318 logf("audio_reset_buffer");
2320 /* If the setup of anything allocated before the file buffer is
2321 changed, do check the adjustments after the buffer_alloc call
2322 as it will likely be affected and need sliding over */
2324 /* Initially set up file buffer as all space available */
2325 malloc_buf = audiobuf + talk_get_bufsize();
2326 /* Align the malloc buf to line size. Especially important to cf
2327 targets that do line reads/writes. */
2328 malloc_buf = (unsigned char *)(((uintptr_t)malloc_buf + 15) & ~15);
2329 filebuf = malloc_buf; /* filebuf line align implied */
2330 filebuflen = audiobufend - filebuf;
2332 filebuflen &= ~15;
2334 /* Subtract whatever the pcm buffer says it used plus the guard buffer */
2335 const size_t pcmbuf_size = pcmbuf_init(filebuf + filebuflen) +GUARD_BUFSIZE;
2336 #ifdef DEBUG
2337 if(pcmbuf_size > filebuflen)
2338 panicf("Not enough memory for pcmbuf_init() : %d > %d",
2339 (int)pcmbuf_size, (int)filebuflen);
2340 #endif
2341 filebuflen -= pcmbuf_size;
2343 /* Make sure filebuflen is a longword multiple after adjustment - filebuf
2344 will already be line aligned */
2345 filebuflen &= ~3;
2347 buffering_reset(filebuf, filebuflen);
2349 /* Clear any references to the file buffer */
2350 buffer_state = AUDIOBUF_STATE_INITIALIZED;
2352 #if defined(ROCKBOX_HAS_LOGF) && defined(LOGF_ENABLE)
2353 /* Make sure everything adds up - yes, some info is a bit redundant but
2354 aids viewing and the sumation of certain variables should add up to
2355 the location of others. */
2357 size_t pcmbufsize;
2358 const unsigned char *pcmbuf = pcmbuf_get_meminfo(&pcmbufsize);
2359 logf("mabuf: %08X", (unsigned)malloc_buf);
2360 logf("fbuf: %08X", (unsigned)filebuf);
2361 logf("fbufe: %08X", (unsigned)(filebuf + filebuflen));
2362 logf("gbuf: %08X", (unsigned)(filebuf + filebuflen));
2363 logf("gbufe: %08X", (unsigned)(filebuf + filebuflen + GUARD_BUFSIZE));
2364 logf("pcmb: %08X", (unsigned)pcmbuf);
2365 logf("pcmbe: %08X", (unsigned)(pcmbuf + pcmbufsize));
2367 #endif
2370 static void audio_thread(void)
2372 struct queue_event ev;
2374 pcm_postinit();
2376 audio_thread_ready = true;
2378 while (1)
2380 if (filling != STATE_FILLING) {
2381 cancel_cpu_boost();
2384 if (!pcmbuf_queue_scan(&ev))
2385 queue_wait_w_tmo(&audio_queue, &ev, HZ/2);
2387 switch (ev.id) {
2389 case Q_AUDIO_FILL_BUFFER:
2390 LOGFQUEUE("audio < Q_AUDIO_FILL_BUFFER %d", (int)ev.data);
2391 audio_fill_file_buffer((bool)ev.data, 0);
2392 break;
2394 case Q_AUDIO_FINISH_LOAD:
2395 LOGFQUEUE("audio < Q_AUDIO_FINISH_LOAD");
2396 audio_finish_load_track();
2397 break;
2399 case Q_AUDIO_PLAY:
2400 LOGFQUEUE("audio < Q_AUDIO_PLAY");
2401 if (playing && ev.data <= 0)
2402 audio_new_playlist();
2403 else
2405 audio_stop_playback();
2406 audio_play_start((size_t)ev.data);
2408 break;
2410 case Q_AUDIO_STOP:
2411 LOGFQUEUE("audio < Q_AUDIO_STOP");
2412 if (playing)
2413 audio_stop_playback();
2414 if (ev.data != 0)
2415 queue_clear(&audio_queue);
2416 break;
2418 case Q_AUDIO_PAUSE:
2419 LOGFQUEUE("audio < Q_AUDIO_PAUSE");
2420 if (!(bool) ev.data && skipped_during_pause && !pcmbuf_is_crossfade_active())
2421 pcmbuf_play_stop(); /* Flush old track on resume after skip */
2422 skipped_during_pause = false;
2423 if (!playing)
2424 break;
2425 pcmbuf_pause((bool)ev.data);
2426 paused = (bool)ev.data;
2427 break;
2429 case Q_AUDIO_SKIP:
2430 LOGFQUEUE("audio < Q_AUDIO_SKIP");
2431 audio_initiate_track_change((long)ev.data);
2432 break;
2434 case Q_AUDIO_PRE_FF_REWIND:
2435 LOGFQUEUE("audio < Q_AUDIO_PRE_FF_REWIND");
2436 if (!playing)
2437 break;
2438 pcmbuf_pause(true);
2439 break;
2441 case Q_AUDIO_FF_REWIND:
2442 LOGFQUEUE("audio < Q_AUDIO_FF_REWIND");
2443 if (!playing)
2444 break;
2445 if (automatic_skip)
2447 /* An automatic track skip is in progress. Finalize it,
2448 then go back to the previous track */
2449 audio_finalise_track_change();
2450 ci.new_track = -1;
2452 ci.seek_time = (long)ev.data+1;
2453 break;
2455 case Q_AUDIO_CHECK_NEW_TRACK:
2456 LOGFQUEUE("audio < Q_AUDIO_CHECK_NEW_TRACK");
2457 queue_reply(&audio_queue, audio_check_new_track());
2458 break;
2460 case Q_AUDIO_DIR_SKIP:
2461 LOGFQUEUE("audio < Q_AUDIO_DIR_SKIP");
2462 audio_initiate_dir_change(ev.data);
2463 break;
2465 case Q_AUDIO_FLUSH:
2466 LOGFQUEUE("audio < Q_AUDIO_FLUSH");
2467 audio_invalidate_tracks();
2468 break;
2470 case Q_AUDIO_TRACK_CHANGED:
2471 /* PCM track change done */
2472 LOGFQUEUE("audio < Q_AUDIO_TRACK_CHANGED");
2473 audio_finalise_track_change();
2474 break;
2476 #ifndef SIMULATOR
2477 case SYS_USB_CONNECTED:
2478 LOGFQUEUE("audio < SYS_USB_CONNECTED");
2479 if (playing)
2480 audio_stop_playback();
2481 #ifdef PLAYBACK_VOICE
2482 voice_stop();
2483 #endif
2484 usb_acknowledge(SYS_USB_CONNECTED_ACK);
2485 usb_wait_for_disconnect(&audio_queue);
2487 /* Mark all entries null. */
2488 audio_clear_track_entries();
2490 /* release tracks to make sure all handles are closed */
2491 audio_release_tracks();
2492 break;
2493 #endif
2495 case SYS_TIMEOUT:
2496 LOGFQUEUE_SYS_TIMEOUT("audio < SYS_TIMEOUT");
2497 break;
2499 default:
2500 LOGFQUEUE("audio < default");
2501 break;
2502 } /* end switch */
2503 } /* end while */
2506 /* Initialize the audio system - called from init() in main.c.
2507 * Last function because of all the references to internal symbols
2509 void audio_init(void)
2511 unsigned int audio_thread_id;
2513 /* Can never do this twice */
2514 if (audio_is_initialized)
2516 logf("audio: already initialized");
2517 return;
2520 logf("audio: initializing");
2522 /* Initialize queues before giving control elsewhere in case it likes
2523 to send messages. Thread creation will be delayed however so nothing
2524 starts running until ready if something yields such as talk_init. */
2525 queue_init(&audio_queue, true);
2526 queue_init(&codec_queue, false);
2527 queue_init(&pcmbuf_queue, false);
2529 pcm_init();
2531 /* Initialize codec api. */
2532 ci.read_filebuf = codec_filebuf_callback;
2533 ci.pcmbuf_insert = codec_pcmbuf_insert_callback;
2534 ci.codec_get_buffer = codec_get_buffer;
2535 ci.request_buffer = codec_request_buffer_callback;
2536 ci.advance_buffer = codec_advance_buffer_callback;
2537 ci.advance_buffer_loc = codec_advance_buffer_loc_callback;
2538 ci.request_next_track = codec_request_next_track_callback;
2539 ci.seek_buffer = codec_seek_buffer_callback;
2540 ci.seek_complete = codec_seek_complete_callback;
2541 ci.set_elapsed = codec_set_elapsed_callback;
2542 ci.set_offset = codec_set_offset_callback;
2543 ci.configure = codec_configure_callback;
2544 ci.discard_codec = codec_discard_codec_callback;
2545 ci.dsp = (struct dsp_config *)dsp_configure(NULL, DSP_MYDSP,
2546 CODEC_IDX_AUDIO);
2548 /* initialize the buffer */
2549 filebuf = audiobuf;
2551 /* audio_reset_buffer must to know the size of voice buffer so init
2552 talk first */
2553 talk_init();
2555 codec_thread_id = create_thread(
2556 codec_thread, codec_stack, sizeof(codec_stack),
2557 CREATE_THREAD_FROZEN,
2558 codec_thread_name IF_PRIO(, PRIORITY_PLAYBACK)
2559 IF_COP(, CPU));
2561 queue_enable_queue_send(&codec_queue, &codec_queue_sender_list,
2562 codec_thread_id);
2564 audio_thread_id = create_thread(audio_thread, audio_stack,
2565 sizeof(audio_stack), CREATE_THREAD_FROZEN,
2566 audio_thread_name IF_PRIO(, PRIORITY_USER_INTERFACE)
2567 IF_COP(, CPU));
2569 queue_enable_queue_send(&audio_queue, &audio_queue_sender_list,
2570 audio_thread_id);
2572 #ifdef PLAYBACK_VOICE
2573 voice_thread_init();
2574 #endif
2576 /* Set crossfade setting for next buffer init which should be about... */
2577 pcmbuf_crossfade_enable(global_settings.crossfade);
2579 /* initialize the buffering system */
2581 buffering_init();
2582 /* ...now! Set up the buffers */
2583 audio_reset_buffer();
2585 int i;
2586 for(i = 0; i < MAX_TRACK; i++)
2588 tracks[i].audio_hid = -1;
2589 tracks[i].id3_hid = -1;
2590 tracks[i].codec_hid = -1;
2591 #ifdef HAVE_ALBUMART
2592 tracks[i].aa_hid = -1;
2593 #endif
2596 add_event(BUFFER_EVENT_REBUFFER, false, buffering_handle_rebuffer_callback);
2597 add_event(BUFFER_EVENT_FINISHED, false, buffering_handle_finished_callback);
2599 /* Probably safe to say */
2600 audio_is_initialized = true;
2602 sound_settings_apply();
2603 #ifdef HAVE_DISK_STORAGE
2604 audio_set_buffer_margin(global_settings.buffer_margin);
2605 #endif
2607 /* it's safe to let the threads run now */
2608 #ifdef PLAYBACK_VOICE
2609 voice_thread_resume();
2610 #endif
2611 thread_thaw(codec_thread_id);
2612 thread_thaw(audio_thread_id);
2614 } /* audio_init */
2616 bool audio_is_thread_ready(void)
2618 return audio_thread_ready;