Fixes FS#8651 (noise and/or crash while crossfading). Latest ARM-asm submit for dsp...
[maemo-rb.git] / apps / playback.c
blob319f55a0ce548fe5c1eafb36d56266f01783f649
1 /***************************************************************************
2 * __________ __ ___.
3 * Open \______ \ ____ ____ | | _\_ |__ _______ ___
4 * Source | _// _ \_/ ___\| |/ /| __ \ / _ \ \/ /
5 * Jukebox | | ( <_> ) \___| < | \_\ ( <_> > < <
6 * Firmware |____|_ /\____/ \___ >__|_ \|___ /\____/__/\_ \
7 * \/ \/ \/ \/ \/
8 * $Id$
10 * Copyright (C) 2005 Miika Pekkarinen
12 * All files in this archive are subject to the GNU General Public License.
13 * See the file COPYING in the source tree root for full license agreement.
15 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
16 * KIND, either express or implied.
18 ****************************************************************************/
20 /* TODO: Pause should be handled in here, rather than PCMBUF so that voice can
21 * play whilst audio is paused */
23 #include <stdio.h>
24 #include <string.h>
25 #include <stdlib.h>
26 #include <ctype.h>
28 #include "system.h"
29 #include "thread.h"
30 #include "file.h"
31 #include "panic.h"
32 #include "memory.h"
33 #include "lcd.h"
34 #include "font.h"
35 #include "button.h"
36 #include "kernel.h"
37 #include "tree.h"
38 #include "debug.h"
39 #include "sprintf.h"
40 #include "settings.h"
41 #include "codecs.h"
42 #include "audio.h"
43 #include "buffering.h"
44 #include "voice_thread.h"
45 #include "mp3_playback.h"
46 #include "usb.h"
47 #include "status.h"
48 #include "ata.h"
49 #include "screens.h"
50 #include "playlist.h"
51 #include "playback.h"
52 #include "pcmbuf.h"
53 #include "buffer.h"
54 #include "dsp.h"
55 #include "abrepeat.h"
56 #include "cuesheet.h"
57 #ifdef HAVE_TAGCACHE
58 #include "tagcache.h"
59 #endif
60 #ifdef HAVE_LCD_BITMAP
61 #include "icons.h"
62 #include "peakmeter.h"
63 #include "action.h"
64 #include "albumart.h"
65 #endif
66 #include "lang.h"
67 #include "bookmark.h"
68 #include "misc.h"
69 #include "sound.h"
70 #include "metadata.h"
71 #include "splash.h"
72 #include "talk.h"
73 #include "ata_idle_notify.h"
75 #ifdef HAVE_RECORDING
76 #include "recording.h"
77 #include "talk.h"
78 #endif
80 #define PLAYBACK_VOICE
82 /* default point to start buffer refill */
83 #define AUDIO_DEFAULT_WATERMARK (1024*512)
84 /* amount of guess-space to allow for codecs that must hunt and peck
85 * for their correct seeek target, 32k seems a good size */
86 #define AUDIO_REBUFFER_GUESS_SIZE (1024*32)
88 /* Define LOGF_ENABLE to enable logf output in this file */
89 /*#define LOGF_ENABLE*/
90 #include "logf.h"
92 /* macros to enable logf for queues
93 logging on SYS_TIMEOUT can be disabled */
94 #ifdef SIMULATOR
95 /* Define this for logf output of all queuing except SYS_TIMEOUT */
96 #define PLAYBACK_LOGQUEUES
97 /* Define this to logf SYS_TIMEOUT messages */
98 /*#define PLAYBACK_LOGQUEUES_SYS_TIMEOUT*/
99 #endif
101 #ifdef PLAYBACK_LOGQUEUES
102 #define LOGFQUEUE logf
103 #else
104 #define LOGFQUEUE(...)
105 #endif
107 #ifdef PLAYBACK_LOGQUEUES_SYS_TIMEOUT
108 #define LOGFQUEUE_SYS_TIMEOUT logf
109 #else
110 #define LOGFQUEUE_SYS_TIMEOUT(...)
111 #endif
114 /* Define one constant that includes recording related functionality */
115 #if defined(HAVE_RECORDING) && !defined(SIMULATOR)
116 #define AUDIO_HAVE_RECORDING
117 #endif
119 enum {
120 Q_NULL = 0,
121 Q_AUDIO_PLAY = 1,
122 Q_AUDIO_STOP,
123 Q_AUDIO_PAUSE,
124 Q_AUDIO_SKIP,
125 Q_AUDIO_PRE_FF_REWIND,
126 Q_AUDIO_FF_REWIND,
127 Q_AUDIO_CHECK_NEW_TRACK,
128 Q_AUDIO_FLUSH,
129 Q_AUDIO_TRACK_CHANGED,
130 Q_AUDIO_DIR_SKIP,
131 Q_AUDIO_POSTINIT,
132 Q_AUDIO_FILL_BUFFER,
133 Q_CODEC_REQUEST_COMPLETE,
134 Q_CODEC_REQUEST_FAILED,
136 Q_CODEC_LOAD,
137 Q_CODEC_LOAD_DISK,
139 #ifdef AUDIO_HAVE_RECORDING
140 Q_ENCODER_LOAD_DISK,
141 Q_ENCODER_RECORD,
142 #endif
145 enum filling_state {
146 STATE_IDLE, /* audio is stopped: nothing to do */
147 STATE_FILLING, /* adding tracks to the buffer */
148 STATE_FULL, /* can't add any more tracks */
149 STATE_FINISHED, /* all remaining tracks have been added */
152 /* As defined in plugins/lib/xxx2wav.h */
153 #if MEM > 1
154 #define MALLOC_BUFSIZE (512*1024)
155 #define GUARD_BUFSIZE (32*1024)
156 #else
157 #define MALLOC_BUFSIZE (100*1024)
158 #define GUARD_BUFSIZE (8*1024)
159 #endif
161 /* As defined in plugin.lds */
162 #if defined(CPU_PP)
163 #define CODEC_IRAM_ORIGIN ((unsigned char *)0x4000c000)
164 #define CODEC_IRAM_SIZE ((size_t)0xc000)
165 #elif defined(IAUDIO_X5) || defined(IAUDIO_M5)
166 #define CODEC_IRAM_ORIGIN ((unsigned char *)0x10010000)
167 #define CODEC_IRAM_SIZE ((size_t)0x10000)
168 #else
169 #define CODEC_IRAM_ORIGIN ((unsigned char *)0x1000c000)
170 #define CODEC_IRAM_SIZE ((size_t)0xc000)
171 #endif
173 bool audio_is_initialized = false;
174 static bool audio_thread_ready NOCACHEBSS_ATTR = false;
176 /* Variables are commented with the threads that use them: *
177 * A=audio, C=codec, V=voice. A suffix of - indicates that *
178 * the variable is read but not updated on that thread. */
179 /* TBD: Split out "audio" and "playback" (ie. calling) threads */
181 /* Main state control */
182 static volatile bool audio_codec_loaded NOCACHEBSS_ATTR = false; /* Codec loaded? (C/A-) */
183 static volatile bool playing NOCACHEBSS_ATTR = false; /* Is audio playing? (A) */
184 static volatile bool paused NOCACHEBSS_ATTR = false; /* Is audio paused? (A/C-) */
186 /* Ring buffer where compressed audio and codecs are loaded */
187 static unsigned char *filebuf = NULL; /* Start of buffer (A/C-) */
188 static unsigned char *malloc_buf = NULL; /* Start of malloc buffer (A/C-) */
189 /* FIXME: make filebuflen static */
190 size_t filebuflen = 0; /* Size of buffer (A/C-) */
191 /* FIXME: make buf_ridx (C/A-) */
193 /* Possible arrangements of the buffer */
194 #define BUFFER_STATE_TRASHED -1 /* trashed; must be reset */
195 #define BUFFER_STATE_INITIALIZED 0 /* voice+audio OR audio-only */
196 #define BUFFER_STATE_VOICED_ONLY 1 /* voice-only */
197 static int buffer_state = BUFFER_STATE_TRASHED; /* Buffer state */
199 /* Used to keep the WPS up-to-date during track transtition */
200 static struct mp3entry prevtrack_id3;
202 /* Used to provide the codec with a pointer */
203 static struct mp3entry curtrack_id3;
205 /* Used to make next track info available while playing last track on buffer */
206 static struct mp3entry lasttrack_id3;
208 /* Track info structure about songs in the file buffer (A/C-) */
209 struct track_info {
210 int audio_hid; /* The ID for the track's buffer handle */
211 int id3_hid; /* The ID for the track's metadata handle */
212 int codec_hid; /* The ID for the track's codec handle */
213 #ifdef HAVE_ALBUMART
214 int aa_hid; /* The ID for the track's album art handle */
215 #endif
217 size_t filesize; /* File total length */
219 bool taginfo_ready; /* Is metadata read */
222 static struct track_info tracks[MAX_TRACK];
223 static volatile int track_ridx = 0; /* Track being decoded (A/C-) */
224 static int track_widx = 0; /* Track being buffered (A) */
226 #define CUR_TI (&tracks[track_ridx]) /* Playing track info pointer (A/C-) */
227 static struct track_info *prev_ti = NULL; /* Pointer to the previously played
228 track */
230 /* Set by the audio thread when the current track information has updated
231 * and the WPS may need to update its cached information */
232 static bool track_changed = false;
234 /* Information used only for filling the buffer */
235 /* Playlist steps from playing track to next track to be buffered (A) */
236 static int last_peek_offset = 0;
238 /* Scrobbler support */
239 static unsigned long prev_track_elapsed = 0; /* Previous track elapsed time (C/A-)*/
241 static enum filling_state filling;
243 /* Track change controls */
244 static bool automatic_skip = false; /* Who initiated in-progress skip? (C/A-) */
245 static bool playlist_end = false; /* Has the current playlist ended? (A) */
246 static bool auto_dir_skip = false; /* Have we changed dirs automatically? */
247 static bool dir_skip = false; /* Is a directory skip pending? (A) */
248 static bool new_playlist = false; /* Are we starting a new playlist? (A) */
249 static int wps_offset = 0; /* Pending track change offset, to keep WPS responsive (A) */
250 static bool skipped_during_pause = false; /* Do we need to clear the PCM buffer when playback resumes (A) */
252 /* Set to true if the codec thread should send an audio stop request
253 * (typically because the end of the playlist has been reached).
255 static bool codec_requested_stop = false;
257 static size_t buffer_margin = 0; /* Buffer margin aka anti-skip buffer (A/C-) */
259 /* Multiple threads */
260 /* Set the watermark to trigger buffer fill (A/C) FIXME */
261 static void set_filebuf_watermark(int seconds, size_t max);
263 /* Audio thread */
264 static struct event_queue audio_queue NOCACHEBSS_ATTR;
265 static struct queue_sender_list audio_queue_sender_list NOCACHEBSS_ATTR;
266 static long audio_stack[(DEFAULT_STACK_SIZE + 0x1000)/sizeof(long)];
267 static const char audio_thread_name[] = "audio";
269 static void audio_thread(void);
270 static void audio_initiate_track_change(long direction);
271 static bool audio_have_tracks(void);
272 static void audio_reset_buffer(void);
274 /* Codec thread */
275 extern struct codec_api ci;
276 static struct event_queue codec_queue NOCACHEBSS_ATTR;
277 static struct queue_sender_list codec_queue_sender_list;
278 static long codec_stack[(DEFAULT_STACK_SIZE + 0x2000)/sizeof(long)]
279 IBSS_ATTR;
280 static const char codec_thread_name[] = "codec";
281 struct thread_entry *codec_thread_p; /* For modifying thread priority later. */
283 /* PCM buffer messaging */
284 static struct event_queue pcmbuf_queue NOCACHEBSS_ATTR;
286 /* Function to be called by pcm buffer callbacks.
287 * Permissible Context(s): Audio interrupt
289 static void pcmbuf_callback_queue_post(long id, intptr_t data)
291 /* No lock since we're already in audio interrupt context */
292 queue_post(&pcmbuf_queue, id, data);
295 /* Scan the pcmbuf queue and return true if a message pulled.
296 * Permissible Context(s): Thread
298 static bool pcmbuf_queue_scan(struct queue_event *ev)
300 if (!queue_empty(&pcmbuf_queue))
302 /* Transfer message to audio queue */
303 pcm_play_lock();
304 /* Pull message - never, ever any blocking call! */
305 queue_wait_w_tmo(&pcmbuf_queue, ev, 0);
306 pcm_play_unlock();
307 return true;
310 return false;
313 /* Clear the pcmbuf queue of messages
314 * Permissible Context(s): Thread
316 static void pcmbuf_queue_clear(void)
318 pcm_play_lock();
319 queue_clear(&pcmbuf_queue);
320 pcm_play_unlock();
323 /* --- Helper functions --- */
325 static struct mp3entry *bufgetid3(int handle_id)
327 if (handle_id < 0)
328 return NULL;
330 struct mp3entry *id3;
331 ssize_t ret = bufgetdata(handle_id, 0, (void *)&id3);
333 if (ret < 0 || ret != sizeof(struct mp3entry))
334 return NULL;
336 return id3;
339 static bool clear_track_info(struct track_info *track)
341 /* bufclose returns true if the handle is not found, or if it is closed
342 * successfully, so these checks are safe on non-existant handles */
343 if (!track)
344 return false;
346 if (track->codec_hid >= 0) {
347 if (bufclose(track->codec_hid))
348 track->codec_hid = -1;
349 else
350 return false;
353 if (track->id3_hid >= 0) {
354 if (bufclose(track->id3_hid))
355 track->id3_hid = -1;
356 else
357 return false;
360 if (track->audio_hid >= 0) {
361 if (bufclose(track->audio_hid))
362 track->audio_hid = -1;
363 else
364 return false;
367 #ifdef HAVE_ALBUMART
368 if (track->aa_hid >= 0) {
369 if (bufclose(track->aa_hid))
370 track->aa_hid = -1;
371 else
372 return false;
374 #endif
376 track->filesize = 0;
377 track->taginfo_ready = false;
379 return true;
382 /* --- External interfaces --- */
384 /* This sends a stop message and the audio thread will dump all it's
385 subsequenct messages */
386 void audio_hard_stop(void)
388 /* Stop playback */
389 LOGFQUEUE("audio >| audio Q_AUDIO_STOP: 1");
390 queue_send(&audio_queue, Q_AUDIO_STOP, 1);
391 #ifdef PLAYBACK_VOICE
392 voice_stop();
393 #endif
396 bool audio_restore_playback(int type)
398 switch (type)
400 case AUDIO_WANT_PLAYBACK:
401 if (buffer_state != BUFFER_STATE_INITIALIZED)
402 audio_reset_buffer();
403 return true;
404 case AUDIO_WANT_VOICE:
405 if (buffer_state == BUFFER_STATE_TRASHED)
406 audio_reset_buffer();
407 return true;
408 default:
409 return false;
413 unsigned char *audio_get_buffer(bool talk_buf, size_t *buffer_size)
415 unsigned char *buf, *end;
417 if (audio_is_initialized)
419 audio_hard_stop();
421 /* else buffer_state will be BUFFER_STATE_TRASHED at this point */
423 if (buffer_size == NULL)
425 /* Special case for talk_init to use since it already knows it's
426 trashed */
427 buffer_state = BUFFER_STATE_TRASHED;
428 return NULL;
431 if (talk_buf || buffer_state == BUFFER_STATE_TRASHED
432 || !talk_voice_required())
434 logf("get buffer: talk, audio");
435 /* Ok to use everything from audiobuf to audiobufend - voice is loaded,
436 the talk buffer is not needed because voice isn't being used, or
437 could be BUFFER_STATE_TRASHED already. If state is
438 BUFFER_STATE_VOICED_ONLY, no problem as long as memory isn't written
439 without the caller knowing what's going on. Changing certain settings
440 may move it to a worse condition but the memory in use by something
441 else will remain undisturbed.
443 if (buffer_state != BUFFER_STATE_TRASHED)
445 talk_buffer_steal();
446 buffer_state = BUFFER_STATE_TRASHED;
449 buf = audiobuf;
450 end = audiobufend;
452 else
454 /* Safe to just return this if already BUFFER_STATE_VOICED_ONLY or
455 still BUFFER_STATE_INITIALIZED */
456 /* Skip talk buffer and move pcm buffer to end to maximize available
457 contiguous memory - no audio running means voice will not need the
458 swap space */
459 logf("get buffer: audio");
460 buf = audiobuf + talk_get_bufsize();
461 end = audiobufend - pcmbuf_init(audiobufend);
462 buffer_state = BUFFER_STATE_VOICED_ONLY;
465 *buffer_size = end - buf;
467 return buf;
470 #ifdef HAVE_RECORDING
471 unsigned char *audio_get_recording_buffer(size_t *buffer_size)
473 /* Stop audio, voice and obtain all available buffer space */
474 audio_hard_stop();
475 talk_buffer_steal();
477 unsigned char *end = audiobufend;
478 buffer_state = BUFFER_STATE_TRASHED;
479 *buffer_size = end - audiobuf;
481 return (unsigned char *)audiobuf;
484 bool audio_load_encoder(int afmt)
486 #ifndef SIMULATOR
487 const char *enc_fn = get_codec_filename(afmt | CODEC_TYPE_ENCODER);
488 if (!enc_fn)
489 return false;
491 audio_remove_encoder();
492 ci.enc_codec_loaded = 0; /* clear any previous error condition */
494 LOGFQUEUE("codec > Q_ENCODER_LOAD_DISK");
495 queue_post(&codec_queue, Q_ENCODER_LOAD_DISK, (intptr_t)enc_fn);
497 while (ci.enc_codec_loaded == 0)
498 yield();
500 logf("codec loaded: %d", ci.enc_codec_loaded);
502 return ci.enc_codec_loaded > 0;
503 #else
504 (void)afmt;
505 return true;
506 #endif
507 } /* audio_load_encoder */
509 void audio_remove_encoder(void)
511 #ifndef SIMULATOR
512 /* force encoder codec unload (if currently loaded) */
513 if (ci.enc_codec_loaded <= 0)
514 return;
516 ci.stop_encoder = true;
517 while (ci.enc_codec_loaded > 0)
518 yield();
519 #endif
520 } /* audio_remove_encoder */
522 #endif /* HAVE_RECORDING */
524 #ifdef HAVE_ALBUMART
525 int audio_current_aa_hid(void)
527 int cur_idx;
528 int offset = ci.new_track + wps_offset;
530 cur_idx = track_ridx + offset;
531 cur_idx &= MAX_TRACK_MASK;
533 return tracks[cur_idx].aa_hid;
535 #endif
537 struct mp3entry* audio_current_track(void)
539 const char *filename;
540 const char *p;
541 static struct mp3entry temp_id3;
542 int cur_idx;
543 int offset = ci.new_track + wps_offset;
545 cur_idx = (track_ridx + offset) & MAX_TRACK_MASK;
547 if (cur_idx == track_ridx && *curtrack_id3.path)
549 /* The usual case */
550 return &curtrack_id3;
552 else if (offset == -1 && *prevtrack_id3.path)
554 /* We're in a track transition. The codec has moved on to the nex track,
555 but the audio being played is still the same (now previous) track.
556 prevtrack_id3.elapsed is being updated in an ISR by
557 codec_pcmbuf_position_callback */
558 return &prevtrack_id3;
560 else if (tracks[cur_idx].id3_hid >= 0)
562 /* Get the ID3 metadata from the main buffer */
563 return bufgetid3(tracks[cur_idx].id3_hid);
566 /* We didn't find the ID3 metadata, so we fill temp_id3 with the little info
567 we have and return that. */
569 memset(&temp_id3, 0, sizeof(struct mp3entry));
571 filename = playlist_peek(0);
572 if (!filename)
573 filename = "No file!";
575 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
576 if (tagcache_fill_tags(&temp_id3, filename))
577 return &temp_id3;
578 #endif
580 p = strrchr(filename, '/');
581 if (!p)
582 p = filename;
583 else
584 p++;
586 strncpy(temp_id3.path, p, sizeof(temp_id3.path)-1);
587 temp_id3.title = &temp_id3.path[0];
589 return &temp_id3;
592 struct mp3entry* audio_next_track(void)
594 int next_idx;
595 int offset = ci.new_track + wps_offset;
597 if (!audio_have_tracks())
598 return NULL;
600 if (wps_offset == -1 && *prevtrack_id3.path)
602 /* We're in a track transition. The next track for the WPS is the one
603 currently being decoded. */
604 return &curtrack_id3;
607 next_idx = (track_ridx + offset + 1) & MAX_TRACK_MASK;
609 if (next_idx == track_widx)
611 /* The next track hasn't been buffered yet, so we return the static
612 version of its metadata. */
613 return &lasttrack_id3;
616 if (tracks[next_idx].id3_hid < 0)
617 return NULL;
618 else
619 return bufgetid3(tracks[next_idx].id3_hid);
622 bool audio_has_changed_track(void)
624 if (track_changed)
626 track_changed = false;
627 return true;
630 return false;
633 void audio_play(long offset)
635 logf("audio_play");
637 #ifdef PLAYBACK_VOICE
638 /* Truncate any existing voice output so we don't have spelling
639 * etc. over the first part of the played track */
640 talk_force_shutup();
641 #endif
643 /* Start playback */
644 LOGFQUEUE("audio >| audio Q_AUDIO_PLAY: %ld", offset);
645 /* Don't return until playback has actually started */
646 queue_send(&audio_queue, Q_AUDIO_PLAY, offset);
649 void audio_stop(void)
651 /* Stop playback */
652 LOGFQUEUE("audio >| audio Q_AUDIO_STOP");
653 /* Don't return until playback has actually stopped */
654 queue_send(&audio_queue, Q_AUDIO_STOP, 0);
657 void audio_pause(void)
659 LOGFQUEUE("audio >| audio Q_AUDIO_PAUSE");
660 /* Don't return until playback has actually paused */
661 queue_send(&audio_queue, Q_AUDIO_PAUSE, true);
664 void audio_resume(void)
666 LOGFQUEUE("audio >| audio Q_AUDIO_PAUSE resume");
667 /* Don't return until playback has actually resumed */
668 queue_send(&audio_queue, Q_AUDIO_PAUSE, false);
671 static void audio_skip(int direction)
673 if (playlist_check(ci.new_track + wps_offset + direction))
675 if (global_settings.beep)
676 pcmbuf_beep(5000, 100, 2500*global_settings.beep);
678 LOGFQUEUE("audio > audio Q_AUDIO_SKIP %d", direction);
679 queue_post(&audio_queue, Q_AUDIO_SKIP, direction);
680 /* Update wps while our message travels inside deep playback queues. */
681 wps_offset += direction;
682 /* Immediately update the playlist index */
683 playlist_next(direction);
684 track_changed = true;
686 else
688 /* No more tracks. */
689 if (global_settings.beep)
690 pcmbuf_beep(1000, 100, 1000*global_settings.beep);
694 void audio_next(void)
696 audio_skip(1);
699 void audio_prev(void)
701 audio_skip(-1);
704 void audio_next_dir(void)
706 LOGFQUEUE("audio > audio Q_AUDIO_DIR_SKIP 1");
707 queue_post(&audio_queue, Q_AUDIO_DIR_SKIP, 1);
710 void audio_prev_dir(void)
712 LOGFQUEUE("audio > audio Q_AUDIO_DIR_SKIP -1");
713 queue_post(&audio_queue, Q_AUDIO_DIR_SKIP, -1);
716 void audio_pre_ff_rewind(void)
718 LOGFQUEUE("audio > audio Q_AUDIO_PRE_FF_REWIND");
719 queue_post(&audio_queue, Q_AUDIO_PRE_FF_REWIND, 0);
722 void audio_ff_rewind(long newpos)
724 LOGFQUEUE("audio > audio Q_AUDIO_FF_REWIND");
725 queue_post(&audio_queue, Q_AUDIO_FF_REWIND, newpos);
728 void audio_flush_and_reload_tracks(void)
730 LOGFQUEUE("audio > audio Q_AUDIO_FLUSH");
731 queue_post(&audio_queue, Q_AUDIO_FLUSH, 0);
734 void audio_error_clear(void)
736 #ifdef AUDIO_HAVE_RECORDING
737 pcm_rec_error_clear();
738 #endif
741 int audio_status(void)
743 int ret = 0;
745 if (playing)
746 ret |= AUDIO_STATUS_PLAY;
748 if (paused)
749 ret |= AUDIO_STATUS_PAUSE;
751 #ifdef HAVE_RECORDING
752 /* Do this here for constitency with mpeg.c version */
753 ret |= pcm_rec_status();
754 #endif
756 return ret;
759 int audio_get_file_pos(void)
761 return 0;
764 #ifndef HAVE_FLASH_STORAGE
765 void audio_set_buffer_margin(int setting)
767 static const int lookup[] = {5, 15, 30, 60, 120, 180, 300, 600};
768 buffer_margin = lookup[setting];
769 logf("buffer margin: %ld", (long)buffer_margin);
770 set_filebuf_watermark(buffer_margin, 0);
772 #endif
774 /* Take necessary steps to enable or disable the crossfade setting */
775 void audio_set_crossfade(int enable)
777 size_t offset;
778 bool was_playing;
779 size_t size;
781 /* Tell it the next setting to use */
782 pcmbuf_crossfade_enable(enable);
784 /* Return if size hasn't changed or this is too early to determine
785 which in the second case there's no way we could be playing
786 anything at all */
787 if (pcmbuf_is_same_size())
789 /* This function is a copout and just syncs some variables -
790 to be removed at a later date */
791 pcmbuf_crossfade_enable_finished();
792 return;
795 offset = 0;
796 was_playing = playing;
798 /* Playback has to be stopped before changing the buffer size */
799 if (was_playing)
801 /* Store the track resume position */
802 offset = curtrack_id3.offset;
803 gui_syncsplash(0, str(LANG_RESTARTING_PLAYBACK));
806 /* Blast it - audio buffer will have to be setup again next time
807 something plays */
808 audio_get_buffer(true, &size);
810 /* Restart playback if audio was running previously */
811 if (was_playing)
812 audio_play(offset);
815 /* --- Routines called from multiple threads --- */
817 static void set_filebuf_watermark(int seconds, size_t max)
819 size_t bytes;
821 if (!filebuf)
822 return; /* Audio buffers not yet set up */
824 bytes = seconds?MAX(curtrack_id3.bitrate * seconds * (1000/8), max):max;
825 bytes = MIN(bytes, filebuflen / 2);
826 buf_set_watermark(bytes);
829 const char *get_codec_filename(int cod_spec)
831 const char *fname;
833 #ifdef HAVE_RECORDING
834 /* Can choose decoder or encoder if one available */
835 int type = cod_spec & CODEC_TYPE_MASK;
836 int afmt = cod_spec & CODEC_AFMT_MASK;
838 if ((unsigned)afmt >= AFMT_NUM_CODECS)
839 type = AFMT_UNKNOWN | (type & CODEC_TYPE_MASK);
841 fname = (type == CODEC_TYPE_ENCODER) ?
842 audio_formats[afmt].codec_enc_root_fn :
843 audio_formats[afmt].codec_root_fn;
845 logf("%s: %d - %s",
846 (type == CODEC_TYPE_ENCODER) ? "Encoder" : "Decoder",
847 afmt, fname ? fname : "<unknown>");
848 #else /* !HAVE_RECORDING */
849 /* Always decoder */
850 if ((unsigned)cod_spec >= AFMT_NUM_CODECS)
851 cod_spec = AFMT_UNKNOWN;
852 fname = audio_formats[cod_spec].codec_root_fn;
853 logf("Codec: %d - %s", cod_spec, fname ? fname : "<unknown>");
854 #endif /* HAVE_RECORDING */
856 return fname;
857 } /* get_codec_filename */
859 /* --- Codec thread --- */
860 static bool codec_pcmbuf_insert_callback(
861 const void *ch1, const void *ch2, int count)
863 const char *src[2] = { ch1, ch2 };
865 while (count > 0)
867 int out_count = dsp_output_count(ci.dsp, count);
868 int inp_count;
869 char *dest;
871 /* Prevent audio from a previous track from playing */
872 if (ci.new_track || ci.stop_codec)
873 return true;
875 while ((dest = pcmbuf_request_buffer(&out_count)) == NULL)
877 cancel_cpu_boost();
878 sleep(1);
879 if (ci.seek_time || ci.new_track || ci.stop_codec)
880 return true;
883 /* Get the real input_size for output_size bytes, guarding
884 * against resampling buffer overflows. */
885 inp_count = dsp_input_count(ci.dsp, out_count);
887 if (inp_count <= 0)
888 return true;
890 /* Input size has grown, no error, just don't write more than length */
891 if (inp_count > count)
892 inp_count = count;
894 out_count = dsp_process(ci.dsp, dest, src, inp_count);
896 if (out_count <= 0)
897 return true;
899 pcmbuf_write_complete(out_count);
901 count -= inp_count;
904 return true;
905 } /* codec_pcmbuf_insert_callback */
907 static void* codec_get_memory_callback(size_t *size)
909 *size = MALLOC_BUFSIZE;
910 return malloc_buf;
913 /* Between the codec and PCM track change, we need to keep updating the
914 "elapsed" value of the previous (to the codec, but current to the
915 user/PCM/WPS) track, so that the progressbar reaches the end.
916 During that transition, the WPS will display prevtrack_id3. */
917 static void codec_pcmbuf_position_callback(size_t size) ICODE_ATTR;
918 static void codec_pcmbuf_position_callback(size_t size)
920 /* This is called from an ISR, so be quick */
921 unsigned int time = size * 1000 / 4 / NATIVE_FREQUENCY +
922 prevtrack_id3.elapsed;
924 if (time >= prevtrack_id3.length)
926 pcmbuf_set_position_callback(NULL);
927 prevtrack_id3.elapsed = prevtrack_id3.length;
929 else
930 prevtrack_id3.elapsed = time;
933 static void codec_set_elapsed_callback(unsigned int value)
935 unsigned int latency;
936 if (ci.seek_time)
937 return;
939 #ifdef AB_REPEAT_ENABLE
940 ab_position_report(value);
941 #endif
943 latency = pcmbuf_get_latency();
944 if (value < latency)
945 curtrack_id3.elapsed = 0;
946 else if (value - latency > curtrack_id3.elapsed ||
947 value - latency < curtrack_id3.elapsed - 2)
949 curtrack_id3.elapsed = value - latency;
953 static void codec_set_offset_callback(size_t value)
955 unsigned int latency;
957 if (ci.seek_time)
958 return;
960 latency = pcmbuf_get_latency() * curtrack_id3.bitrate / 8;
961 if (value < latency)
962 curtrack_id3.offset = 0;
963 else
964 curtrack_id3.offset = value - latency;
967 static void codec_advance_buffer_counters(size_t amount)
969 bufadvance(CUR_TI->audio_hid, amount);
970 ci.curpos += amount;
973 /* copy up-to size bytes into ptr and return the actual size copied */
974 static size_t codec_filebuf_callback(void *ptr, size_t size)
976 ssize_t copy_n;
978 if (ci.stop_codec || !playing)
979 return 0;
981 copy_n = bufread(CUR_TI->audio_hid, size, ptr);
983 /* Nothing requested OR nothing left */
984 if (copy_n == 0)
985 return 0;
987 /* Update read and other position pointers */
988 codec_advance_buffer_counters(copy_n);
990 /* Return the actual amount of data copied to the buffer */
991 return copy_n;
992 } /* codec_filebuf_callback */
994 static void* codec_request_buffer_callback(size_t *realsize, size_t reqsize)
996 size_t copy_n = reqsize;
997 ssize_t ret;
998 void *ptr;
1000 if (!playing)
1002 *realsize = 0;
1003 return NULL;
1006 ret = bufgetdata(CUR_TI->audio_hid, reqsize, &ptr);
1007 if (ret >= 0)
1008 copy_n = MIN((size_t)ret, reqsize);
1010 if (copy_n == 0)
1012 *realsize = 0;
1013 return NULL;
1016 *realsize = copy_n;
1018 return ptr;
1019 } /* codec_request_buffer_callback */
1021 static int get_codec_base_type(int type)
1023 switch (type) {
1024 case AFMT_MPA_L1:
1025 case AFMT_MPA_L2:
1026 case AFMT_MPA_L3:
1027 return AFMT_MPA_L3;
1030 return type;
1033 static void codec_advance_buffer_callback(size_t amount)
1035 codec_advance_buffer_counters(amount);
1036 codec_set_offset_callback(ci.curpos);
1039 static void codec_advance_buffer_loc_callback(void *ptr)
1041 size_t amount = buf_get_offset(CUR_TI->audio_hid, ptr);
1042 codec_advance_buffer_callback(amount);
1045 static void codec_seek_complete_callback(void)
1047 logf("seek_complete");
1048 if (pcm_is_paused())
1050 /* If this is not a seamless seek, clear the buffer */
1051 pcmbuf_play_stop();
1052 dsp_configure(ci.dsp, DSP_FLUSH, 0);
1054 /* If playback was not 'deliberately' paused, unpause now */
1055 if (!paused)
1056 pcmbuf_pause(false);
1058 ci.seek_time = 0;
1061 static bool codec_seek_buffer_callback(size_t newpos)
1063 logf("codec_seek_buffer_callback");
1065 int ret = bufseek(CUR_TI->audio_hid, newpos);
1066 if (ret == 0) {
1067 ci.curpos = newpos;
1068 return true;
1070 else {
1071 return false;
1075 static void codec_configure_callback(int setting, intptr_t value)
1077 switch (setting) {
1078 case CODEC_SET_FILEBUF_WATERMARK:
1079 set_filebuf_watermark(buffer_margin, value);
1080 break;
1082 default:
1083 if (!dsp_configure(ci.dsp, setting, value))
1084 { logf("Illegal key:%d", setting); }
1088 static void codec_track_changed(void)
1090 LOGFQUEUE("codec > audio Q_AUDIO_TRACK_CHANGED");
1091 queue_post(&audio_queue, Q_AUDIO_TRACK_CHANGED, 0);
1094 static void codec_pcmbuf_track_changed_callback(void)
1096 pcmbuf_set_position_callback(NULL);
1097 pcmbuf_callback_queue_post(Q_AUDIO_TRACK_CHANGED, 0);
1100 static void codec_discard_codec_callback(void)
1102 if (CUR_TI->codec_hid >= 0)
1104 bufclose(CUR_TI->codec_hid);
1105 CUR_TI->codec_hid = -1;
1109 static inline void codec_gapless_track_change(void)
1111 /* callback keeps the progress bar moving while the pcmbuf empties */
1112 pcmbuf_set_position_callback(codec_pcmbuf_position_callback);
1113 /* set the pcmbuf callback for when the track really changes */
1114 pcmbuf_set_event_handler(codec_pcmbuf_track_changed_callback);
1117 static inline void codec_crossfade_track_change(void)
1119 /* Initiate automatic crossfade mode */
1120 pcmbuf_crossfade_init(false);
1121 /* Notify the wps that the track change starts now */
1122 codec_track_changed();
1125 static void codec_track_skip_done(bool was_manual)
1127 /* Manual track change (always crossfade or flush audio). */
1128 if (was_manual)
1130 pcmbuf_crossfade_init(true);
1131 LOGFQUEUE("codec > audio Q_AUDIO_TRACK_CHANGED");
1132 queue_post(&audio_queue, Q_AUDIO_TRACK_CHANGED, 0);
1134 /* Automatic track change w/crossfade, if not in "Track Skip Only" mode. */
1135 else if (pcmbuf_is_crossfade_enabled() && !pcmbuf_is_crossfade_active()
1136 && global_settings.crossfade != CROSSFADE_ENABLE_TRACKSKIP)
1138 if (global_settings.crossfade == CROSSFADE_ENABLE_SHUFFLE_AND_TRACKSKIP)
1140 if (global_settings.playlist_shuffle)
1141 /* shuffle mode is on, so crossfade: */
1142 codec_crossfade_track_change();
1143 else
1144 /* shuffle mode is off, so do a gapless track change */
1145 codec_gapless_track_change();
1147 else
1148 /* normal crossfade: */
1149 codec_crossfade_track_change();
1151 else
1152 /* normal gapless playback. */
1153 codec_gapless_track_change();
1156 static bool codec_load_next_track(void)
1158 intptr_t result = Q_CODEC_REQUEST_FAILED;
1160 prev_track_elapsed = curtrack_id3.elapsed;
1162 #ifdef AB_REPEAT_ENABLE
1163 ab_end_of_track_report();
1164 #endif
1166 logf("Request new track");
1168 if (ci.new_track == 0)
1170 ci.new_track++;
1171 automatic_skip = true;
1174 if (!ci.stop_codec)
1176 trigger_cpu_boost();
1177 LOGFQUEUE("codec >| audio Q_AUDIO_CHECK_NEW_TRACK");
1178 result = queue_send(&audio_queue, Q_AUDIO_CHECK_NEW_TRACK, 0);
1181 switch (result)
1183 case Q_CODEC_REQUEST_COMPLETE:
1184 LOGFQUEUE("codec |< Q_CODEC_REQUEST_COMPLETE");
1185 codec_track_skip_done(!automatic_skip);
1186 return true;
1188 case Q_CODEC_REQUEST_FAILED:
1189 LOGFQUEUE("codec |< Q_CODEC_REQUEST_FAILED");
1190 ci.new_track = 0;
1191 ci.stop_codec = true;
1192 codec_requested_stop = true;
1193 return false;
1195 default:
1196 LOGFQUEUE("codec |< default");
1197 ci.stop_codec = true;
1198 codec_requested_stop = true;
1199 return false;
1203 static bool codec_request_next_track_callback(void)
1205 int prev_codectype;
1207 if (ci.stop_codec || !playing)
1208 return false;
1210 prev_codectype = get_codec_base_type(curtrack_id3.codectype);
1212 if (!codec_load_next_track())
1213 return false;
1215 /* Check if the next codec is the same file. */
1216 if (prev_codectype == get_codec_base_type(curtrack_id3.codectype))
1218 logf("New track loaded");
1219 codec_discard_codec_callback();
1220 return true;
1222 else
1224 logf("New codec:%d/%d", curtrack_id3.codectype, prev_codectype);
1225 return false;
1229 static void codec_thread(void)
1231 struct queue_event ev;
1232 int status;
1234 while (1) {
1235 status = 0;
1237 if (!pcmbuf_is_crossfade_active()) {
1238 cancel_cpu_boost();
1241 queue_wait(&codec_queue, &ev);
1242 codec_requested_stop = false;
1244 switch (ev.id) {
1245 case Q_CODEC_LOAD_DISK:
1246 LOGFQUEUE("codec < Q_CODEC_LOAD_DISK");
1247 queue_reply(&codec_queue, 1);
1248 audio_codec_loaded = true;
1249 ci.stop_codec = false;
1250 status = codec_load_file((const char *)ev.data, &ci);
1251 break;
1253 case Q_CODEC_LOAD:
1254 LOGFQUEUE("codec < Q_CODEC_LOAD");
1255 if (CUR_TI->codec_hid < 0) {
1256 logf("Codec slot is empty!");
1257 /* Wait for the pcm buffer to go empty */
1258 while (pcm_is_playing())
1259 yield();
1260 /* This must be set to prevent an infinite loop */
1261 ci.stop_codec = true;
1262 LOGFQUEUE("codec > codec Q_AUDIO_PLAY");
1263 queue_post(&codec_queue, Q_AUDIO_PLAY, 0);
1264 break;
1267 audio_codec_loaded = true;
1268 ci.stop_codec = false;
1269 status = codec_load_buf(CUR_TI->codec_hid, &ci);
1270 break;
1272 #ifdef AUDIO_HAVE_RECORDING
1273 case Q_ENCODER_LOAD_DISK:
1274 LOGFQUEUE("codec < Q_ENCODER_LOAD_DISK");
1275 audio_codec_loaded = false; /* Not audio codec! */
1276 logf("loading encoder");
1277 ci.stop_encoder = false;
1278 status = codec_load_file((const char *)ev.data, &ci);
1279 logf("encoder stopped");
1280 break;
1281 #endif /* AUDIO_HAVE_RECORDING */
1283 default:
1284 LOGFQUEUE("codec < default");
1287 if (audio_codec_loaded)
1289 if (ci.stop_codec)
1291 status = CODEC_OK;
1292 if (!playing)
1293 pcmbuf_play_stop();
1296 audio_codec_loaded = false;
1299 switch (ev.id) {
1300 case Q_CODEC_LOAD_DISK:
1301 case Q_CODEC_LOAD:
1302 LOGFQUEUE("codec < Q_CODEC_LOAD");
1303 if (playing)
1305 if (ci.new_track || status != CODEC_OK)
1307 if (!ci.new_track)
1309 logf("Codec failure");
1310 gui_syncsplash(HZ*2, "Codec failure");
1313 if (!codec_load_next_track())
1315 LOGFQUEUE("codec > audio Q_AUDIO_STOP");
1316 /* End of playlist */
1317 queue_post(&audio_queue, Q_AUDIO_STOP, 0);
1318 break;
1321 else
1323 logf("Codec finished");
1324 if (ci.stop_codec)
1326 /* Wait for the audio to stop playing before
1327 * triggering the WPS exit */
1328 while(pcm_is_playing())
1330 curtrack_id3.elapsed =
1331 curtrack_id3.length - pcmbuf_get_latency();
1332 sleep(1);
1335 if (codec_requested_stop)
1337 LOGFQUEUE("codec > audio Q_AUDIO_STOP");
1338 queue_post(&audio_queue, Q_AUDIO_STOP, 0);
1340 break;
1344 if (CUR_TI->codec_hid >= 0)
1346 LOGFQUEUE("codec > codec Q_CODEC_LOAD");
1347 queue_post(&codec_queue, Q_CODEC_LOAD, 0);
1349 else
1351 const char *codec_fn =
1352 get_codec_filename(curtrack_id3.codectype);
1353 if (codec_fn)
1355 LOGFQUEUE("codec > codec Q_CODEC_LOAD_DISK");
1356 queue_post(&codec_queue, Q_CODEC_LOAD_DISK,
1357 (intptr_t)codec_fn);
1361 break;
1363 #ifdef AUDIO_HAVE_RECORDING
1364 case Q_ENCODER_LOAD_DISK:
1365 LOGFQUEUE("codec < Q_ENCODER_LOAD_DISK");
1367 if (status == CODEC_OK)
1368 break;
1370 logf("Encoder failure");
1371 gui_syncsplash(HZ*2, "Encoder failure");
1373 if (ci.enc_codec_loaded < 0)
1374 break;
1376 logf("Encoder failed to load");
1377 ci.enc_codec_loaded = -1;
1378 break;
1379 #endif /* AUDIO_HAVE_RECORDING */
1381 default:
1382 LOGFQUEUE("codec < default");
1384 } /* end switch */
1389 /* --- Audio thread --- */
1391 static bool audio_have_tracks(void)
1393 return (audio_track_count() != 0);
1396 static int audio_free_track_count(void)
1398 /* Used tracks + free tracks adds up to MAX_TRACK - 1 */
1399 return MAX_TRACK - 1 - audio_track_count();
1402 int audio_track_count(void)
1404 /* Calculate difference from track_ridx to track_widx
1405 * taking into account a possible wrap-around. */
1406 return (MAX_TRACK + track_widx - track_ridx) & MAX_TRACK_MASK;
1409 long audio_filebufused(void)
1411 return (long) buf_used();
1414 /* Update track info after successful a codec track change */
1415 static void audio_update_trackinfo(void)
1417 /* Load the curent track's metadata into curtrack_id3 */
1418 CUR_TI->taginfo_ready = (CUR_TI->id3_hid >= 0);
1419 if (CUR_TI->id3_hid >= 0)
1420 copy_mp3entry(&curtrack_id3, bufgetid3(CUR_TI->id3_hid));
1422 int next_idx = (track_ridx + 1) & MAX_TRACK_MASK;
1423 tracks[next_idx].taginfo_ready = (tracks[next_idx].id3_hid >= 0);
1425 /* Reset current position */
1426 curtrack_id3.elapsed = 0;
1427 curtrack_id3.offset = 0;
1429 /* Update the codec API */
1430 ci.filesize = CUR_TI->filesize;
1431 ci.id3 = &curtrack_id3;
1432 ci.curpos = 0;
1433 ci.taginfo_ready = &CUR_TI->taginfo_ready;
1436 static void buffering_audio_callback(enum callback_event ev, int value)
1438 (void)value;
1439 logf("buffering_audio_callback");
1441 switch (ev)
1443 case EVENT_BUFFER_LOW:
1444 if (filling == STATE_FULL) {
1445 /* force a refill */
1446 LOGFQUEUE("buffering > audio Q_AUDIO_FILL_BUFFER");
1447 queue_post(&audio_queue, Q_AUDIO_FILL_BUFFER, 0);
1449 break;
1451 case EVENT_HANDLE_REBUFFER:
1452 LOGFQUEUE("audio >| audio Q_AUDIO_FLUSH");
1453 queue_send(&audio_queue, Q_AUDIO_FLUSH, 0);
1454 break;
1456 case EVENT_HANDLE_FINISHED:
1457 logf("handle %d finished buffering", value);
1458 strip_tags(value);
1459 break;
1461 default:
1462 break;
1466 /* Clear tracks between write and read, non inclusive */
1467 static void audio_clear_track_entries(void)
1469 int cur_idx = track_widx;
1471 logf("Clearing tracks:%d/%d", track_ridx, track_widx);
1473 /* Loop over all tracks from write-to-read */
1474 while (1)
1476 cur_idx = (cur_idx + 1) & MAX_TRACK_MASK;
1478 if (cur_idx == track_ridx)
1479 break;
1481 clear_track_info(&tracks[cur_idx]);
1485 /* Clear all tracks */
1486 static bool audio_release_tracks(void)
1488 int i, cur_idx;
1490 logf("releasing all tracks");
1492 for(i = 0; i < MAX_TRACK; i++)
1494 cur_idx = (track_ridx + i) & MAX_TRACK_MASK;
1495 if (!clear_track_info(&tracks[cur_idx]))
1496 return false;
1499 return true;
1502 static bool audio_loadcodec(bool start_play)
1504 int prev_track;
1505 char codec_path[MAX_PATH]; /* Full path to codec */
1507 if (tracks[track_widx].id3_hid < 0) {
1508 return false;
1511 const char * codec_fn =
1512 get_codec_filename(bufgetid3(tracks[track_widx].id3_hid)->codectype);
1513 if (codec_fn == NULL)
1514 return false;
1516 tracks[track_widx].codec_hid = -1;
1518 if (start_play)
1520 /* Load the codec directly from disk and save some memory. */
1521 track_ridx = track_widx;
1522 ci.filesize = CUR_TI->filesize;
1523 ci.id3 = &curtrack_id3;
1524 ci.taginfo_ready = &CUR_TI->taginfo_ready;
1525 ci.curpos = 0;
1526 LOGFQUEUE("codec > codec Q_CODEC_LOAD_DISK");
1527 queue_post(&codec_queue, Q_CODEC_LOAD_DISK, (intptr_t)codec_fn);
1528 return true;
1530 else
1532 /* If we already have another track than this one buffered */
1533 if (track_widx != track_ridx)
1535 prev_track = (track_widx - 1) & MAX_TRACK_MASK;
1537 /* If the previous codec is the same as this one, there is no need
1538 * to put another copy of it on the file buffer */
1539 if (get_codec_base_type(
1540 bufgetid3(tracks[track_widx].id3_hid)->codectype) ==
1541 get_codec_base_type(
1542 bufgetid3(tracks[prev_track].id3_hid)->codectype)
1543 && audio_codec_loaded)
1545 logf("Reusing prev. codec");
1546 return true;
1551 codec_get_full_path(codec_path, codec_fn);
1553 tracks[track_widx].codec_hid = bufopen(codec_path, 0, TYPE_CODEC);
1554 if (tracks[track_widx].codec_hid < 0)
1555 return false;
1557 logf("Loaded codec");
1559 return true;
1562 /* TODO: Copied from mpeg.c. Should be moved somewhere else. */
1563 static void audio_set_elapsed(struct mp3entry* id3)
1565 unsigned long offset = id3->offset > id3->first_frame_offset ?
1566 id3->offset - id3->first_frame_offset : 0;
1568 if ( id3->vbr ) {
1569 if ( id3->has_toc ) {
1570 /* calculate elapsed time using TOC */
1571 int i;
1572 unsigned int remainder, plen, relpos, nextpos;
1574 /* find wich percent we're at */
1575 for (i=0; i<100; i++ )
1576 if ( offset < id3->toc[i] * (id3->filesize / 256) )
1577 break;
1579 i--;
1580 if (i < 0)
1581 i = 0;
1583 relpos = id3->toc[i];
1585 if (i < 99)
1586 nextpos = id3->toc[i+1];
1587 else
1588 nextpos = 256;
1590 remainder = offset - (relpos * (id3->filesize / 256));
1592 /* set time for this percent (divide before multiply to prevent
1593 overflow on long files. loss of precision is negligible on
1594 short files) */
1595 id3->elapsed = i * (id3->length / 100);
1597 /* calculate remainder time */
1598 plen = (nextpos - relpos) * (id3->filesize / 256);
1599 id3->elapsed += (((remainder * 100) / plen) *
1600 (id3->length / 10000));
1602 else {
1603 /* no TOC exists. set a rough estimate using average bitrate */
1604 int tpk = id3->length /
1605 ((id3->filesize - id3->first_frame_offset - id3->id3v1len) /
1606 1024);
1607 id3->elapsed = offset / 1024 * tpk;
1610 else
1612 /* constant bitrate, use exact calculation */
1613 if (id3->bitrate != 0)
1614 id3->elapsed = offset / (id3->bitrate / 8);
1618 /* Load one track by making the appropriate bufopen calls. Return true if
1619 everything required was loaded correctly, false if not. */
1620 static bool audio_load_track(int offset, bool start_play)
1622 const char *trackname;
1623 char msgbuf[80];
1624 int fd = -1;
1625 int file_offset = 0;
1626 struct mp3entry id3;
1628 /* Stop buffer filling if there is no free track entries.
1629 Don't fill up the last track entry (we wan't to store next track
1630 metadata there). */
1631 if (!audio_free_track_count())
1633 logf("No free tracks");
1634 return false;
1637 last_peek_offset++;
1638 tracks[track_widx].taginfo_ready = false;
1640 peek_again:
1641 logf("Buffering track:%d/%d", track_widx, track_ridx);
1642 /* Get track name from current playlist read position. */
1643 while ((trackname = playlist_peek(last_peek_offset)) != NULL)
1645 /* Handle broken playlists. */
1646 fd = open(trackname, O_RDONLY);
1647 if (fd < 0)
1649 logf("Open failed");
1650 /* Skip invalid entry from playlist. */
1651 playlist_skip_entry(NULL, last_peek_offset);
1653 else
1654 break;
1657 if (!trackname)
1659 logf("End-of-playlist");
1660 playlist_end = true;
1661 memset(&lasttrack_id3, 0, sizeof(struct mp3entry));
1662 filling = STATE_FINISHED;
1663 return false;
1666 tracks[track_widx].filesize = filesize(fd);
1668 if ((unsigned)offset > tracks[track_widx].filesize)
1669 offset = 0;
1671 /* Set default values */
1672 if (start_play)
1674 buf_set_watermark(AUDIO_DEFAULT_WATERMARK);
1675 dsp_configure(ci.dsp, DSP_RESET, 0);
1676 track_changed = true;
1677 playlist_update_resume_info(audio_current_track());
1680 /* Get track metadata if we don't already have it. */
1681 if (tracks[track_widx].id3_hid < 0)
1683 if (get_metadata(&id3, fd, trackname))
1685 send_event(PLAYBACK_EVENT_TRACK_BUFFER, &id3);
1687 tracks[track_widx].id3_hid =
1688 bufalloc(&id3, sizeof(struct mp3entry), TYPE_ID3);
1690 if (tracks[track_widx].id3_hid < 0)
1692 last_peek_offset--;
1693 close(fd);
1694 copy_mp3entry(&lasttrack_id3, &id3);
1695 goto buffer_full;
1698 if (track_widx == track_ridx)
1699 copy_mp3entry(&curtrack_id3, &id3);
1701 if (start_play)
1703 track_changed = true;
1704 playlist_update_resume_info(audio_current_track());
1707 else
1709 logf("mde:%s!",trackname);
1711 /* Skip invalid entry from playlist. */
1712 playlist_skip_entry(NULL, last_peek_offset);
1713 close(fd);
1714 goto peek_again;
1719 close(fd);
1721 #if 0
1722 if (cuesheet_is_enabled() && tracks[track_widx].id3.cuesheet_type == 1)
1724 char cuepath[MAX_PATH];
1726 struct cuesheet *cue = start_play ? curr_cue : temp_cue;
1728 if (look_for_cuesheet_file(trackname, cuepath) &&
1729 parse_cuesheet(cuepath, cue))
1731 strcpy((cue)->audio_filename, trackname);
1732 if (start_play)
1733 cue_spoof_id3(curr_cue, &tracks[track_widx].id3);
1736 #endif
1738 struct mp3entry *track_id3;
1740 if (track_widx == track_ridx)
1741 track_id3 = &curtrack_id3;
1742 else
1743 track_id3 = bufgetid3(tracks[track_widx].id3_hid);
1745 #ifdef HAVE_ALBUMART
1746 if (tracks[track_widx].aa_hid < 0 && gui_sync_wps_uses_albumart())
1748 char aa_path[MAX_PATH];
1749 if (find_albumart(track_id3, aa_path, sizeof(aa_path)))
1750 tracks[track_widx].aa_hid = bufopen(aa_path, 0, TYPE_BITMAP);
1752 #endif
1754 /* Load the codec. */
1755 if (!audio_loadcodec(start_play))
1757 if (tracks[track_widx].codec_hid == ERR_BUFFER_FULL)
1759 /* No space for codec on buffer, not an error */
1760 goto buffer_full;
1763 /* This is an error condition, either no codec was found, or reading
1764 * the codec file failed part way through, either way, skip the track */
1765 snprintf(msgbuf, sizeof(msgbuf)-1, "No codec for: %s", trackname);
1766 /* We should not use gui_syncplash from audio thread! */
1767 gui_syncsplash(HZ*2, msgbuf);
1768 /* Skip invalid entry from playlist. */
1769 playlist_skip_entry(NULL, last_peek_offset);
1770 goto peek_again;
1773 track_id3->elapsed = 0;
1775 enum data_type type = TYPE_PACKET_AUDIO;
1777 switch (track_id3->codectype) {
1778 case AFMT_MPA_L1:
1779 case AFMT_MPA_L2:
1780 case AFMT_MPA_L3:
1781 if (offset > 0) {
1782 file_offset = offset;
1783 track_id3->offset = offset;
1784 audio_set_elapsed(track_id3);
1786 break;
1788 case AFMT_WAVPACK:
1789 if (offset > 0) {
1790 file_offset = offset;
1791 track_id3->offset = offset;
1792 track_id3->elapsed = track_id3->length / 2;
1794 break;
1796 case AFMT_OGG_VORBIS:
1797 case AFMT_SPEEX:
1798 case AFMT_FLAC:
1799 case AFMT_PCM_WAV:
1800 case AFMT_A52:
1801 case AFMT_AAC:
1802 case AFMT_MPC:
1803 case AFMT_APE:
1804 if (offset > 0)
1805 track_id3->offset = offset;
1806 break;
1808 case AFMT_NSF:
1809 case AFMT_SPC:
1810 case AFMT_SID:
1811 logf("Loading atomic %d",track_id3->codectype);
1812 type = TYPE_ATOMIC_AUDIO;
1813 break;
1816 logf("alt:%s", trackname);
1818 if (file_offset > AUDIO_REBUFFER_GUESS_SIZE)
1819 file_offset -= AUDIO_REBUFFER_GUESS_SIZE;
1820 else if (track_id3->first_frame_offset)
1821 file_offset = track_id3->first_frame_offset;
1822 else
1823 file_offset = 0;
1825 tracks[track_widx].audio_hid = bufopen(trackname, file_offset, type);
1827 if (tracks[track_widx].audio_hid < 0)
1828 goto buffer_full;
1830 /* All required data is now available for the codec. */
1831 tracks[track_widx].taginfo_ready = true;
1833 if (start_play)
1835 ci.curpos=file_offset;
1836 buf_request_buffer_handle(tracks[track_widx].audio_hid);
1839 track_widx = (track_widx + 1) & MAX_TRACK_MASK;
1841 return true;
1843 buffer_full:
1844 logf("buffer is full for now");
1845 filling = STATE_FULL;
1846 return false;
1849 static void audio_fill_file_buffer(bool start_play, size_t offset)
1851 bool had_next_track = audio_next_track() != NULL;
1852 bool continue_buffering;
1854 filling = STATE_FILLING;
1855 trigger_cpu_boost();
1857 /* No need to rebuffer if there are track skips pending. */
1858 if (ci.new_track != 0)
1859 return;
1861 /* Must reset the buffer before use if trashed or voice only - voice
1862 file size shouldn't have changed so we can go straight from
1863 BUFFER_STATE_VOICED_ONLY to BUFFER_STATE_INITIALIZED */
1864 if (buffer_state != BUFFER_STATE_INITIALIZED)
1865 audio_reset_buffer();
1867 logf("Starting buffer fill");
1869 if (!start_play)
1870 audio_clear_track_entries();
1872 /* Save the current resume position once. */
1873 playlist_update_resume_info(audio_current_track());
1875 continue_buffering = audio_load_track(offset, start_play);
1876 do {
1877 sleep(1);
1878 if (!queue_empty(&audio_queue))
1879 /* There's a message in the queue. break the loop to treat it */
1880 break;
1881 continue_buffering = audio_load_track(0, false);
1882 } while (continue_buffering);
1884 if (!had_next_track && audio_next_track())
1885 track_changed = true;
1889 static void audio_rebuffer(void)
1891 logf("Forcing rebuffer");
1893 clear_track_info(CUR_TI);
1895 /* Reset track pointers */
1896 track_widx = track_ridx;
1897 audio_clear_track_entries();
1899 /* Fill the buffer */
1900 last_peek_offset = -1;
1901 ci.curpos = 0;
1903 if (!CUR_TI->taginfo_ready)
1904 memset(&curtrack_id3, 0, sizeof(struct mp3entry));
1906 audio_fill_file_buffer(false, 0);
1909 /* Called on request from the codec to get a new track. This is the codec part
1910 of the track transition. */
1911 static int audio_check_new_track(void)
1913 int track_count = audio_track_count();
1914 int old_track_ridx = track_ridx;
1915 int i, idx;
1916 int next_playlist_index;
1917 bool forward;
1918 bool end_of_playlist; /* Temporary flag, not the same as playlist_end */
1920 /* Now it's good time to send track unbuffer events. */
1921 send_event(PLAYBACK_EVENT_TRACK_FINISH, &curtrack_id3);
1923 if (dir_skip)
1925 dir_skip = false;
1926 if (playlist_next_dir(ci.new_track))
1928 ci.new_track = 0;
1929 audio_rebuffer();
1930 goto skip_done;
1932 else
1934 LOGFQUEUE("audio >|= codec Q_CODEC_REQUEST_FAILED");
1935 return Q_CODEC_REQUEST_FAILED;
1939 if (new_playlist)
1940 ci.new_track = 0;
1942 end_of_playlist = playlist_peek(automatic_skip ? ci.new_track : 0) == NULL;
1943 auto_dir_skip = end_of_playlist && global_settings.next_folder;
1945 /* If the playlist isn't that big */
1946 if (automatic_skip && !playlist_check(ci.new_track))
1948 if (ci.new_track >= 0)
1950 LOGFQUEUE("audio >|= codec Q_CODEC_REQUEST_FAILED");
1951 return Q_CODEC_REQUEST_FAILED;
1953 /* Find the beginning backward if the user over-skips it */
1954 while (!playlist_check(++ci.new_track))
1955 if (ci.new_track >= 0)
1957 LOGFQUEUE("audio >|= codec Q_CODEC_REQUEST_FAILED");
1958 return Q_CODEC_REQUEST_FAILED;
1962 /* Update the playlist */
1963 last_peek_offset -= ci.new_track;
1965 if (auto_dir_skip)
1967 /* If the track change was the result of an auto dir skip,
1968 we need to update the playlist now */
1969 next_playlist_index = playlist_next(ci.new_track);
1971 if (next_playlist_index < 0)
1973 LOGFQUEUE("audio >|= codec Q_CODEC_REQUEST_FAILED");
1974 return Q_CODEC_REQUEST_FAILED;
1978 if (new_playlist)
1980 ci.new_track = 1;
1981 new_playlist = false;
1984 /* Save the track metadata to allow the WPS to display it
1985 while PCM finishes playing that track */
1986 copy_mp3entry(&prevtrack_id3, &curtrack_id3);
1988 /* Update the main buffer copy of the track metadata with the one
1989 the codec has been using (for the unbuffer callbacks) */
1990 if (CUR_TI->id3_hid >= 0)
1991 copy_mp3entry(bufgetid3(CUR_TI->id3_hid), &curtrack_id3);
1993 /* Save a pointer to the old track to allow later clearing */
1994 prev_ti = CUR_TI;
1996 for (i = 0; i < ci.new_track; i++)
1998 idx = (track_ridx + i) & MAX_TRACK_MASK;
1999 struct mp3entry *id3 = bufgetid3(tracks[idx].id3_hid);
2000 ssize_t offset = buf_handle_offset(tracks[idx].audio_hid);
2001 if (!id3 || offset < 0 || (unsigned)offset > id3->first_frame_offset)
2003 /* We don't have all the audio data for that track, so clear it,
2004 but keep the metadata. */
2005 if (tracks[idx].audio_hid >= 0 && bufclose(tracks[idx].audio_hid))
2007 tracks[idx].audio_hid = -1;
2008 tracks[idx].filesize = 0;
2013 /* Move to the new track */
2014 track_ridx = (track_ridx + ci.new_track) & MAX_TRACK_MASK;
2016 buf_set_base_handle(CUR_TI->audio_hid);
2018 if (automatic_skip)
2020 playlist_end = false;
2021 wps_offset = -ci.new_track;
2022 track_changed = true;
2025 /* If it is not safe to even skip this many track entries */
2026 if (ci.new_track >= track_count || ci.new_track <= track_count - MAX_TRACK)
2028 ci.new_track = 0;
2029 audio_rebuffer();
2030 goto skip_done;
2033 forward = ci.new_track > 0;
2034 ci.new_track = 0;
2036 /* If the target track is clearly not in memory */
2037 if (CUR_TI->filesize == 0 || !CUR_TI->taginfo_ready)
2039 audio_rebuffer();
2040 goto skip_done;
2043 /* When skipping backwards, it is possible that we've found a track that's
2044 * buffered, but which is around the track-wrap and therefor not the track
2045 * we are looking for */
2046 if (!forward)
2048 int cur_idx = track_ridx;
2049 bool taginfo_ready = true;
2050 /* We've wrapped the buffer backwards if new > old */
2051 bool wrap = track_ridx > old_track_ridx;
2053 while (1)
2055 cur_idx = (cur_idx + 1) & MAX_TRACK_MASK;
2057 /* if we've advanced past the wrap when cur_idx is zeroed */
2058 if (!cur_idx)
2059 wrap = false;
2061 /* if we aren't still on the wrap and we've caught the old track */
2062 if (!(wrap || cur_idx < old_track_ridx))
2063 break;
2065 /* If we hit a track in between without valid tag info, bail */
2066 if (!tracks[cur_idx].taginfo_ready)
2068 taginfo_ready = false;
2069 break;
2072 if (!taginfo_ready)
2074 audio_rebuffer();
2078 skip_done:
2079 audio_update_trackinfo();
2080 LOGFQUEUE("audio >|= codec Q_CODEC_REQUEST_COMPLETE");
2081 return Q_CODEC_REQUEST_COMPLETE;
2084 unsigned long audio_prev_elapsed(void)
2086 return prev_track_elapsed;
2089 static void audio_stop_codec_flush(void)
2091 ci.stop_codec = true;
2092 pcmbuf_pause(true);
2094 while (audio_codec_loaded)
2095 yield();
2097 /* If the audio codec is not loaded any more, and the audio is still
2098 * playing, it is now and _only_ now safe to call this function from the
2099 * audio thread */
2100 if (pcm_is_playing())
2102 pcmbuf_play_stop();
2103 pcmbuf_queue_clear();
2105 pcmbuf_pause(paused);
2108 static void audio_stop_playback(void)
2110 /* If we were playing, save resume information */
2111 if (playing)
2113 struct mp3entry *id3 = NULL;
2115 if (!playlist_end || !ci.stop_codec)
2117 /* Set this early, the outside code yields and may allow the codec
2118 to try to wait for a reply on a buffer wait */
2119 ci.stop_codec = true;
2120 id3 = audio_current_track();
2123 /* Save the current playing spot, or NULL if the playlist has ended */
2124 playlist_update_resume_info(id3);
2126 /* TODO: Create auto bookmark too? */
2128 prev_track_elapsed = curtrack_id3.elapsed;
2131 paused = false;
2132 audio_stop_codec_flush();
2133 playing = false;
2135 filling = STATE_IDLE;
2137 /* Mark all entries null. */
2138 audio_clear_track_entries();
2140 /* Close all tracks */
2141 audio_release_tracks();
2143 unregister_buffering_callback(buffering_audio_callback);
2145 memset(&curtrack_id3, 0, sizeof(struct mp3entry));
2148 static void audio_play_start(size_t offset)
2150 int i;
2152 #if INPUT_SRC_CAPS != 0
2153 audio_set_input_source(AUDIO_SRC_PLAYBACK, SRCF_PLAYBACK);
2154 audio_set_output_source(AUDIO_SRC_PLAYBACK);
2155 #endif
2157 /* Wait for any previously playing audio to flush - TODO: Not necessary? */
2158 paused = false;
2159 audio_stop_codec_flush();
2161 track_changed = true;
2162 playlist_end = false;
2164 playing = true;
2166 ci.new_track = 0;
2167 ci.seek_time = 0;
2168 wps_offset = 0;
2170 sound_set_volume(global_settings.volume);
2171 track_widx = track_ridx = 0;
2173 /* Clear all track entries. */
2174 for (i = 0; i < MAX_TRACK; i++) {
2175 clear_track_info(&tracks[i]);
2178 last_peek_offset = -1;
2180 /* Officially playing */
2181 queue_reply(&audio_queue, 1);
2183 #ifndef HAVE_FLASH_STORAGE
2184 set_filebuf_watermark(buffer_margin, 0);
2185 #endif
2187 audio_fill_file_buffer(true, offset);
2188 register_buffering_callback(buffering_audio_callback);
2190 LOGFQUEUE("audio > audio Q_AUDIO_TRACK_CHANGED");
2191 queue_post(&audio_queue, Q_AUDIO_TRACK_CHANGED, 0);
2195 /* Invalidates all but currently playing track. */
2196 static void audio_invalidate_tracks(void)
2198 if (audio_have_tracks())
2200 last_peek_offset = 0;
2201 playlist_end = false;
2202 track_widx = track_ridx;
2204 /* Mark all other entries null (also buffered wrong metadata). */
2205 audio_clear_track_entries();
2207 track_widx = (track_widx + 1) & MAX_TRACK_MASK;
2209 audio_fill_file_buffer(false, 0);
2213 static void audio_new_playlist(void)
2215 /* Prepare to start a new fill from the beginning of the playlist */
2216 last_peek_offset = -1;
2217 if (audio_have_tracks())
2219 if (paused)
2220 skipped_during_pause = true;
2221 playlist_end = false;
2222 track_widx = track_ridx;
2223 audio_clear_track_entries();
2225 track_widx = (track_widx + 1) & MAX_TRACK_MASK;
2227 /* Mark the current track as invalid to prevent skipping back to it */
2228 CUR_TI->taginfo_ready = false;
2231 /* Signal the codec to initiate a track change forward */
2232 new_playlist = true;
2233 ci.new_track = 1;
2235 /* Officially playing */
2236 queue_reply(&audio_queue, 1);
2238 audio_fill_file_buffer(false, 0);
2241 /* Called on manual track skip */
2242 static void audio_initiate_track_change(long direction)
2244 logf("audio_initiate_track_change(%ld)", direction);
2246 playlist_end = false;
2247 ci.new_track += direction;
2248 wps_offset -= direction;
2249 if (paused)
2250 skipped_during_pause = true;
2253 /* Called on manual dir skip */
2254 static void audio_initiate_dir_change(long direction)
2256 playlist_end = false;
2257 dir_skip = true;
2258 ci.new_track = direction;
2259 if (paused)
2260 skipped_during_pause = true;
2263 /* Called when PCM track change is complete */
2264 static void audio_finalise_track_change(void)
2266 logf("audio_finalise_track_change");
2268 if (automatic_skip)
2270 if (!auto_dir_skip)
2271 playlist_next(-wps_offset);
2273 wps_offset = 0;
2274 automatic_skip = false;
2277 auto_dir_skip = false;
2279 /* Invalidate prevtrack_id3 */
2280 prevtrack_id3.path[0] = 0;
2282 if (prev_ti && prev_ti->audio_hid < 0)
2284 /* No audio left so we clear all the track info. */
2285 clear_track_info(prev_ti);
2288 if (prev_ti && prev_ti->id3_hid >= 0)
2290 /* Reset the elapsed time to force the progressbar to be empty if
2291 the user skips back to this track */
2292 bufgetid3(prev_ti->id3_hid)->elapsed = 0;
2295 send_event(PLAYBACK_EVENT_TRACK_CHANGE, &curtrack_id3);
2297 track_changed = true;
2298 playlist_update_resume_info(audio_current_track());
2302 * Layout audio buffer as follows - iram buffer depends on target:
2303 * [|SWAP:iram][|TALK]|MALLOC|FILE|GUARD|PCM|[SWAP:dram[|iram]|]
2305 static void audio_reset_buffer(void)
2307 /* see audio_get_recording_buffer if this is modified */
2308 logf("audio_reset_buffer");
2310 /* If the setup of anything allocated before the file buffer is
2311 changed, do check the adjustments after the buffer_alloc call
2312 as it will likely be affected and need sliding over */
2314 /* Initially set up file buffer as all space available */
2315 malloc_buf = audiobuf + talk_get_bufsize();
2316 /* Align the malloc buf to line size. Especially important to cf
2317 targets that do line reads/writes. */
2318 malloc_buf = (unsigned char *)(((uintptr_t)malloc_buf + 15) & ~15);
2319 filebuf = malloc_buf + MALLOC_BUFSIZE; /* filebuf line align implied */
2320 filebuflen = audiobufend - filebuf;
2322 filebuflen &= ~15;
2324 /* Subtract whatever the pcm buffer says it used plus the guard buffer */
2325 filebuflen -= pcmbuf_init(filebuf + filebuflen) + GUARD_BUFSIZE;
2327 /* Make sure filebuflen is a longword multiple after adjustment - filebuf
2328 will already be line aligned */
2329 filebuflen &= ~3;
2331 buffering_reset(filebuf, filebuflen);
2333 /* Clear any references to the file buffer */
2334 buffer_state = BUFFER_STATE_INITIALIZED;
2336 #if defined(ROCKBOX_HAS_LOGF) && defined(LOGF_ENABLE)
2337 /* Make sure everything adds up - yes, some info is a bit redundant but
2338 aids viewing and the sumation of certain variables should add up to
2339 the location of others. */
2341 size_t pcmbufsize;
2342 const unsigned char *pcmbuf = pcmbuf_get_meminfo(&pcmbufsize);
2343 logf("mabuf: %08X", (unsigned)malloc_buf);
2344 logf("mabufe: %08X", (unsigned)(malloc_buf + MALLOC_BUFSIZE));
2345 logf("fbuf: %08X", (unsigned)filebuf);
2346 logf("fbufe: %08X", (unsigned)(filebuf + filebuflen));
2347 logf("gbuf: %08X", (unsigned)(filebuf + filebuflen));
2348 logf("gbufe: %08X", (unsigned)(filebuf + filebuflen + GUARD_BUFSIZE));
2349 logf("pcmb: %08X", (unsigned)pcmbuf);
2350 logf("pcmbe: %08X", (unsigned)(pcmbuf + pcmbufsize));
2352 #endif
2355 static void audio_thread(void)
2357 struct queue_event ev;
2359 pcm_postinit();
2361 audio_thread_ready = true;
2363 while (1)
2365 if (filling != STATE_FILLING) {
2366 cancel_cpu_boost();
2369 if (!pcmbuf_queue_scan(&ev))
2370 queue_wait_w_tmo(&audio_queue, &ev, HZ/2);
2372 switch (ev.id) {
2374 case Q_AUDIO_FILL_BUFFER:
2375 LOGFQUEUE("audio < Q_AUDIO_FILL_BUFFER");
2376 audio_fill_file_buffer(false, 0);
2377 break;
2379 case Q_AUDIO_PLAY:
2380 LOGFQUEUE("audio < Q_AUDIO_PLAY");
2381 if (playing && ev.data <= 0)
2382 audio_new_playlist();
2383 else
2385 audio_stop_playback();
2386 audio_play_start((size_t)ev.data);
2388 break;
2390 case Q_AUDIO_STOP:
2391 LOGFQUEUE("audio < Q_AUDIO_STOP");
2392 if (playing)
2393 audio_stop_playback();
2394 if (ev.data != 0)
2395 queue_clear(&audio_queue);
2396 break;
2398 case Q_AUDIO_PAUSE:
2399 LOGFQUEUE("audio < Q_AUDIO_PAUSE");
2400 if (!(bool) ev.data && skipped_during_pause && !pcmbuf_is_crossfade_active())
2401 pcmbuf_play_stop(); /* Flush old track on resume after skip */
2402 skipped_during_pause = false;
2403 if (!playing)
2404 break;
2405 pcmbuf_pause((bool)ev.data);
2406 paused = (bool)ev.data;
2407 break;
2409 case Q_AUDIO_SKIP:
2410 LOGFQUEUE("audio < Q_AUDIO_SKIP");
2411 audio_initiate_track_change((long)ev.data);
2412 break;
2414 case Q_AUDIO_PRE_FF_REWIND:
2415 LOGFQUEUE("audio < Q_AUDIO_PRE_FF_REWIND");
2416 if (!playing)
2417 break;
2418 pcmbuf_pause(true);
2419 break;
2421 case Q_AUDIO_FF_REWIND:
2422 LOGFQUEUE("audio < Q_AUDIO_FF_REWIND");
2423 if (!playing)
2424 break;
2425 if (automatic_skip)
2427 /* An automatic track skip is in progress. Finalize it,
2428 then go back to the previous track */
2429 audio_finalise_track_change();
2430 ci.new_track = -1;
2432 ci.seek_time = (long)ev.data+1;
2433 break;
2435 case Q_AUDIO_CHECK_NEW_TRACK:
2436 LOGFQUEUE("audio < Q_AUDIO_CHECK_NEW_TRACK");
2437 queue_reply(&audio_queue, audio_check_new_track());
2438 break;
2440 case Q_AUDIO_DIR_SKIP:
2441 LOGFQUEUE("audio < Q_AUDIO_DIR_SKIP");
2442 playlist_end = false;
2443 audio_initiate_dir_change(ev.data);
2444 break;
2446 case Q_AUDIO_FLUSH:
2447 LOGFQUEUE("audio < Q_AUDIO_FLUSH");
2448 audio_invalidate_tracks();
2449 break;
2451 case Q_AUDIO_TRACK_CHANGED:
2452 /* PCM track change done */
2453 LOGFQUEUE("audio < Q_AUDIO_TRACK_CHANGED");
2454 audio_finalise_track_change();
2455 break;
2457 #ifndef SIMULATOR
2458 case SYS_USB_CONNECTED:
2459 LOGFQUEUE("audio < SYS_USB_CONNECTED");
2460 if (playing)
2461 audio_stop_playback();
2462 #ifdef PLAYBACK_VOICE
2463 voice_stop();
2464 #endif
2465 usb_acknowledge(SYS_USB_CONNECTED_ACK);
2466 usb_wait_for_disconnect(&audio_queue);
2468 /* Mark all entries null. */
2469 audio_clear_track_entries();
2471 /* release tracks to make sure all handles are closed */
2472 audio_release_tracks();
2473 break;
2474 #endif
2476 case SYS_TIMEOUT:
2477 LOGFQUEUE_SYS_TIMEOUT("audio < SYS_TIMEOUT");
2478 if (filling == STATE_FILLING)
2479 audio_fill_file_buffer(false, 0);
2480 break;
2482 default:
2483 LOGFQUEUE("audio < default");
2484 break;
2485 } /* end switch */
2486 } /* end while */
2489 /* Initialize the audio system - called from init() in main.c.
2490 * Last function because of all the references to internal symbols
2492 void audio_init(void)
2494 struct thread_entry *audio_thread_p;
2496 /* Can never do this twice */
2497 if (audio_is_initialized)
2499 logf("audio: already initialized");
2500 return;
2503 logf("audio: initializing");
2505 /* Initialize queues before giving control elsewhere in case it likes
2506 to send messages. Thread creation will be delayed however so nothing
2507 starts running until ready if something yields such as talk_init. */
2508 queue_init(&audio_queue, true);
2509 queue_init(&codec_queue, false);
2510 queue_init(&pcmbuf_queue, false);
2512 pcm_init();
2514 /* Initialize codec api. */
2515 ci.read_filebuf = codec_filebuf_callback;
2516 ci.pcmbuf_insert = codec_pcmbuf_insert_callback;
2517 ci.get_codec_memory = codec_get_memory_callback;
2518 ci.request_buffer = codec_request_buffer_callback;
2519 ci.advance_buffer = codec_advance_buffer_callback;
2520 ci.advance_buffer_loc = codec_advance_buffer_loc_callback;
2521 ci.request_next_track = codec_request_next_track_callback;
2522 ci.seek_buffer = codec_seek_buffer_callback;
2523 ci.seek_complete = codec_seek_complete_callback;
2524 ci.set_elapsed = codec_set_elapsed_callback;
2525 ci.set_offset = codec_set_offset_callback;
2526 ci.configure = codec_configure_callback;
2527 ci.discard_codec = codec_discard_codec_callback;
2528 ci.dsp = (struct dsp_config *)dsp_configure(NULL, DSP_MYDSP,
2529 CODEC_IDX_AUDIO);
2531 /* initialize the buffer */
2532 filebuf = audiobuf;
2534 /* audio_reset_buffer must to know the size of voice buffer so init
2535 talk first */
2536 talk_init();
2538 codec_thread_p = create_thread(
2539 codec_thread, codec_stack, sizeof(codec_stack),
2540 CREATE_THREAD_FROZEN,
2541 codec_thread_name IF_PRIO(, PRIORITY_PLAYBACK)
2542 IF_COP(, CPU));
2544 queue_enable_queue_send(&codec_queue, &codec_queue_sender_list,
2545 codec_thread_p);
2547 audio_thread_p = create_thread(audio_thread, audio_stack,
2548 sizeof(audio_stack), CREATE_THREAD_FROZEN,
2549 audio_thread_name IF_PRIO(, PRIORITY_USER_INTERFACE)
2550 IF_COP(, CPU));
2552 queue_enable_queue_send(&audio_queue, &audio_queue_sender_list,
2553 audio_thread_p);
2555 #ifdef PLAYBACK_VOICE
2556 voice_thread_init();
2557 #endif
2559 /* Set crossfade setting for next buffer init which should be about... */
2560 pcmbuf_crossfade_enable(global_settings.crossfade);
2562 /* initialize the buffering system */
2564 buffering_init();
2565 /* ...now! Set up the buffers */
2566 audio_reset_buffer();
2568 int i;
2569 for(i = 0; i < MAX_TRACK; i++)
2571 tracks[i].audio_hid = -1;
2572 tracks[i].id3_hid = -1;
2573 tracks[i].codec_hid = -1;
2574 #ifdef HAVE_ALBUMART
2575 tracks[i].aa_hid = -1;
2576 #endif
2579 /* Probably safe to say */
2580 audio_is_initialized = true;
2582 sound_settings_apply();
2583 #ifndef HAVE_FLASH_STORAGE
2584 audio_set_buffer_margin(global_settings.buffer_margin);
2585 #endif
2587 /* it's safe to let the threads run now */
2588 #ifdef PLAYBACK_VOICE
2589 voice_thread_resume();
2590 #endif
2591 thread_thaw(codec_thread_p);
2592 thread_thaw(audio_thread_p);
2594 } /* audio_init */
2596 void audio_wait_for_init(void)
2598 /* audio thread will only set this once after it finished the final
2599 * audio hardware init so this little construct is safe - even
2600 * cross-core. */
2601 while (!audio_thread_ready)
2603 sleep(0);