Fix FS#9110 and its maybe-dupes.
[Rockbox.git] / apps / playback.c
blobaee06b07ae545dbed2753572937c526b5ec9018d
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 "events.h"
48 #include "voice_thread.h"
49 #include "mp3_playback.h"
50 #include "usb.h"
51 #include "status.h"
52 #include "ata.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 #endif
84 #define PLAYBACK_VOICE
86 /* default point to start buffer refill */
87 #define AUDIO_DEFAULT_WATERMARK (1024*512)
88 /* amount of guess-space to allow for codecs that must hunt and peck
89 * for their correct seeek target, 32k seems a good size */
90 #define AUDIO_REBUFFER_GUESS_SIZE (1024*32)
92 /* Define LOGF_ENABLE to enable logf output in this file */
93 /*#define LOGF_ENABLE*/
94 #include "logf.h"
96 /* macros to enable logf for queues
97 logging on SYS_TIMEOUT can be disabled */
98 #ifdef SIMULATOR
99 /* Define this for logf output of all queuing except SYS_TIMEOUT */
100 #define PLAYBACK_LOGQUEUES
101 /* Define this to logf SYS_TIMEOUT messages */
102 /*#define PLAYBACK_LOGQUEUES_SYS_TIMEOUT*/
103 #endif
105 #ifdef PLAYBACK_LOGQUEUES
106 #define LOGFQUEUE logf
107 #else
108 #define LOGFQUEUE(...)
109 #endif
111 #ifdef PLAYBACK_LOGQUEUES_SYS_TIMEOUT
112 #define LOGFQUEUE_SYS_TIMEOUT logf
113 #else
114 #define LOGFQUEUE_SYS_TIMEOUT(...)
115 #endif
118 /* Define one constant that includes recording related functionality */
119 #if defined(HAVE_RECORDING) && !defined(SIMULATOR)
120 #define AUDIO_HAVE_RECORDING
121 #endif
123 enum {
124 Q_NULL = 0,
125 Q_AUDIO_PLAY = 1,
126 Q_AUDIO_STOP,
127 Q_AUDIO_PAUSE,
128 Q_AUDIO_SKIP,
129 Q_AUDIO_PRE_FF_REWIND,
130 Q_AUDIO_FF_REWIND,
131 Q_AUDIO_CHECK_NEW_TRACK,
132 Q_AUDIO_FLUSH,
133 Q_AUDIO_TRACK_CHANGED,
134 Q_AUDIO_DIR_SKIP,
135 Q_AUDIO_POSTINIT,
136 Q_AUDIO_FILL_BUFFER,
137 Q_AUDIO_FINISH_LOAD,
138 Q_CODEC_REQUEST_COMPLETE,
139 Q_CODEC_REQUEST_FAILED,
141 Q_CODEC_LOAD,
142 Q_CODEC_LOAD_DISK,
144 #ifdef AUDIO_HAVE_RECORDING
145 Q_ENCODER_LOAD_DISK,
146 Q_ENCODER_RECORD,
147 #endif
150 enum filling_state {
151 STATE_IDLE, /* audio is stopped: nothing to do */
152 STATE_FILLING, /* adding tracks to the buffer */
153 STATE_FULL, /* can't add any more tracks */
154 STATE_END_OF_PLAYLIST, /* all remaining tracks have been added */
155 STATE_FINISHED, /* all remaining tracks are fully buffered */
158 #if MEM > 1
159 #define MAX_TRACK 128
160 #else
161 #define MAX_TRACK 32
162 #endif
164 #define MAX_TRACK_MASK (MAX_TRACK-1)
166 /* As defined in plugins/lib/xxx2wav.h */
167 #if MEM > 1
168 #define MALLOC_BUFSIZE (512*1024)
169 #define GUARD_BUFSIZE (32*1024)
170 #else
171 #define MALLOC_BUFSIZE (100*1024)
172 #define GUARD_BUFSIZE (8*1024)
173 #endif
175 /* As defined in plugin.lds */
176 #if defined(CPU_PP)
177 #define CODEC_IRAM_ORIGIN ((unsigned char *)0x4000c000)
178 #define CODEC_IRAM_SIZE ((size_t)0xc000)
179 #elif defined(IAUDIO_X5) || defined(IAUDIO_M5)
180 #define CODEC_IRAM_ORIGIN ((unsigned char *)0x10010000)
181 #define CODEC_IRAM_SIZE ((size_t)0x10000)
182 #else
183 #define CODEC_IRAM_ORIGIN ((unsigned char *)0x1000c000)
184 #define CODEC_IRAM_SIZE ((size_t)0xc000)
185 #endif
187 bool audio_is_initialized = false;
188 static bool audio_thread_ready SHAREDBSS_ATTR = false;
190 /* Variables are commented with the threads that use them: *
191 * A=audio, C=codec, V=voice. A suffix of - indicates that *
192 * the variable is read but not updated on that thread. */
193 /* TBD: Split out "audio" and "playback" (ie. calling) threads */
195 /* Main state control */
196 static volatile bool audio_codec_loaded SHAREDBSS_ATTR = false; /* Codec loaded? (C/A-) */
197 static volatile bool playing SHAREDBSS_ATTR = false; /* Is audio playing? (A) */
198 static volatile bool paused SHAREDBSS_ATTR = false; /* Is audio paused? (A/C-) */
200 /* Ring buffer where compressed audio and codecs are loaded */
201 static unsigned char *filebuf = NULL; /* Start of buffer (A/C-) */
202 static unsigned char *malloc_buf = NULL; /* Start of malloc buffer (A/C-) */
203 /* FIXME: make filebuflen static */
204 size_t filebuflen = 0; /* Size of buffer (A/C-) */
205 /* FIXME: make buf_ridx (C/A-) */
207 /* Possible arrangements of the buffer */
208 #define BUFFER_STATE_TRASHED -1 /* trashed; must be reset */
209 #define BUFFER_STATE_INITIALIZED 0 /* voice+audio OR audio-only */
210 #define BUFFER_STATE_VOICED_ONLY 1 /* voice-only */
211 static int buffer_state = BUFFER_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 /* Set to true if the codec thread should send an audio stop request
268 * (typically because the end of the playlist has been reached).
270 static bool codec_requested_stop = false;
272 static size_t buffer_margin = 0; /* Buffer margin aka anti-skip buffer (A/C-) */
274 /* Multiple threads */
275 /* Set the watermark to trigger buffer fill (A/C) FIXME */
276 static void set_filebuf_watermark(int seconds, size_t max);
278 /* Audio thread */
279 static struct event_queue audio_queue SHAREDBSS_ATTR;
280 static struct queue_sender_list audio_queue_sender_list SHAREDBSS_ATTR;
281 static long audio_stack[(DEFAULT_STACK_SIZE + 0x1000)/sizeof(long)];
282 static const char audio_thread_name[] = "audio";
284 static void audio_thread(void);
285 static void audio_initiate_track_change(long direction);
286 static bool audio_have_tracks(void);
287 static void audio_reset_buffer(void);
289 /* Codec thread */
290 extern struct codec_api ci;
291 static struct event_queue codec_queue SHAREDBSS_ATTR;
292 static struct queue_sender_list codec_queue_sender_list;
293 static long codec_stack[(DEFAULT_STACK_SIZE + 0x2000)/sizeof(long)]
294 IBSS_ATTR;
295 static const char codec_thread_name[] = "codec";
296 struct thread_entry *codec_thread_p; /* For modifying thread priority later. */
298 /* PCM buffer messaging */
299 static struct event_queue pcmbuf_queue SHAREDBSS_ATTR;
301 /* Function to be called by pcm buffer callbacks.
302 * Permissible Context(s): Audio interrupt
304 static void pcmbuf_callback_queue_post(long id, intptr_t data)
306 /* No lock since we're already in audio interrupt context */
307 queue_post(&pcmbuf_queue, id, data);
310 /* Scan the pcmbuf queue and return true if a message pulled.
311 * Permissible Context(s): Thread
313 static bool pcmbuf_queue_scan(struct queue_event *ev)
315 if (!queue_empty(&pcmbuf_queue))
317 /* Transfer message to audio queue */
318 pcm_play_lock();
319 /* Pull message - never, ever any blocking call! */
320 queue_wait_w_tmo(&pcmbuf_queue, ev, 0);
321 pcm_play_unlock();
322 return true;
325 return false;
328 /* Clear the pcmbuf queue of messages
329 * Permissible Context(s): Thread
331 static void pcmbuf_queue_clear(void)
333 pcm_play_lock();
334 queue_clear(&pcmbuf_queue);
335 pcm_play_unlock();
338 /* --- Helper functions --- */
340 static struct mp3entry *bufgetid3(int handle_id)
342 if (handle_id < 0)
343 return NULL;
345 struct mp3entry *id3;
346 ssize_t ret = bufgetdata(handle_id, 0, (void *)&id3);
348 if (ret < 0 || ret != sizeof(struct mp3entry))
349 return NULL;
351 return id3;
354 static bool clear_track_info(struct track_info *track)
356 /* bufclose returns true if the handle is not found, or if it is closed
357 * successfully, so these checks are safe on non-existant handles */
358 if (!track)
359 return false;
361 if (track->codec_hid >= 0) {
362 if (bufclose(track->codec_hid))
363 track->codec_hid = -1;
364 else
365 return false;
368 if (track->id3_hid >= 0) {
369 if (bufclose(track->id3_hid))
370 track->id3_hid = -1;
371 else
372 return false;
375 if (track->audio_hid >= 0) {
376 if (bufclose(track->audio_hid))
377 track->audio_hid = -1;
378 else
379 return false;
382 #ifdef HAVE_ALBUMART
383 if (track->aa_hid >= 0) {
384 if (bufclose(track->aa_hid))
385 track->aa_hid = -1;
386 else
387 return false;
389 #endif
391 track->filesize = 0;
392 track->taginfo_ready = false;
394 return true;
397 /* --- External interfaces --- */
399 /* This sends a stop message and the audio thread will dump all it's
400 subsequenct messages */
401 void audio_hard_stop(void)
403 /* Stop playback */
404 LOGFQUEUE("audio >| audio Q_AUDIO_STOP: 1");
405 queue_send(&audio_queue, Q_AUDIO_STOP, 1);
406 #ifdef PLAYBACK_VOICE
407 voice_stop();
408 #endif
411 bool audio_restore_playback(int type)
413 switch (type)
415 case AUDIO_WANT_PLAYBACK:
416 if (buffer_state != BUFFER_STATE_INITIALIZED)
417 audio_reset_buffer();
418 return true;
419 case AUDIO_WANT_VOICE:
420 if (buffer_state == BUFFER_STATE_TRASHED)
421 audio_reset_buffer();
422 return true;
423 default:
424 return false;
428 unsigned char *audio_get_buffer(bool talk_buf, size_t *buffer_size)
430 unsigned char *buf, *end;
432 if (audio_is_initialized)
434 audio_hard_stop();
436 /* else buffer_state will be BUFFER_STATE_TRASHED at this point */
438 if (buffer_size == NULL)
440 /* Special case for talk_init to use since it already knows it's
441 trashed */
442 buffer_state = BUFFER_STATE_TRASHED;
443 return NULL;
446 if (talk_buf || buffer_state == BUFFER_STATE_TRASHED
447 || !talk_voice_required())
449 logf("get buffer: talk, audio");
450 /* Ok to use everything from audiobuf to audiobufend - voice is loaded,
451 the talk buffer is not needed because voice isn't being used, or
452 could be BUFFER_STATE_TRASHED already. If state is
453 BUFFER_STATE_VOICED_ONLY, no problem as long as memory isn't written
454 without the caller knowing what's going on. Changing certain settings
455 may move it to a worse condition but the memory in use by something
456 else will remain undisturbed.
458 if (buffer_state != BUFFER_STATE_TRASHED)
460 talk_buffer_steal();
461 buffer_state = BUFFER_STATE_TRASHED;
464 buf = audiobuf;
465 end = audiobufend;
467 else
469 /* Safe to just return this if already BUFFER_STATE_VOICED_ONLY or
470 still BUFFER_STATE_INITIALIZED */
471 /* Skip talk buffer and move pcm buffer to end to maximize available
472 contiguous memory - no audio running means voice will not need the
473 swap space */
474 logf("get buffer: audio");
475 buf = audiobuf + talk_get_bufsize();
476 end = audiobufend - pcmbuf_init(audiobufend);
477 buffer_state = BUFFER_STATE_VOICED_ONLY;
480 *buffer_size = end - buf;
482 return buf;
485 #ifdef HAVE_RECORDING
486 unsigned char *audio_get_recording_buffer(size_t *buffer_size)
488 /* Stop audio, voice and obtain all available buffer space */
489 audio_hard_stop();
490 talk_buffer_steal();
492 unsigned char *end = audiobufend;
493 buffer_state = BUFFER_STATE_TRASHED;
494 *buffer_size = end - audiobuf;
496 return (unsigned char *)audiobuf;
499 bool audio_load_encoder(int afmt)
501 #ifndef SIMULATOR
502 const char *enc_fn = get_codec_filename(afmt | CODEC_TYPE_ENCODER);
503 if (!enc_fn)
504 return false;
506 audio_remove_encoder();
507 ci.enc_codec_loaded = 0; /* clear any previous error condition */
509 LOGFQUEUE("codec > Q_ENCODER_LOAD_DISK");
510 queue_post(&codec_queue, Q_ENCODER_LOAD_DISK, (intptr_t)enc_fn);
512 while (ci.enc_codec_loaded == 0)
513 yield();
515 logf("codec loaded: %d", ci.enc_codec_loaded);
517 return ci.enc_codec_loaded > 0;
518 #else
519 (void)afmt;
520 return true;
521 #endif
522 } /* audio_load_encoder */
524 void audio_remove_encoder(void)
526 #ifndef SIMULATOR
527 /* force encoder codec unload (if currently loaded) */
528 if (ci.enc_codec_loaded <= 0)
529 return;
531 ci.stop_encoder = true;
532 while (ci.enc_codec_loaded > 0)
533 yield();
534 #endif
535 } /* audio_remove_encoder */
537 #endif /* HAVE_RECORDING */
539 #ifdef HAVE_ALBUMART
540 int audio_current_aa_hid(void)
542 int cur_idx;
543 int offset = ci.new_track + wps_offset;
545 cur_idx = track_ridx + offset;
546 cur_idx &= MAX_TRACK_MASK;
548 return tracks[cur_idx].aa_hid;
550 #endif
552 struct mp3entry* audio_current_track(void)
554 const char *filename;
555 const char *p;
556 static struct mp3entry temp_id3;
557 struct playlist_track_info trackinfo;
558 int cur_idx;
559 int offset = ci.new_track + wps_offset;
561 cur_idx = (track_ridx + offset) & MAX_TRACK_MASK;
563 if (cur_idx == track_ridx && *curtrack_id3.path)
565 /* The usual case */
566 return &curtrack_id3;
568 else if (automatic_skip && offset == -1 && *prevtrack_id3.path)
570 /* We're in a track transition. The codec has moved on to the nex track,
571 but the audio being played is still the same (now previous) track.
572 prevtrack_id3.elapsed is being updated in an ISR by
573 codec_pcmbuf_position_callback */
574 return &prevtrack_id3;
576 else if (tracks[cur_idx].id3_hid >= 0)
578 /* Get the ID3 metadata from the main buffer */
579 struct mp3entry *ret = bufgetid3(tracks[cur_idx].id3_hid);
580 if (ret) return ret;
583 /* We didn't find the ID3 metadata, so we fill temp_id3 with the little info
584 we have and return that. */
586 memset(&temp_id3, 0, sizeof(struct mp3entry));
588 playlist_get_track_info(NULL, playlist_next(0)+wps_offset, &trackinfo);
589 filename = trackinfo.filename;
590 if (!filename)
591 filename = "No file!";
593 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
594 if (tagcache_fill_tags(&temp_id3, filename))
595 return &temp_id3;
596 #endif
598 p = strrchr(filename, '/');
599 if (!p)
600 p = filename;
601 else
602 p++;
604 strncpy(temp_id3.path, p, sizeof(temp_id3.path)-1);
605 temp_id3.title = &temp_id3.path[0];
607 return &temp_id3;
610 struct mp3entry* audio_next_track(void)
612 int next_idx;
613 int offset = ci.new_track + wps_offset;
615 if (!audio_have_tracks())
616 return NULL;
618 if (wps_offset == -1 && *prevtrack_id3.path)
620 /* We're in a track transition. The next track for the WPS is the one
621 currently being decoded. */
622 return &curtrack_id3;
625 next_idx = (track_ridx + offset + 1) & MAX_TRACK_MASK;
627 if (tracks[next_idx].id3_hid >= 0)
628 return bufgetid3(tracks[next_idx].id3_hid);
630 if (next_idx == track_widx)
632 /* The next track hasn't been buffered yet, so we return the static
633 version of its metadata. */
634 return &lasttrack_id3;
637 return NULL;
640 bool audio_has_changed_track(void)
642 if (track_changed)
644 track_changed = false;
645 return true;
648 return false;
651 void audio_play(long offset)
653 logf("audio_play");
655 #ifdef PLAYBACK_VOICE
656 /* Truncate any existing voice output so we don't have spelling
657 * etc. over the first part of the played track */
658 talk_force_shutup();
659 #endif
661 /* Start playback */
662 LOGFQUEUE("audio >| audio Q_AUDIO_PLAY: %ld", offset);
663 /* Don't return until playback has actually started */
664 queue_send(&audio_queue, Q_AUDIO_PLAY, offset);
667 void audio_stop(void)
669 /* Stop playback */
670 LOGFQUEUE("audio >| audio Q_AUDIO_STOP");
671 /* Don't return until playback has actually stopped */
672 queue_send(&audio_queue, Q_AUDIO_STOP, 0);
675 void audio_pause(void)
677 LOGFQUEUE("audio >| audio Q_AUDIO_PAUSE");
678 /* Don't return until playback has actually paused */
679 queue_send(&audio_queue, Q_AUDIO_PAUSE, true);
682 void audio_resume(void)
684 LOGFQUEUE("audio >| audio Q_AUDIO_PAUSE resume");
685 /* Don't return until playback has actually resumed */
686 queue_send(&audio_queue, Q_AUDIO_PAUSE, false);
689 static void audio_skip(int direction)
691 if (playlist_check(ci.new_track + wps_offset + direction))
693 if (global_settings.beep)
694 pcmbuf_beep(5000, 100, 2500*global_settings.beep);
696 LOGFQUEUE("audio > audio Q_AUDIO_SKIP %d", direction);
697 queue_post(&audio_queue, Q_AUDIO_SKIP, direction);
698 /* Update wps while our message travels inside deep playback queues. */
699 wps_offset += direction;
700 track_changed = true;
702 else
704 /* No more tracks. */
705 if (global_settings.beep)
706 pcmbuf_beep(1000, 100, 1000*global_settings.beep);
710 void audio_next(void)
712 audio_skip(1);
715 void audio_prev(void)
717 audio_skip(-1);
720 void audio_next_dir(void)
722 LOGFQUEUE("audio > audio Q_AUDIO_DIR_SKIP 1");
723 queue_post(&audio_queue, Q_AUDIO_DIR_SKIP, 1);
726 void audio_prev_dir(void)
728 LOGFQUEUE("audio > audio Q_AUDIO_DIR_SKIP -1");
729 queue_post(&audio_queue, Q_AUDIO_DIR_SKIP, -1);
732 void audio_pre_ff_rewind(void)
734 LOGFQUEUE("audio > audio Q_AUDIO_PRE_FF_REWIND");
735 queue_post(&audio_queue, Q_AUDIO_PRE_FF_REWIND, 0);
738 void audio_ff_rewind(long newpos)
740 LOGFQUEUE("audio > audio Q_AUDIO_FF_REWIND");
741 queue_post(&audio_queue, Q_AUDIO_FF_REWIND, newpos);
744 void audio_flush_and_reload_tracks(void)
746 LOGFQUEUE("audio > audio Q_AUDIO_FLUSH");
747 queue_post(&audio_queue, Q_AUDIO_FLUSH, 0);
750 void audio_error_clear(void)
752 #ifdef AUDIO_HAVE_RECORDING
753 pcm_rec_error_clear();
754 #endif
757 int audio_status(void)
759 int ret = 0;
761 if (playing)
762 ret |= AUDIO_STATUS_PLAY;
764 if (paused)
765 ret |= AUDIO_STATUS_PAUSE;
767 #ifdef HAVE_RECORDING
768 /* Do this here for constitency with mpeg.c version */
769 ret |= pcm_rec_status();
770 #endif
772 return ret;
775 int audio_get_file_pos(void)
777 return 0;
780 #ifndef HAVE_FLASH_STORAGE
781 void audio_set_buffer_margin(int setting)
783 static const int lookup[] = {5, 15, 30, 60, 120, 180, 300, 600};
784 buffer_margin = lookup[setting];
785 logf("buffer margin: %ld", (long)buffer_margin);
786 set_filebuf_watermark(buffer_margin, 0);
788 #endif
790 /* Take necessary steps to enable or disable the crossfade setting */
791 void audio_set_crossfade(int enable)
793 size_t offset;
794 bool was_playing;
795 size_t size;
797 /* Tell it the next setting to use */
798 pcmbuf_crossfade_enable(enable);
800 /* Return if size hasn't changed or this is too early to determine
801 which in the second case there's no way we could be playing
802 anything at all */
803 if (pcmbuf_is_same_size())
805 /* This function is a copout and just syncs some variables -
806 to be removed at a later date */
807 pcmbuf_crossfade_enable_finished();
808 return;
811 offset = 0;
812 was_playing = playing;
814 /* Playback has to be stopped before changing the buffer size */
815 if (was_playing)
817 /* Store the track resume position */
818 offset = curtrack_id3.offset;
819 gui_syncsplash(0, str(LANG_RESTARTING_PLAYBACK));
822 /* Blast it - audio buffer will have to be setup again next time
823 something plays */
824 audio_get_buffer(true, &size);
826 /* Restart playback if audio was running previously */
827 if (was_playing)
828 audio_play(offset);
831 /* --- Routines called from multiple threads --- */
833 static void set_filebuf_watermark(int seconds, size_t max)
835 size_t bytes;
837 if (!filebuf)
838 return; /* Audio buffers not yet set up */
840 bytes = seconds?MAX(curtrack_id3.bitrate * seconds * (1000/8), max):max;
841 bytes = MIN(bytes, filebuflen / 2);
842 buf_set_watermark(bytes);
845 const char *get_codec_filename(int cod_spec)
847 const char *fname;
849 #ifdef HAVE_RECORDING
850 /* Can choose decoder or encoder if one available */
851 int type = cod_spec & CODEC_TYPE_MASK;
852 int afmt = cod_spec & CODEC_AFMT_MASK;
854 if ((unsigned)afmt >= AFMT_NUM_CODECS)
855 type = AFMT_UNKNOWN | (type & CODEC_TYPE_MASK);
857 fname = (type == CODEC_TYPE_ENCODER) ?
858 audio_formats[afmt].codec_enc_root_fn :
859 audio_formats[afmt].codec_root_fn;
861 logf("%s: %d - %s",
862 (type == CODEC_TYPE_ENCODER) ? "Encoder" : "Decoder",
863 afmt, fname ? fname : "<unknown>");
864 #else /* !HAVE_RECORDING */
865 /* Always decoder */
866 if ((unsigned)cod_spec >= AFMT_NUM_CODECS)
867 cod_spec = AFMT_UNKNOWN;
868 fname = audio_formats[cod_spec].codec_root_fn;
869 logf("Codec: %d - %s", cod_spec, fname ? fname : "<unknown>");
870 #endif /* HAVE_RECORDING */
872 return fname;
873 } /* get_codec_filename */
875 /* --- Codec thread --- */
876 static bool codec_pcmbuf_insert_callback(
877 const void *ch1, const void *ch2, int count)
879 const char *src[2] = { ch1, ch2 };
881 while (count > 0)
883 int out_count = dsp_output_count(ci.dsp, count);
884 int inp_count;
885 char *dest;
887 /* Prevent audio from a previous track from playing */
888 if (ci.new_track || ci.stop_codec)
889 return true;
891 while ((dest = pcmbuf_request_buffer(&out_count)) == NULL)
893 cancel_cpu_boost();
894 sleep(1);
895 if (ci.seek_time || ci.new_track || ci.stop_codec)
896 return true;
899 /* Get the real input_size for output_size bytes, guarding
900 * against resampling buffer overflows. */
901 inp_count = dsp_input_count(ci.dsp, out_count);
903 if (inp_count <= 0)
904 return true;
906 /* Input size has grown, no error, just don't write more than length */
907 if (inp_count > count)
908 inp_count = count;
910 out_count = dsp_process(ci.dsp, dest, src, inp_count);
912 if (out_count <= 0)
913 return true;
915 pcmbuf_write_complete(out_count);
917 count -= inp_count;
920 return true;
921 } /* codec_pcmbuf_insert_callback */
923 static void* codec_get_memory_callback(size_t *size)
925 *size = MALLOC_BUFSIZE;
926 return malloc_buf;
929 /* Between the codec and PCM track change, we need to keep updating the
930 "elapsed" value of the previous (to the codec, but current to the
931 user/PCM/WPS) track, so that the progressbar reaches the end.
932 During that transition, the WPS will display prevtrack_id3. */
933 static void codec_pcmbuf_position_callback(size_t size) ICODE_ATTR;
934 static void codec_pcmbuf_position_callback(size_t size)
936 /* This is called from an ISR, so be quick */
937 unsigned int time = size * 1000 / 4 / NATIVE_FREQUENCY +
938 prevtrack_id3.elapsed;
940 if (time >= prevtrack_id3.length)
942 pcmbuf_set_position_callback(NULL);
943 prevtrack_id3.elapsed = prevtrack_id3.length;
945 else
946 prevtrack_id3.elapsed = time;
949 static void codec_set_elapsed_callback(unsigned int value)
951 unsigned int latency;
952 if (ci.seek_time)
953 return;
955 #ifdef AB_REPEAT_ENABLE
956 ab_position_report(value);
957 #endif
959 latency = pcmbuf_get_latency();
960 if (value < latency)
961 curtrack_id3.elapsed = 0;
962 else if (value - latency > curtrack_id3.elapsed ||
963 value - latency < curtrack_id3.elapsed - 2)
965 curtrack_id3.elapsed = value - latency;
969 static void codec_set_offset_callback(size_t value)
971 unsigned int latency;
973 if (ci.seek_time)
974 return;
976 latency = pcmbuf_get_latency() * curtrack_id3.bitrate / 8;
977 if (value < latency)
978 curtrack_id3.offset = 0;
979 else
980 curtrack_id3.offset = value - latency;
983 static void codec_advance_buffer_counters(size_t amount)
985 bufadvance(CUR_TI->audio_hid, amount);
986 ci.curpos += amount;
989 /* copy up-to size bytes into ptr and return the actual size copied */
990 static size_t codec_filebuf_callback(void *ptr, size_t size)
992 ssize_t copy_n;
994 if (ci.stop_codec || !playing)
995 return 0;
997 copy_n = bufread(CUR_TI->audio_hid, size, ptr);
999 /* Nothing requested OR nothing left */
1000 if (copy_n == 0)
1001 return 0;
1003 /* Update read and other position pointers */
1004 codec_advance_buffer_counters(copy_n);
1006 /* Return the actual amount of data copied to the buffer */
1007 return copy_n;
1008 } /* codec_filebuf_callback */
1010 static void* codec_request_buffer_callback(size_t *realsize, size_t reqsize)
1012 size_t copy_n = reqsize;
1013 ssize_t ret;
1014 void *ptr;
1016 if (!playing)
1018 *realsize = 0;
1019 return NULL;
1022 ret = bufgetdata(CUR_TI->audio_hid, reqsize, &ptr);
1023 if (ret >= 0)
1024 copy_n = MIN((size_t)ret, reqsize);
1026 if (copy_n == 0)
1028 *realsize = 0;
1029 return NULL;
1032 *realsize = copy_n;
1034 return ptr;
1035 } /* codec_request_buffer_callback */
1037 static int get_codec_base_type(int type)
1039 switch (type) {
1040 case AFMT_MPA_L1:
1041 case AFMT_MPA_L2:
1042 case AFMT_MPA_L3:
1043 return AFMT_MPA_L3;
1046 return type;
1049 static void codec_advance_buffer_callback(size_t amount)
1051 codec_advance_buffer_counters(amount);
1052 codec_set_offset_callback(ci.curpos);
1055 static void codec_advance_buffer_loc_callback(void *ptr)
1057 size_t amount = buf_get_offset(CUR_TI->audio_hid, ptr);
1058 codec_advance_buffer_callback(amount);
1061 static void codec_seek_complete_callback(void)
1063 logf("seek_complete");
1064 if (pcm_is_paused())
1066 /* If this is not a seamless seek, clear the buffer */
1067 pcmbuf_play_stop();
1068 dsp_configure(ci.dsp, DSP_FLUSH, 0);
1070 /* If playback was not 'deliberately' paused, unpause now */
1071 if (!paused)
1072 pcmbuf_pause(false);
1074 ci.seek_time = 0;
1077 static bool codec_seek_buffer_callback(size_t newpos)
1079 logf("codec_seek_buffer_callback");
1081 int ret = bufseek(CUR_TI->audio_hid, newpos);
1082 if (ret == 0) {
1083 ci.curpos = newpos;
1084 return true;
1086 else {
1087 return false;
1091 static void codec_configure_callback(int setting, intptr_t value)
1093 switch (setting) {
1094 case CODEC_SET_FILEBUF_WATERMARK:
1095 set_filebuf_watermark(buffer_margin, value);
1096 break;
1098 default:
1099 if (!dsp_configure(ci.dsp, setting, value))
1100 { logf("Illegal key:%d", setting); }
1104 static void codec_track_changed(void)
1106 LOGFQUEUE("codec > audio Q_AUDIO_TRACK_CHANGED");
1107 queue_post(&audio_queue, Q_AUDIO_TRACK_CHANGED, 0);
1110 static void codec_pcmbuf_track_changed_callback(void)
1112 pcmbuf_set_position_callback(NULL);
1113 pcmbuf_callback_queue_post(Q_AUDIO_TRACK_CHANGED, 0);
1116 static void codec_discard_codec_callback(void)
1118 if (CUR_TI->codec_hid >= 0)
1120 bufclose(CUR_TI->codec_hid);
1121 CUR_TI->codec_hid = -1;
1125 static inline void codec_gapless_track_change(void)
1127 /* callback keeps the progress bar moving while the pcmbuf empties */
1128 pcmbuf_set_position_callback(codec_pcmbuf_position_callback);
1129 /* set the pcmbuf callback for when the track really changes */
1130 pcmbuf_set_event_handler(codec_pcmbuf_track_changed_callback);
1133 static inline void codec_crossfade_track_change(void)
1135 /* Initiate automatic crossfade mode */
1136 pcmbuf_crossfade_init(false);
1137 /* Notify the wps that the track change starts now */
1138 codec_track_changed();
1141 static void codec_track_skip_done(bool was_manual)
1143 /* Manual track change (always crossfade or flush audio). */
1144 if (was_manual)
1146 pcmbuf_crossfade_init(true);
1147 LOGFQUEUE("codec > audio Q_AUDIO_TRACK_CHANGED");
1148 queue_post(&audio_queue, Q_AUDIO_TRACK_CHANGED, 0);
1150 /* Automatic track change w/crossfade, if not in "Track Skip Only" mode. */
1151 else if (pcmbuf_is_crossfade_enabled() && !pcmbuf_is_crossfade_active()
1152 && global_settings.crossfade != CROSSFADE_ENABLE_TRACKSKIP)
1154 if (global_settings.crossfade == CROSSFADE_ENABLE_SHUFFLE_AND_TRACKSKIP)
1156 if (global_settings.playlist_shuffle)
1157 /* shuffle mode is on, so crossfade: */
1158 codec_crossfade_track_change();
1159 else
1160 /* shuffle mode is off, so do a gapless track change */
1161 codec_gapless_track_change();
1163 else
1164 /* normal crossfade: */
1165 codec_crossfade_track_change();
1167 else
1168 /* normal gapless playback. */
1169 codec_gapless_track_change();
1172 static bool codec_load_next_track(void)
1174 intptr_t result = Q_CODEC_REQUEST_FAILED;
1176 prev_track_elapsed = curtrack_id3.elapsed;
1178 #ifdef AB_REPEAT_ENABLE
1179 ab_end_of_track_report();
1180 #endif
1182 logf("Request new track");
1184 if (ci.new_track == 0)
1186 ci.new_track++;
1187 automatic_skip = true;
1190 if (!ci.stop_codec)
1192 trigger_cpu_boost();
1193 LOGFQUEUE("codec >| audio Q_AUDIO_CHECK_NEW_TRACK");
1194 result = queue_send(&audio_queue, Q_AUDIO_CHECK_NEW_TRACK, 0);
1197 switch (result)
1199 case Q_CODEC_REQUEST_COMPLETE:
1200 LOGFQUEUE("codec |< Q_CODEC_REQUEST_COMPLETE");
1201 codec_track_skip_done(!automatic_skip);
1202 return true;
1204 case Q_CODEC_REQUEST_FAILED:
1205 LOGFQUEUE("codec |< Q_CODEC_REQUEST_FAILED");
1206 ci.new_track = 0;
1207 ci.stop_codec = true;
1208 codec_requested_stop = true;
1209 return false;
1211 default:
1212 LOGFQUEUE("codec |< default");
1213 ci.stop_codec = true;
1214 codec_requested_stop = true;
1215 return false;
1219 static bool codec_request_next_track_callback(void)
1221 int prev_codectype;
1223 if (ci.stop_codec || !playing)
1224 return false;
1226 prev_codectype = get_codec_base_type(curtrack_id3.codectype);
1228 if (!codec_load_next_track())
1229 return false;
1231 /* Seek to the beginning of the new track because if the struct
1232 mp3entry was buffered, "elapsed" might not be zero (if the track has
1233 been played already but not unbuffered) */
1234 codec_seek_buffer_callback(curtrack_id3.first_frame_offset);
1236 /* Check if the next codec is the same file. */
1237 if (prev_codectype == get_codec_base_type(curtrack_id3.codectype))
1239 logf("New track loaded");
1240 codec_discard_codec_callback();
1241 return true;
1243 else
1245 logf("New codec:%d/%d", curtrack_id3.codectype, prev_codectype);
1246 return false;
1250 static void codec_thread(void)
1252 struct queue_event ev;
1253 int status;
1255 while (1) {
1256 status = 0;
1258 if (!pcmbuf_is_crossfade_active()) {
1259 cancel_cpu_boost();
1262 queue_wait(&codec_queue, &ev);
1263 codec_requested_stop = false;
1265 switch (ev.id) {
1266 case Q_CODEC_LOAD_DISK:
1267 LOGFQUEUE("codec < Q_CODEC_LOAD_DISK");
1268 queue_reply(&codec_queue, 1);
1269 audio_codec_loaded = true;
1270 ci.stop_codec = false;
1271 status = codec_load_file((const char *)ev.data, &ci);
1272 break;
1274 case Q_CODEC_LOAD:
1275 LOGFQUEUE("codec < Q_CODEC_LOAD");
1276 if (CUR_TI->codec_hid < 0) {
1277 logf("Codec slot is empty!");
1278 /* Wait for the pcm buffer to go empty */
1279 while (pcm_is_playing())
1280 yield();
1281 /* This must be set to prevent an infinite loop */
1282 ci.stop_codec = true;
1283 LOGFQUEUE("codec > codec Q_AUDIO_PLAY");
1284 queue_post(&codec_queue, Q_AUDIO_PLAY, 0);
1285 break;
1288 audio_codec_loaded = true;
1289 ci.stop_codec = false;
1290 status = codec_load_buf(CUR_TI->codec_hid, &ci);
1291 break;
1293 #ifdef AUDIO_HAVE_RECORDING
1294 case Q_ENCODER_LOAD_DISK:
1295 LOGFQUEUE("codec < Q_ENCODER_LOAD_DISK");
1296 audio_codec_loaded = false; /* Not audio codec! */
1297 logf("loading encoder");
1298 ci.stop_encoder = false;
1299 status = codec_load_file((const char *)ev.data, &ci);
1300 logf("encoder stopped");
1301 break;
1302 #endif /* AUDIO_HAVE_RECORDING */
1304 default:
1305 LOGFQUEUE("codec < default");
1308 if (audio_codec_loaded)
1310 if (ci.stop_codec)
1312 status = CODEC_OK;
1313 if (!playing)
1314 pcmbuf_play_stop();
1317 audio_codec_loaded = false;
1320 switch (ev.id) {
1321 case Q_CODEC_LOAD_DISK:
1322 case Q_CODEC_LOAD:
1323 LOGFQUEUE("codec < Q_CODEC_LOAD");
1324 if (playing)
1326 if (ci.new_track || status != CODEC_OK)
1328 if (!ci.new_track)
1330 logf("Codec failure");
1331 gui_syncsplash(HZ*2, "Codec failure");
1334 if (!codec_load_next_track())
1336 LOGFQUEUE("codec > audio Q_AUDIO_STOP");
1337 /* End of playlist */
1338 queue_post(&audio_queue, Q_AUDIO_STOP, 0);
1339 break;
1342 else
1344 logf("Codec finished");
1345 if (ci.stop_codec)
1347 /* Wait for the audio to stop playing before
1348 * triggering the WPS exit */
1349 while(pcm_is_playing())
1351 curtrack_id3.elapsed =
1352 curtrack_id3.length - pcmbuf_get_latency();
1353 sleep(1);
1356 if (codec_requested_stop)
1358 LOGFQUEUE("codec > audio Q_AUDIO_STOP");
1359 queue_post(&audio_queue, Q_AUDIO_STOP, 0);
1361 break;
1365 if (CUR_TI->codec_hid >= 0)
1367 LOGFQUEUE("codec > codec Q_CODEC_LOAD");
1368 queue_post(&codec_queue, Q_CODEC_LOAD, 0);
1370 else
1372 const char *codec_fn =
1373 get_codec_filename(curtrack_id3.codectype);
1374 if (codec_fn)
1376 LOGFQUEUE("codec > codec Q_CODEC_LOAD_DISK");
1377 queue_post(&codec_queue, Q_CODEC_LOAD_DISK,
1378 (intptr_t)codec_fn);
1382 break;
1384 #ifdef AUDIO_HAVE_RECORDING
1385 case Q_ENCODER_LOAD_DISK:
1386 LOGFQUEUE("codec < Q_ENCODER_LOAD_DISK");
1388 if (status == CODEC_OK)
1389 break;
1391 logf("Encoder failure");
1392 gui_syncsplash(HZ*2, "Encoder failure");
1394 if (ci.enc_codec_loaded < 0)
1395 break;
1397 logf("Encoder failed to load");
1398 ci.enc_codec_loaded = -1;
1399 break;
1400 #endif /* AUDIO_HAVE_RECORDING */
1402 default:
1403 LOGFQUEUE("codec < default");
1405 } /* end switch */
1410 /* --- Buffering callbacks --- */
1412 static void buffering_low_buffer_callback(void *data)
1414 (void)data;
1415 logf("low buffer callback");
1417 if (filling == STATE_FULL || filling == STATE_END_OF_PLAYLIST) {
1418 /* force a refill */
1419 LOGFQUEUE("buffering > audio Q_AUDIO_FILL_BUFFER");
1420 queue_post(&audio_queue, Q_AUDIO_FILL_BUFFER, 0);
1424 static void buffering_handle_rebuffer_callback(void *data)
1426 (void)data;
1427 LOGFQUEUE("audio >| audio Q_AUDIO_FLUSH");
1428 queue_post(&audio_queue, Q_AUDIO_FLUSH, 0);
1431 static void buffering_handle_finished_callback(int *data)
1433 logf("handle %d finished buffering", *data);
1435 if (*data == tracks[track_widx].id3_hid)
1437 /* The metadata handle for the last loaded track has been buffered.
1438 We can ask the audio thread to load the rest of the track's data. */
1439 LOGFQUEUE("audio >| audio Q_AUDIO_FINISH_LOAD");
1440 queue_post(&audio_queue, Q_AUDIO_FINISH_LOAD, 0);
1442 else
1444 /* This is most likely an audio handle, so we strip the useless
1445 trailing tags that are left. */
1446 strip_tags(*data);
1448 if (*data == tracks[track_widx-1].audio_hid
1449 && filling == STATE_END_OF_PLAYLIST)
1451 /* This was the last track in the playlist.
1452 We now have all the data we need. */
1453 logf("last track finished buffering");
1454 filling = STATE_FINISHED;
1460 /* --- Audio thread --- */
1462 static bool audio_have_tracks(void)
1464 return (audio_track_count() != 0);
1467 static int audio_free_track_count(void)
1469 /* Used tracks + free tracks adds up to MAX_TRACK - 1 */
1470 return MAX_TRACK - 1 - audio_track_count();
1473 int audio_track_count(void)
1475 /* Calculate difference from track_ridx to track_widx
1476 * taking into account a possible wrap-around. */
1477 return (MAX_TRACK + track_widx - track_ridx) & MAX_TRACK_MASK;
1480 long audio_filebufused(void)
1482 return (long) buf_used();
1485 /* Update track info after successful a codec track change */
1486 static void audio_update_trackinfo(void)
1488 /* Load the curent track's metadata into curtrack_id3 */
1489 if (CUR_TI->id3_hid >= 0)
1490 copy_mp3entry(&curtrack_id3, bufgetid3(CUR_TI->id3_hid));
1492 /* Reset current position */
1493 curtrack_id3.elapsed = 0;
1494 curtrack_id3.offset = 0;
1496 /* Update the codec API */
1497 ci.filesize = CUR_TI->filesize;
1498 ci.id3 = &curtrack_id3;
1499 ci.curpos = 0;
1500 ci.taginfo_ready = &CUR_TI->taginfo_ready;
1503 /* Clear tracks between write and read, non inclusive */
1504 static void audio_clear_track_entries(void)
1506 int cur_idx = track_widx;
1508 logf("Clearing tracks:%d/%d", track_ridx, track_widx);
1510 /* Loop over all tracks from write-to-read */
1511 while (1)
1513 cur_idx = (cur_idx + 1) & MAX_TRACK_MASK;
1515 if (cur_idx == track_ridx)
1516 break;
1518 clear_track_info(&tracks[cur_idx]);
1522 /* Clear all tracks */
1523 static bool audio_release_tracks(void)
1525 int i, cur_idx;
1527 logf("releasing all tracks");
1529 for(i = 0; i < MAX_TRACK; i++)
1531 cur_idx = (track_ridx + i) & MAX_TRACK_MASK;
1532 if (!clear_track_info(&tracks[cur_idx]))
1533 return false;
1536 return true;
1539 static bool audio_loadcodec(bool start_play)
1541 int prev_track;
1542 char codec_path[MAX_PATH]; /* Full path to codec */
1543 const struct mp3entry *id3, *prev_id3;
1545 if (tracks[track_widx].id3_hid < 0) {
1546 return false;
1549 id3 = bufgetid3(tracks[track_widx].id3_hid);
1550 if (!id3)
1551 return false;
1553 const char *codec_fn = get_codec_filename(id3->codectype);
1554 if (codec_fn == NULL)
1555 return false;
1557 tracks[track_widx].codec_hid = -1;
1559 if (start_play)
1561 /* Load the codec directly from disk and save some memory. */
1562 track_ridx = track_widx;
1563 ci.filesize = CUR_TI->filesize;
1564 ci.id3 = &curtrack_id3;
1565 ci.taginfo_ready = &CUR_TI->taginfo_ready;
1566 ci.curpos = 0;
1567 LOGFQUEUE("codec > codec Q_CODEC_LOAD_DISK");
1568 queue_post(&codec_queue, Q_CODEC_LOAD_DISK, (intptr_t)codec_fn);
1569 return true;
1571 else
1573 /* If we already have another track than this one buffered */
1574 if (track_widx != track_ridx)
1576 prev_track = (track_widx - 1) & MAX_TRACK_MASK;
1578 id3 = bufgetid3(tracks[track_widx].id3_hid);
1579 prev_id3 = bufgetid3(tracks[prev_track].id3_hid);
1581 /* If the previous codec is the same as this one, there is no need
1582 * to put another copy of it on the file buffer */
1583 if (id3 && prev_id3 &&
1584 get_codec_base_type(id3->codectype) ==
1585 get_codec_base_type(prev_id3->codectype)
1586 && audio_codec_loaded)
1588 logf("Reusing prev. codec");
1589 return true;
1594 codec_get_full_path(codec_path, codec_fn);
1596 tracks[track_widx].codec_hid = bufopen(codec_path, 0, TYPE_CODEC);
1597 if (tracks[track_widx].codec_hid < 0)
1598 return false;
1600 logf("Loaded codec");
1602 return true;
1605 /* Load metadata for the next track (with bufopen). The rest of the track
1606 loading will be handled by audio_finish_load_track once the metadata has been
1607 actually loaded by the buffering thread. */
1608 static bool audio_load_track(size_t offset, bool start_play)
1610 const char *trackname;
1611 int fd = -1;
1613 start_play_g = start_play; /* will be read by audio_finish_load_track */
1615 /* Stop buffer filling if there is no free track entries.
1616 Don't fill up the last track entry (we wan't to store next track
1617 metadata there). */
1618 if (!audio_free_track_count())
1620 logf("No free tracks");
1621 return false;
1624 last_peek_offset++;
1625 tracks[track_widx].taginfo_ready = false;
1627 logf("Buffering track:%d/%d", track_widx, track_ridx);
1628 /* Get track name from current playlist read position. */
1629 while ((trackname = playlist_peek(last_peek_offset)) != NULL)
1631 /* Handle broken playlists. */
1632 fd = open(trackname, O_RDONLY);
1633 if (fd < 0)
1635 logf("Open failed");
1636 /* Skip invalid entry from playlist. */
1637 playlist_skip_entry(NULL, last_peek_offset);
1639 else
1640 break;
1643 if (!trackname)
1645 logf("End-of-playlist");
1646 memset(&lasttrack_id3, 0, sizeof(struct mp3entry));
1647 filling = STATE_END_OF_PLAYLIST;
1648 return false;
1651 tracks[track_widx].filesize = filesize(fd);
1653 if (offset > tracks[track_widx].filesize)
1654 offset = 0;
1656 /* Set default values */
1657 if (start_play)
1659 buf_set_watermark(AUDIO_DEFAULT_WATERMARK);
1660 dsp_configure(ci.dsp, DSP_RESET, 0);
1661 track_changed = true;
1662 playlist_update_resume_info(audio_current_track());
1665 /* Get track metadata if we don't already have it. */
1666 if (tracks[track_widx].id3_hid < 0)
1668 tracks[track_widx].id3_hid = bufopen(trackname, 0, TYPE_ID3);
1670 if (tracks[track_widx].id3_hid < 0)
1672 /* Buffer is full. */
1673 get_metadata(&lasttrack_id3, fd, trackname);
1674 last_peek_offset--;
1675 close(fd);
1676 logf("buffer is full for now");
1677 filling = STATE_FULL;
1678 return false;
1681 if (track_widx == track_ridx)
1683 buf_request_buffer_handle(tracks[track_widx].id3_hid);
1684 copy_mp3entry(&curtrack_id3, bufgetid3(tracks[track_widx].id3_hid));
1685 curtrack_id3.offset = offset;
1688 if (start_play)
1690 track_changed = true;
1691 playlist_update_resume_info(audio_current_track());
1695 close(fd);
1696 return true;
1699 /* Second part of the track loading: We now have the metadata available, so we
1700 can load the codec, the album art and finally the audio data.
1701 This is called on the audio thread after the buffering thread calls the
1702 buffering_handle_finished_callback callback. */
1703 static void audio_finish_load_track(void)
1705 char msgbuf[80];
1706 size_t file_offset = 0;
1707 size_t offset = 0;
1708 bool start_play = start_play_g;
1710 #if 0
1711 if (cuesheet_is_enabled() && tracks[track_widx].id3.cuesheet_type == 1)
1713 char cuepath[MAX_PATH];
1715 struct cuesheet *cue = start_play ? curr_cue : temp_cue;
1717 if (look_for_cuesheet_file(trackname, cuepath) &&
1718 parse_cuesheet(cuepath, cue))
1720 strcpy((cue)->audio_filename, trackname);
1721 if (start_play)
1722 cue_spoof_id3(curr_cue, &tracks[track_widx].id3);
1725 #endif
1727 if (tracks[track_widx].id3_hid < 0) {
1728 logf("no metatdata");
1729 return;
1732 struct mp3entry *track_id3;
1734 if (track_widx == track_ridx)
1735 track_id3 = &curtrack_id3;
1736 else
1737 track_id3 = bufgetid3(tracks[track_widx].id3_hid);
1739 if (track_id3->length == 0 && track_id3->filesize == 0)
1741 logf("audio_finish_load_track: invalid metadata");
1743 /* Invalid metadata */
1744 bufclose(tracks[track_widx].id3_hid);
1745 tracks[track_widx].id3_hid = -1;
1747 /* Skip invalid entry from playlist. */
1748 playlist_skip_entry(NULL, last_peek_offset--);
1750 /* load next track */
1751 LOGFQUEUE("audio > audio Q_AUDIO_FILL_BUFFER %d", (int)start_play);
1752 queue_post(&audio_queue, Q_AUDIO_FILL_BUFFER, start_play);
1754 return;
1757 #ifdef HAVE_ALBUMART
1758 if (tracks[track_widx].aa_hid < 0 && gui_sync_wps_uses_albumart())
1760 char aa_path[MAX_PATH];
1761 if (find_albumart(track_id3, aa_path, sizeof(aa_path)))
1762 tracks[track_widx].aa_hid = bufopen(aa_path, 0, TYPE_BITMAP);
1764 #endif
1766 /* Load the codec. */
1767 if (!audio_loadcodec(start_play))
1769 if (tracks[track_widx].codec_hid == ERR_BUFFER_FULL)
1771 /* No space for codec on buffer, not an error */
1772 return;
1775 /* This is an error condition, either no codec was found, or reading
1776 * the codec file failed part way through, either way, skip the track */
1777 snprintf(msgbuf, sizeof(msgbuf)-1, "No codec for: %s", track_id3->path);
1778 /* We should not use gui_syncplash from audio thread! */
1779 gui_syncsplash(HZ*2, msgbuf);
1780 /* Skip invalid entry from playlist. */
1781 playlist_skip_entry(NULL, last_peek_offset);
1782 return;
1785 track_id3->elapsed = 0;
1786 offset = track_id3->offset;
1788 enum data_type type = TYPE_PACKET_AUDIO;
1790 switch (track_id3->codectype) {
1791 case AFMT_MPA_L1:
1792 case AFMT_MPA_L2:
1793 case AFMT_MPA_L3:
1794 if (offset > 0) {
1795 file_offset = offset;
1796 track_id3->offset = offset;
1798 break;
1800 case AFMT_WAVPACK:
1801 if (offset > 0) {
1802 file_offset = offset;
1803 track_id3->offset = offset;
1804 track_id3->elapsed = track_id3->length / 2;
1806 break;
1808 case AFMT_OGG_VORBIS:
1809 case AFMT_SPEEX:
1810 case AFMT_FLAC:
1811 case AFMT_PCM_WAV:
1812 case AFMT_A52:
1813 case AFMT_AAC:
1814 case AFMT_MPC:
1815 case AFMT_APE:
1816 case AFMT_WMA:
1817 if (offset > 0)
1818 track_id3->offset = offset;
1819 break;
1821 case AFMT_NSF:
1822 case AFMT_SPC:
1823 case AFMT_SID:
1824 logf("Loading atomic %d",track_id3->codectype);
1825 type = TYPE_ATOMIC_AUDIO;
1826 break;
1829 logf("alt:%s", track_id3->path);
1831 if (file_offset > AUDIO_REBUFFER_GUESS_SIZE)
1832 file_offset -= AUDIO_REBUFFER_GUESS_SIZE;
1833 else if (track_id3->first_frame_offset)
1834 file_offset = track_id3->first_frame_offset;
1835 else
1836 file_offset = 0;
1838 tracks[track_widx].audio_hid = bufopen(track_id3->path, file_offset, type);
1840 if (tracks[track_widx].audio_hid < 0)
1841 return;
1843 /* All required data is now available for the codec. */
1844 tracks[track_widx].taginfo_ready = true;
1846 if (start_play)
1848 ci.curpos=file_offset;
1849 buf_request_buffer_handle(tracks[track_widx].audio_hid);
1852 track_widx = (track_widx + 1) & MAX_TRACK_MASK;
1854 send_event(PLAYBACK_EVENT_TRACK_BUFFER, track_id3);
1856 /* load next track */
1857 LOGFQUEUE("audio > audio Q_AUDIO_FILL_BUFFER");
1858 queue_post(&audio_queue, Q_AUDIO_FILL_BUFFER, 0);
1860 return;
1863 static void audio_fill_file_buffer(bool start_play, size_t offset)
1865 bool had_next_track = audio_next_track() != NULL;
1867 filling = STATE_FILLING;
1868 trigger_cpu_boost();
1870 /* No need to rebuffer if there are track skips pending. */
1871 if (ci.new_track != 0)
1872 return;
1874 /* Must reset the buffer before use if trashed or voice only - voice
1875 file size shouldn't have changed so we can go straight from
1876 BUFFER_STATE_VOICED_ONLY to BUFFER_STATE_INITIALIZED */
1877 if (buffer_state != BUFFER_STATE_INITIALIZED)
1878 audio_reset_buffer();
1880 logf("Starting buffer fill");
1882 if (!start_play)
1883 audio_clear_track_entries();
1885 /* Save the current resume position once. */
1886 playlist_update_resume_info(audio_current_track());
1888 audio_load_track(offset, start_play);
1890 if (!had_next_track && audio_next_track())
1891 track_changed = true;
1894 static void audio_rebuffer(void)
1896 logf("Forcing rebuffer");
1898 clear_track_info(CUR_TI);
1900 /* Reset track pointers */
1901 track_widx = track_ridx;
1902 audio_clear_track_entries();
1904 /* Fill the buffer */
1905 last_peek_offset = -1;
1906 ci.curpos = 0;
1908 if (!CUR_TI->taginfo_ready)
1909 memset(&curtrack_id3, 0, sizeof(struct mp3entry));
1911 audio_fill_file_buffer(false, 0);
1914 /* Called on request from the codec to get a new track. This is the codec part
1915 of the track transition. */
1916 static int audio_check_new_track(void)
1918 int track_count = audio_track_count();
1919 int old_track_ridx = track_ridx;
1920 int i, idx;
1921 bool forward;
1923 /* Now it's good time to send track finish events. */
1924 send_event(PLAYBACK_EVENT_TRACK_FINISH, &curtrack_id3);
1925 if (dir_skip)
1927 dir_skip = false;
1928 if (playlist_next_dir(ci.new_track))
1930 ci.new_track = 0;
1931 audio_rebuffer();
1932 goto skip_done;
1934 else
1936 LOGFQUEUE("audio >|= codec Q_CODEC_REQUEST_FAILED");
1937 return Q_CODEC_REQUEST_FAILED;
1941 if (new_playlist)
1942 ci.new_track = 0;
1944 /* If the playlist isn't that big */
1945 if (automatic_skip)
1947 while (!playlist_check(ci.new_track))
1949 if (ci.new_track >= 0)
1951 LOGFQUEUE("audio >|= codec Q_CODEC_REQUEST_FAILED");
1952 return Q_CODEC_REQUEST_FAILED;
1954 ci.new_track++;
1958 /* Update the playlist */
1959 last_peek_offset -= ci.new_track;
1961 if (playlist_next(ci.new_track) < 0)
1963 LOGFQUEUE("audio >|= codec Q_CODEC_REQUEST_FAILED");
1964 return Q_CODEC_REQUEST_FAILED;
1967 if (new_playlist)
1969 ci.new_track = 1;
1970 new_playlist = false;
1973 /* Save the track metadata to allow the WPS to display it
1974 while PCM finishes playing that track */
1975 copy_mp3entry(&prevtrack_id3, &curtrack_id3);
1977 /* Update the main buffer copy of the track metadata with the one
1978 the codec has been using (for the unbuffer callbacks) */
1979 if (CUR_TI->id3_hid >= 0)
1980 copy_mp3entry(bufgetid3(CUR_TI->id3_hid), &curtrack_id3);
1982 /* Save a pointer to the old track to allow later clearing */
1983 prev_ti = CUR_TI;
1985 for (i = 0; i < ci.new_track; i++)
1987 idx = (track_ridx + i) & MAX_TRACK_MASK;
1988 struct mp3entry *id3 = bufgetid3(tracks[idx].id3_hid);
1989 ssize_t offset = buf_handle_offset(tracks[idx].audio_hid);
1990 if (!id3 || offset < 0 || (unsigned)offset > id3->first_frame_offset)
1992 /* We don't have all the audio data for that track, so clear it,
1993 but keep the metadata. */
1994 if (tracks[idx].audio_hid >= 0 && bufclose(tracks[idx].audio_hid))
1996 tracks[idx].audio_hid = -1;
1997 tracks[idx].filesize = 0;
2002 /* Move to the new track */
2003 track_ridx = (track_ridx + ci.new_track) & MAX_TRACK_MASK;
2005 buf_set_base_handle(CUR_TI->audio_hid);
2007 if (automatic_skip)
2009 wps_offset = -ci.new_track;
2010 track_changed = true;
2013 /* If it is not safe to even skip this many track entries */
2014 if (ci.new_track >= track_count || ci.new_track <= track_count - MAX_TRACK)
2016 ci.new_track = 0;
2017 audio_rebuffer();
2018 goto skip_done;
2021 forward = ci.new_track > 0;
2022 ci.new_track = 0;
2024 /* If the target track is clearly not in memory */
2025 if (CUR_TI->filesize == 0 || !CUR_TI->taginfo_ready)
2027 audio_rebuffer();
2028 goto skip_done;
2031 /* When skipping backwards, it is possible that we've found a track that's
2032 * buffered, but which is around the track-wrap and therefore not the track
2033 * we are looking for */
2034 if (!forward)
2036 int cur_idx = track_ridx;
2037 bool taginfo_ready = true;
2038 /* We've wrapped the buffer backwards if new > old */
2039 bool wrap = track_ridx > old_track_ridx;
2041 while (1)
2043 cur_idx = (cur_idx + 1) & MAX_TRACK_MASK;
2045 /* if we've advanced past the wrap when cur_idx is zeroed */
2046 if (!cur_idx)
2047 wrap = false;
2049 /* if we aren't still on the wrap and we've caught the old track */
2050 if (!(wrap || cur_idx < old_track_ridx))
2051 break;
2053 /* If we hit a track in between without valid tag info, bail */
2054 if (!tracks[cur_idx].taginfo_ready)
2056 taginfo_ready = false;
2057 break;
2060 if (!taginfo_ready)
2062 audio_rebuffer();
2066 skip_done:
2067 audio_update_trackinfo();
2068 LOGFQUEUE("audio >|= codec Q_CODEC_REQUEST_COMPLETE");
2069 return Q_CODEC_REQUEST_COMPLETE;
2072 unsigned long audio_prev_elapsed(void)
2074 return prev_track_elapsed;
2077 static void audio_stop_codec_flush(void)
2079 ci.stop_codec = true;
2080 pcmbuf_pause(true);
2082 while (audio_codec_loaded)
2083 yield();
2085 /* If the audio codec is not loaded any more, and the audio is still
2086 * playing, it is now and _only_ now safe to call this function from the
2087 * audio thread */
2088 if (pcm_is_playing())
2090 pcmbuf_play_stop();
2091 pcmbuf_queue_clear();
2093 pcmbuf_pause(paused);
2096 static void audio_stop_playback(void)
2098 /* If we were playing, save resume information */
2099 if (playing)
2101 struct mp3entry *id3 = NULL;
2103 if (!ci.stop_codec)
2105 /* Set this early, the outside code yields and may allow the codec
2106 to try to wait for a reply on a buffer wait */
2107 ci.stop_codec = true;
2108 id3 = audio_current_track();
2111 /* Save the current playing spot, or NULL if the playlist has ended */
2112 playlist_update_resume_info(id3);
2114 /* TODO: Create auto bookmark too? */
2116 prev_track_elapsed = curtrack_id3.elapsed;
2118 remove_event(EVENT_BUFFER_LOW, buffering_low_buffer_callback);
2121 paused = false;
2122 audio_stop_codec_flush();
2123 playing = false;
2125 filling = STATE_IDLE;
2127 /* Mark all entries null. */
2128 audio_clear_track_entries();
2130 /* Close all tracks */
2131 audio_release_tracks();
2133 memset(&curtrack_id3, 0, sizeof(struct mp3entry));
2136 static void audio_play_start(size_t offset)
2138 int i;
2140 #if INPUT_SRC_CAPS != 0
2141 audio_set_input_source(AUDIO_SRC_PLAYBACK, SRCF_PLAYBACK);
2142 audio_set_output_source(AUDIO_SRC_PLAYBACK);
2143 #endif
2145 /* Wait for any previously playing audio to flush - TODO: Not necessary? */
2146 paused = false;
2147 audio_stop_codec_flush();
2149 track_changed = true;
2151 playing = true;
2153 ci.new_track = 0;
2154 ci.seek_time = 0;
2155 wps_offset = 0;
2157 sound_set_volume(global_settings.volume);
2158 track_widx = track_ridx = 0;
2160 /* Clear all track entries. */
2161 for (i = 0; i < MAX_TRACK; i++) {
2162 clear_track_info(&tracks[i]);
2165 last_peek_offset = -1;
2167 /* Officially playing */
2168 queue_reply(&audio_queue, 1);
2170 #ifndef HAVE_FLASH_STORAGE
2171 set_filebuf_watermark(buffer_margin, 0);
2172 #endif
2174 audio_fill_file_buffer(true, offset);
2176 add_event(EVENT_BUFFER_LOW, false, buffering_low_buffer_callback);
2178 LOGFQUEUE("audio > audio Q_AUDIO_TRACK_CHANGED");
2179 queue_post(&audio_queue, Q_AUDIO_TRACK_CHANGED, 0);
2183 /* Invalidates all but currently playing track. */
2184 static void audio_invalidate_tracks(void)
2186 if (audio_have_tracks())
2188 last_peek_offset = 0;
2189 track_widx = track_ridx;
2191 /* Mark all other entries null (also buffered wrong metadata). */
2192 audio_clear_track_entries();
2194 track_widx = (track_widx + 1) & MAX_TRACK_MASK;
2196 audio_fill_file_buffer(false, 0);
2200 static void audio_new_playlist(void)
2202 /* Prepare to start a new fill from the beginning of the playlist */
2203 last_peek_offset = -1;
2204 if (audio_have_tracks())
2206 if (paused)
2207 skipped_during_pause = true;
2208 track_widx = track_ridx;
2209 audio_clear_track_entries();
2211 track_widx = (track_widx + 1) & MAX_TRACK_MASK;
2213 /* Mark the current track as invalid to prevent skipping back to it */
2214 CUR_TI->taginfo_ready = false;
2217 /* Signal the codec to initiate a track change forward */
2218 new_playlist = true;
2219 ci.new_track = 1;
2221 /* Officially playing */
2222 queue_reply(&audio_queue, 1);
2224 audio_fill_file_buffer(false, 0);
2227 /* Called on manual track skip */
2228 static void audio_initiate_track_change(long direction)
2230 logf("audio_initiate_track_change(%ld)", direction);
2232 ci.new_track += direction;
2233 wps_offset -= direction;
2234 if (paused)
2235 skipped_during_pause = true;
2238 /* Called on manual dir skip */
2239 static void audio_initiate_dir_change(long direction)
2241 dir_skip = true;
2242 ci.new_track = direction;
2243 if (paused)
2244 skipped_during_pause = true;
2247 /* Called when PCM track change is complete */
2248 static void audio_finalise_track_change(void)
2250 logf("audio_finalise_track_change");
2252 if (automatic_skip)
2254 wps_offset = 0;
2255 automatic_skip = false;
2257 /* Invalidate prevtrack_id3 */
2258 prevtrack_id3.path[0] = 0;
2260 if (prev_ti && prev_ti->audio_hid < 0)
2262 /* No audio left so we clear all the track info. */
2263 clear_track_info(prev_ti);
2266 if (prev_ti && prev_ti->id3_hid >= 0)
2268 /* Reset the elapsed time to force the progressbar to be empty if
2269 the user skips back to this track */
2270 bufgetid3(prev_ti->id3_hid)->elapsed = 0;
2274 send_event(PLAYBACK_EVENT_TRACK_CHANGE, &curtrack_id3);
2276 track_changed = true;
2277 playlist_update_resume_info(audio_current_track());
2281 * Layout audio buffer as follows - iram buffer depends on target:
2282 * [|SWAP:iram][|TALK]|MALLOC|FILE|GUARD|PCM|[SWAP:dram[|iram]|]
2284 static void audio_reset_buffer(void)
2286 /* see audio_get_recording_buffer if this is modified */
2287 logf("audio_reset_buffer");
2289 /* If the setup of anything allocated before the file buffer is
2290 changed, do check the adjustments after the buffer_alloc call
2291 as it will likely be affected and need sliding over */
2293 /* Initially set up file buffer as all space available */
2294 malloc_buf = audiobuf + talk_get_bufsize();
2295 /* Align the malloc buf to line size. Especially important to cf
2296 targets that do line reads/writes. */
2297 malloc_buf = (unsigned char *)(((uintptr_t)malloc_buf + 15) & ~15);
2298 filebuf = malloc_buf + MALLOC_BUFSIZE; /* filebuf line align implied */
2299 filebuflen = audiobufend - filebuf;
2301 filebuflen &= ~15;
2303 /* Subtract whatever the pcm buffer says it used plus the guard buffer */
2304 filebuflen -= pcmbuf_init(filebuf + filebuflen) + GUARD_BUFSIZE;
2306 /* Make sure filebuflen is a longword multiple after adjustment - filebuf
2307 will already be line aligned */
2308 filebuflen &= ~3;
2310 buffering_reset(filebuf, filebuflen);
2312 /* Clear any references to the file buffer */
2313 buffer_state = BUFFER_STATE_INITIALIZED;
2315 #if defined(ROCKBOX_HAS_LOGF) && defined(LOGF_ENABLE)
2316 /* Make sure everything adds up - yes, some info is a bit redundant but
2317 aids viewing and the sumation of certain variables should add up to
2318 the location of others. */
2320 size_t pcmbufsize;
2321 const unsigned char *pcmbuf = pcmbuf_get_meminfo(&pcmbufsize);
2322 logf("mabuf: %08X", (unsigned)malloc_buf);
2323 logf("mabufe: %08X", (unsigned)(malloc_buf + MALLOC_BUFSIZE));
2324 logf("fbuf: %08X", (unsigned)filebuf);
2325 logf("fbufe: %08X", (unsigned)(filebuf + filebuflen));
2326 logf("gbuf: %08X", (unsigned)(filebuf + filebuflen));
2327 logf("gbufe: %08X", (unsigned)(filebuf + filebuflen + GUARD_BUFSIZE));
2328 logf("pcmb: %08X", (unsigned)pcmbuf);
2329 logf("pcmbe: %08X", (unsigned)(pcmbuf + pcmbufsize));
2331 #endif
2334 static void audio_thread(void)
2336 struct queue_event ev;
2338 pcm_postinit();
2340 audio_thread_ready = true;
2342 while (1)
2344 if (filling != STATE_FILLING) {
2345 cancel_cpu_boost();
2348 if (!pcmbuf_queue_scan(&ev))
2349 queue_wait_w_tmo(&audio_queue, &ev, HZ/2);
2351 switch (ev.id) {
2353 case Q_AUDIO_FILL_BUFFER:
2354 LOGFQUEUE("audio < Q_AUDIO_FILL_BUFFER %d", (int)ev.data);
2355 audio_fill_file_buffer((bool)ev.data, 0);
2356 break;
2358 case Q_AUDIO_FINISH_LOAD:
2359 LOGFQUEUE("audio < Q_AUDIO_FINISH_LOAD");
2360 audio_finish_load_track();
2361 break;
2363 case Q_AUDIO_PLAY:
2364 LOGFQUEUE("audio < Q_AUDIO_PLAY");
2365 if (playing && ev.data <= 0)
2366 audio_new_playlist();
2367 else
2369 audio_stop_playback();
2370 audio_play_start((size_t)ev.data);
2372 break;
2374 case Q_AUDIO_STOP:
2375 LOGFQUEUE("audio < Q_AUDIO_STOP");
2376 if (playing)
2377 audio_stop_playback();
2378 if (ev.data != 0)
2379 queue_clear(&audio_queue);
2380 break;
2382 case Q_AUDIO_PAUSE:
2383 LOGFQUEUE("audio < Q_AUDIO_PAUSE");
2384 if (!(bool) ev.data && skipped_during_pause && !pcmbuf_is_crossfade_active())
2385 pcmbuf_play_stop(); /* Flush old track on resume after skip */
2386 skipped_during_pause = false;
2387 if (!playing)
2388 break;
2389 pcmbuf_pause((bool)ev.data);
2390 paused = (bool)ev.data;
2391 break;
2393 case Q_AUDIO_SKIP:
2394 LOGFQUEUE("audio < Q_AUDIO_SKIP");
2395 audio_initiate_track_change((long)ev.data);
2396 break;
2398 case Q_AUDIO_PRE_FF_REWIND:
2399 LOGFQUEUE("audio < Q_AUDIO_PRE_FF_REWIND");
2400 if (!playing)
2401 break;
2402 pcmbuf_pause(true);
2403 break;
2405 case Q_AUDIO_FF_REWIND:
2406 LOGFQUEUE("audio < Q_AUDIO_FF_REWIND");
2407 if (!playing)
2408 break;
2409 if (automatic_skip)
2411 /* An automatic track skip is in progress. Finalize it,
2412 then go back to the previous track */
2413 audio_finalise_track_change();
2414 ci.new_track = -1;
2416 ci.seek_time = (long)ev.data+1;
2417 break;
2419 case Q_AUDIO_CHECK_NEW_TRACK:
2420 LOGFQUEUE("audio < Q_AUDIO_CHECK_NEW_TRACK");
2421 queue_reply(&audio_queue, audio_check_new_track());
2422 break;
2424 case Q_AUDIO_DIR_SKIP:
2425 LOGFQUEUE("audio < Q_AUDIO_DIR_SKIP");
2426 audio_initiate_dir_change(ev.data);
2427 break;
2429 case Q_AUDIO_FLUSH:
2430 LOGFQUEUE("audio < Q_AUDIO_FLUSH");
2431 audio_invalidate_tracks();
2432 break;
2434 case Q_AUDIO_TRACK_CHANGED:
2435 /* PCM track change done */
2436 LOGFQUEUE("audio < Q_AUDIO_TRACK_CHANGED");
2437 audio_finalise_track_change();
2438 break;
2440 #ifndef SIMULATOR
2441 case SYS_USB_CONNECTED:
2442 LOGFQUEUE("audio < SYS_USB_CONNECTED");
2443 if (playing)
2444 audio_stop_playback();
2445 #ifdef PLAYBACK_VOICE
2446 voice_stop();
2447 #endif
2448 usb_acknowledge(SYS_USB_CONNECTED_ACK);
2449 usb_wait_for_disconnect(&audio_queue);
2451 /* Mark all entries null. */
2452 audio_clear_track_entries();
2454 /* release tracks to make sure all handles are closed */
2455 audio_release_tracks();
2456 break;
2457 #endif
2459 case SYS_TIMEOUT:
2460 LOGFQUEUE_SYS_TIMEOUT("audio < SYS_TIMEOUT");
2461 break;
2463 default:
2464 LOGFQUEUE("audio < default");
2465 break;
2466 } /* end switch */
2467 } /* end while */
2470 /* Initialize the audio system - called from init() in main.c.
2471 * Last function because of all the references to internal symbols
2473 void audio_init(void)
2475 struct thread_entry *audio_thread_p;
2477 /* Can never do this twice */
2478 if (audio_is_initialized)
2480 logf("audio: already initialized");
2481 return;
2484 logf("audio: initializing");
2486 /* Initialize queues before giving control elsewhere in case it likes
2487 to send messages. Thread creation will be delayed however so nothing
2488 starts running until ready if something yields such as talk_init. */
2489 queue_init(&audio_queue, true);
2490 queue_init(&codec_queue, false);
2491 queue_init(&pcmbuf_queue, false);
2493 pcm_init();
2495 /* Initialize codec api. */
2496 ci.read_filebuf = codec_filebuf_callback;
2497 ci.pcmbuf_insert = codec_pcmbuf_insert_callback;
2498 ci.get_codec_memory = codec_get_memory_callback;
2499 ci.request_buffer = codec_request_buffer_callback;
2500 ci.advance_buffer = codec_advance_buffer_callback;
2501 ci.advance_buffer_loc = codec_advance_buffer_loc_callback;
2502 ci.request_next_track = codec_request_next_track_callback;
2503 ci.seek_buffer = codec_seek_buffer_callback;
2504 ci.seek_complete = codec_seek_complete_callback;
2505 ci.set_elapsed = codec_set_elapsed_callback;
2506 ci.set_offset = codec_set_offset_callback;
2507 ci.configure = codec_configure_callback;
2508 ci.discard_codec = codec_discard_codec_callback;
2509 ci.dsp = (struct dsp_config *)dsp_configure(NULL, DSP_MYDSP,
2510 CODEC_IDX_AUDIO);
2512 /* initialize the buffer */
2513 filebuf = audiobuf;
2515 /* audio_reset_buffer must to know the size of voice buffer so init
2516 talk first */
2517 talk_init();
2519 codec_thread_p = create_thread(
2520 codec_thread, codec_stack, sizeof(codec_stack),
2521 CREATE_THREAD_FROZEN,
2522 codec_thread_name IF_PRIO(, PRIORITY_PLAYBACK)
2523 IF_COP(, CPU));
2525 queue_enable_queue_send(&codec_queue, &codec_queue_sender_list,
2526 codec_thread_p);
2528 audio_thread_p = create_thread(audio_thread, audio_stack,
2529 sizeof(audio_stack), CREATE_THREAD_FROZEN,
2530 audio_thread_name IF_PRIO(, PRIORITY_USER_INTERFACE)
2531 IF_COP(, CPU));
2533 queue_enable_queue_send(&audio_queue, &audio_queue_sender_list,
2534 audio_thread_p);
2536 #ifdef PLAYBACK_VOICE
2537 voice_thread_init();
2538 #endif
2540 /* Set crossfade setting for next buffer init which should be about... */
2541 pcmbuf_crossfade_enable(global_settings.crossfade);
2543 /* initialize the buffering system */
2545 buffering_init();
2546 /* ...now! Set up the buffers */
2547 audio_reset_buffer();
2549 int i;
2550 for(i = 0; i < MAX_TRACK; i++)
2552 tracks[i].audio_hid = -1;
2553 tracks[i].id3_hid = -1;
2554 tracks[i].codec_hid = -1;
2555 #ifdef HAVE_ALBUMART
2556 tracks[i].aa_hid = -1;
2557 #endif
2560 add_event(EVENT_HANDLE_REBUFFER, false, buffering_handle_rebuffer_callback);
2561 add_event(EVENT_HANDLE_FINISHED, false, buffering_handle_finished_callback);
2563 /* Probably safe to say */
2564 audio_is_initialized = true;
2566 sound_settings_apply();
2567 #ifndef HAVE_FLASH_STORAGE
2568 audio_set_buffer_margin(global_settings.buffer_margin);
2569 #endif
2571 /* it's safe to let the threads run now */
2572 #ifdef PLAYBACK_VOICE
2573 voice_thread_resume();
2574 #endif
2575 thread_thaw(codec_thread_p);
2576 thread_thaw(audio_thread_p);
2578 } /* audio_init */
2580 void audio_wait_for_init(void)
2582 /* audio thread will only set this once after it finished the final
2583 * audio hardware init so this little construct is safe - even
2584 * cross-core. */
2585 while (!audio_thread_ready)
2587 sleep(0);