Make the image tags examples nicer.
[Rockbox.git] / apps / playback.c
blob88f1bb58168808b00d5dfda7b224f87a1bf66768
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 /* Copied from mpeg.c. Should be moved somewhere else. */
1046 static int codec_get_file_pos(void)
1048 int pos = -1;
1049 struct mp3entry *id3 = audio_current_track();
1051 if (id3->vbr)
1053 if (id3->has_toc)
1055 /* Use the TOC to find the new position */
1056 unsigned int percent, remainder;
1057 int curtoc, nexttoc, plen;
1059 percent = (id3->elapsed*100)/id3->length;
1060 if (percent > 99)
1061 percent = 99;
1063 curtoc = id3->toc[percent];
1065 if (percent < 99)
1066 nexttoc = id3->toc[percent+1];
1067 else
1068 nexttoc = 256;
1070 pos = (id3->filesize/256)*curtoc;
1072 /* Use the remainder to get a more accurate position */
1073 remainder = (id3->elapsed*100)%id3->length;
1074 remainder = (remainder*100)/id3->length;
1075 plen = (nexttoc - curtoc)*(id3->filesize/256);
1076 pos += (plen/100)*remainder;
1078 else
1080 /* No TOC exists, estimate the new position */
1081 pos = (id3->filesize / (id3->length / 1000)) *
1082 (id3->elapsed / 1000);
1085 else if (id3->bitrate)
1086 pos = id3->elapsed * (id3->bitrate / 8);
1087 else
1088 return -1;
1090 pos += id3->first_frame_offset;
1092 /* Don't seek right to the end of the file so that we can
1093 transition properly to the next song */
1094 if (pos >= (int)(id3->filesize - id3->id3v1len))
1095 pos = id3->filesize - id3->id3v1len - 1;
1097 return pos;
1100 static off_t codec_mp3_get_filepos_callback(int newtime)
1102 off_t newpos;
1104 curtrack_id3.elapsed = newtime;
1105 newpos = codec_get_file_pos();
1107 return newpos;
1110 static void codec_seek_complete_callback(void)
1112 logf("seek_complete");
1113 if (pcm_is_paused())
1115 /* If this is not a seamless seek, clear the buffer */
1116 pcmbuf_play_stop();
1117 dsp_configure(ci.dsp, DSP_FLUSH, 0);
1119 /* If playback was not 'deliberately' paused, unpause now */
1120 if (!paused)
1121 pcmbuf_pause(false);
1123 ci.seek_time = 0;
1126 static bool codec_seek_buffer_callback(size_t newpos)
1128 logf("codec_seek_buffer_callback");
1130 int ret = bufseek(CUR_TI->audio_hid, newpos);
1131 if (ret == 0) {
1132 ci.curpos = newpos;
1133 return true;
1135 else {
1136 return false;
1140 static void codec_configure_callback(int setting, intptr_t value)
1142 switch (setting) {
1143 case CODEC_SET_FILEBUF_WATERMARK:
1144 set_filebuf_watermark(buffer_margin, value);
1145 break;
1147 default:
1148 if (!dsp_configure(ci.dsp, setting, value))
1149 { logf("Illegal key:%d", setting); }
1153 static void codec_track_changed(void)
1155 LOGFQUEUE("codec > audio Q_AUDIO_TRACK_CHANGED");
1156 queue_post(&audio_queue, Q_AUDIO_TRACK_CHANGED, 0);
1159 static void codec_pcmbuf_track_changed_callback(void)
1161 pcmbuf_set_position_callback(NULL);
1162 pcmbuf_callback_queue_post(Q_AUDIO_TRACK_CHANGED, 0);
1165 static void codec_discard_codec_callback(void)
1167 if (CUR_TI->codec_hid >= 0)
1169 bufclose(CUR_TI->codec_hid);
1170 CUR_TI->codec_hid = -1;
1174 static inline void codec_gapless_track_change(void)
1176 /* callback keeps the progress bar moving while the pcmbuf empties */
1177 pcmbuf_set_position_callback(codec_pcmbuf_position_callback);
1178 /* set the pcmbuf callback for when the track really changes */
1179 pcmbuf_set_event_handler(codec_pcmbuf_track_changed_callback);
1182 static inline void codec_crossfade_track_change(void)
1184 /* Initiate automatic crossfade mode */
1185 pcmbuf_crossfade_init(false);
1186 /* Notify the wps that the track change starts now */
1187 codec_track_changed();
1190 static void codec_track_skip_done(bool was_manual)
1192 /* Manual track change (always crossfade or flush audio). */
1193 if (was_manual)
1195 pcmbuf_crossfade_init(true);
1196 LOGFQUEUE("codec > audio Q_AUDIO_TRACK_CHANGED");
1197 queue_post(&audio_queue, Q_AUDIO_TRACK_CHANGED, 0);
1199 /* Automatic track change w/crossfade, if not in "Track Skip Only" mode. */
1200 else if (pcmbuf_is_crossfade_enabled() && !pcmbuf_is_crossfade_active()
1201 && global_settings.crossfade != CROSSFADE_ENABLE_TRACKSKIP)
1203 if (global_settings.crossfade == CROSSFADE_ENABLE_SHUFFLE_AND_TRACKSKIP)
1205 if (global_settings.playlist_shuffle)
1206 /* shuffle mode is on, so crossfade: */
1207 codec_crossfade_track_change();
1208 else
1209 /* shuffle mode is off, so do a gapless track change */
1210 codec_gapless_track_change();
1212 else
1213 /* normal crossfade: */
1214 codec_crossfade_track_change();
1216 else
1217 /* normal gapless playback. */
1218 codec_gapless_track_change();
1221 static bool codec_load_next_track(void)
1223 intptr_t result = Q_CODEC_REQUEST_FAILED;
1225 prev_track_elapsed = curtrack_id3.elapsed;
1227 #ifdef AB_REPEAT_ENABLE
1228 ab_end_of_track_report();
1229 #endif
1231 logf("Request new track");
1233 if (ci.new_track == 0)
1235 ci.new_track++;
1236 automatic_skip = true;
1239 if (!ci.stop_codec)
1241 trigger_cpu_boost();
1242 LOGFQUEUE("codec >| audio Q_AUDIO_CHECK_NEW_TRACK");
1243 result = queue_send(&audio_queue, Q_AUDIO_CHECK_NEW_TRACK, 0);
1246 switch (result)
1248 case Q_CODEC_REQUEST_COMPLETE:
1249 LOGFQUEUE("codec |< Q_CODEC_REQUEST_COMPLETE");
1250 codec_track_skip_done(!automatic_skip);
1251 return true;
1253 case Q_CODEC_REQUEST_FAILED:
1254 LOGFQUEUE("codec |< Q_CODEC_REQUEST_FAILED");
1255 ci.new_track = 0;
1256 ci.stop_codec = true;
1257 codec_requested_stop = true;
1258 return false;
1260 default:
1261 LOGFQUEUE("codec |< default");
1262 ci.stop_codec = true;
1263 codec_requested_stop = true;
1264 return false;
1268 static bool codec_request_next_track_callback(void)
1270 int prev_codectype;
1272 if (ci.stop_codec || !playing)
1273 return false;
1275 prev_codectype = get_codec_base_type(curtrack_id3.codectype);
1277 if (!codec_load_next_track())
1278 return false;
1280 /* Check if the next codec is the same file. */
1281 if (prev_codectype == get_codec_base_type(curtrack_id3.codectype))
1283 logf("New track loaded");
1284 codec_discard_codec_callback();
1285 return true;
1287 else
1289 logf("New codec:%d/%d", curtrack_id3.codectype, prev_codectype);
1290 return false;
1294 static void codec_thread(void)
1296 struct queue_event ev;
1297 int status;
1299 while (1) {
1300 status = 0;
1301 cancel_cpu_boost();
1302 queue_wait(&codec_queue, &ev);
1303 codec_requested_stop = false;
1305 switch (ev.id) {
1306 case Q_CODEC_LOAD_DISK:
1307 LOGFQUEUE("codec < Q_CODEC_LOAD_DISK");
1308 queue_reply(&codec_queue, 1);
1309 audio_codec_loaded = true;
1310 ci.stop_codec = false;
1311 status = codec_load_file((const char *)ev.data, &ci);
1312 break;
1314 case Q_CODEC_LOAD:
1315 LOGFQUEUE("codec < Q_CODEC_LOAD");
1316 if (CUR_TI->codec_hid < 0) {
1317 logf("Codec slot is empty!");
1318 /* Wait for the pcm buffer to go empty */
1319 while (pcm_is_playing())
1320 yield();
1321 /* This must be set to prevent an infinite loop */
1322 ci.stop_codec = true;
1323 LOGFQUEUE("codec > codec Q_AUDIO_PLAY");
1324 queue_post(&codec_queue, Q_AUDIO_PLAY, 0);
1325 break;
1328 audio_codec_loaded = true;
1329 ci.stop_codec = false;
1330 status = codec_load_buf(CUR_TI->codec_hid, &ci);
1331 break;
1333 #ifdef AUDIO_HAVE_RECORDING
1334 case Q_ENCODER_LOAD_DISK:
1335 LOGFQUEUE("codec < Q_ENCODER_LOAD_DISK");
1336 audio_codec_loaded = false; /* Not audio codec! */
1337 logf("loading encoder");
1338 ci.stop_encoder = false;
1339 status = codec_load_file((const char *)ev.data, &ci);
1340 logf("encoder stopped");
1341 break;
1342 #endif /* AUDIO_HAVE_RECORDING */
1344 default:
1345 LOGFQUEUE("codec < default");
1348 if (audio_codec_loaded)
1350 if (ci.stop_codec)
1352 status = CODEC_OK;
1353 if (!playing)
1354 pcmbuf_play_stop();
1357 audio_codec_loaded = false;
1360 switch (ev.id) {
1361 case Q_CODEC_LOAD_DISK:
1362 case Q_CODEC_LOAD:
1363 LOGFQUEUE("codec < Q_CODEC_LOAD");
1364 if (playing)
1366 if (ci.new_track || status != CODEC_OK)
1368 if (!ci.new_track)
1370 logf("Codec failure");
1371 gui_syncsplash(HZ*2, "Codec failure");
1374 if (!codec_load_next_track())
1376 LOGFQUEUE("codec > audio Q_AUDIO_STOP");
1377 /* End of playlist */
1378 queue_post(&audio_queue, Q_AUDIO_STOP, 0);
1379 break;
1382 else
1384 logf("Codec finished");
1385 if (ci.stop_codec)
1387 /* Wait for the audio to stop playing before
1388 * triggering the WPS exit */
1389 while(pcm_is_playing())
1391 curtrack_id3.elapsed =
1392 curtrack_id3.length - pcmbuf_get_latency();
1393 sleep(1);
1396 if (codec_requested_stop)
1398 LOGFQUEUE("codec > audio Q_AUDIO_STOP");
1399 queue_post(&audio_queue, Q_AUDIO_STOP, 0);
1401 break;
1405 if (CUR_TI->codec_hid >= 0)
1407 LOGFQUEUE("codec > codec Q_CODEC_LOAD");
1408 queue_post(&codec_queue, Q_CODEC_LOAD, 0);
1410 else
1412 const char *codec_fn =
1413 get_codec_filename(curtrack_id3.codectype);
1414 if (codec_fn)
1416 LOGFQUEUE("codec > codec Q_CODEC_LOAD_DISK");
1417 queue_post(&codec_queue, Q_CODEC_LOAD_DISK,
1418 (intptr_t)codec_fn);
1422 break;
1424 #ifdef AUDIO_HAVE_RECORDING
1425 case Q_ENCODER_LOAD_DISK:
1426 LOGFQUEUE("codec < Q_ENCODER_LOAD_DISK");
1428 if (status == CODEC_OK)
1429 break;
1431 logf("Encoder failure");
1432 gui_syncsplash(HZ*2, "Encoder failure");
1434 if (ci.enc_codec_loaded < 0)
1435 break;
1437 logf("Encoder failed to load");
1438 ci.enc_codec_loaded = -1;
1439 break;
1440 #endif /* AUDIO_HAVE_RECORDING */
1442 default:
1443 LOGFQUEUE("codec < default");
1445 } /* end switch */
1450 /* --- Audio thread --- */
1452 static bool audio_have_tracks(void)
1454 return (audio_track_count() != 0);
1457 static int audio_free_track_count(void)
1459 /* Used tracks + free tracks adds up to MAX_TRACK - 1 */
1460 return MAX_TRACK - 1 - audio_track_count();
1463 int audio_track_count(void)
1465 /* Calculate difference from track_ridx to track_widx
1466 * taking into account a possible wrap-around. */
1467 return (MAX_TRACK + track_widx - track_ridx) & MAX_TRACK_MASK;
1470 long audio_filebufused(void)
1472 return (long) buf_used();
1475 /* Update track info after successful a codec track change */
1476 static void audio_update_trackinfo(void)
1478 /* Load the curent track's metadata into curtrack_id3 */
1479 CUR_TI->taginfo_ready = (CUR_TI->id3_hid >= 0);
1480 if (CUR_TI->id3_hid >= 0)
1481 copy_mp3entry(&curtrack_id3, bufgetid3(CUR_TI->id3_hid));
1483 int next_idx = (track_ridx + 1) & MAX_TRACK_MASK;
1484 tracks[next_idx].taginfo_ready = (tracks[next_idx].id3_hid >= 0);
1486 /* Reset current position */
1487 curtrack_id3.elapsed = 0;
1488 curtrack_id3.offset = 0;
1490 /* Update the codec API */
1491 ci.filesize = CUR_TI->filesize;
1492 ci.id3 = &curtrack_id3;
1493 ci.curpos = 0;
1494 ci.taginfo_ready = &CUR_TI->taginfo_ready;
1497 static void buffering_audio_callback(enum callback_event ev, int value)
1499 (void)value;
1500 logf("buffering_audio_callback");
1502 switch (ev)
1504 case EVENT_BUFFER_LOW:
1505 if (filling == STATE_FULL) {
1506 /* force a refill */
1507 LOGFQUEUE("buffering > audio Q_AUDIO_FILL_BUFFER");
1508 queue_post(&audio_queue, Q_AUDIO_FILL_BUFFER, 0);
1510 break;
1512 case EVENT_HANDLE_REBUFFER:
1513 LOGFQUEUE("audio >| audio Q_AUDIO_FLUSH");
1514 queue_send(&audio_queue, Q_AUDIO_FLUSH, 0);
1515 break;
1517 case EVENT_HANDLE_FINISHED:
1518 logf("handle %d finished buffering", value);
1519 strip_tags(value);
1520 break;
1522 default:
1523 break;
1527 /* Clear tracks between write and read, non inclusive */
1528 static void audio_clear_track_entries(void)
1530 int cur_idx = track_widx;
1532 logf("Clearing tracks:%d/%d", track_ridx, track_widx);
1534 /* Loop over all tracks from write-to-read */
1535 while (1)
1537 cur_idx = (cur_idx + 1) & MAX_TRACK_MASK;
1539 if (cur_idx == track_ridx)
1540 break;
1542 clear_track_info(&tracks[cur_idx]);
1546 /* Clear all tracks */
1547 static bool audio_release_tracks(void)
1549 int i, cur_idx;
1551 logf("releasing all tracks");
1553 for(i = 0; i < MAX_TRACK; i++)
1555 cur_idx = (track_ridx + i) & MAX_TRACK_MASK;
1556 if (!clear_track_info(&tracks[cur_idx]))
1557 return false;
1560 return true;
1563 static bool audio_loadcodec(bool start_play)
1565 int prev_track;
1566 char codec_path[MAX_PATH]; /* Full path to codec */
1568 if (tracks[track_widx].id3_hid < 0) {
1569 return false;
1572 const char * codec_fn =
1573 get_codec_filename(bufgetid3(tracks[track_widx].id3_hid)->codectype);
1574 if (codec_fn == NULL)
1575 return false;
1577 tracks[track_widx].codec_hid = -1;
1579 if (start_play)
1581 /* Load the codec directly from disk and save some memory. */
1582 track_ridx = track_widx;
1583 ci.filesize = CUR_TI->filesize;
1584 ci.id3 = &curtrack_id3;
1585 ci.taginfo_ready = &CUR_TI->taginfo_ready;
1586 ci.curpos = 0;
1587 LOGFQUEUE("codec > codec Q_CODEC_LOAD_DISK");
1588 queue_post(&codec_queue, Q_CODEC_LOAD_DISK, (intptr_t)codec_fn);
1589 return true;
1591 else
1593 /* If we already have another track than this one buffered */
1594 if (track_widx != track_ridx)
1596 prev_track = (track_widx - 1) & MAX_TRACK_MASK;
1598 /* If the previous codec is the same as this one, there is no need
1599 * to put another copy of it on the file buffer */
1600 if (get_codec_base_type(
1601 bufgetid3(tracks[track_widx].id3_hid)->codectype) ==
1602 get_codec_base_type(
1603 bufgetid3(tracks[prev_track].id3_hid)->codectype)
1604 && audio_codec_loaded)
1606 logf("Reusing prev. codec");
1607 return true;
1612 codec_get_full_path(codec_path, codec_fn);
1614 tracks[track_widx].codec_hid = bufopen(codec_path, 0, TYPE_CODEC);
1615 if (tracks[track_widx].codec_hid < 0)
1616 return false;
1618 logf("Loaded codec");
1620 return true;
1623 /* TODO: Copied from mpeg.c. Should be moved somewhere else. */
1624 static void audio_set_elapsed(struct mp3entry* id3)
1626 unsigned long offset = id3->offset > id3->first_frame_offset ?
1627 id3->offset - id3->first_frame_offset : 0;
1629 if ( id3->vbr ) {
1630 if ( id3->has_toc ) {
1631 /* calculate elapsed time using TOC */
1632 int i;
1633 unsigned int remainder, plen, relpos, nextpos;
1635 /* find wich percent we're at */
1636 for (i=0; i<100; i++ )
1637 if ( offset < id3->toc[i] * (id3->filesize / 256) )
1638 break;
1640 i--;
1641 if (i < 0)
1642 i = 0;
1644 relpos = id3->toc[i];
1646 if (i < 99)
1647 nextpos = id3->toc[i+1];
1648 else
1649 nextpos = 256;
1651 remainder = offset - (relpos * (id3->filesize / 256));
1653 /* set time for this percent (divide before multiply to prevent
1654 overflow on long files. loss of precision is negligible on
1655 short files) */
1656 id3->elapsed = i * (id3->length / 100);
1658 /* calculate remainder time */
1659 plen = (nextpos - relpos) * (id3->filesize / 256);
1660 id3->elapsed += (((remainder * 100) / plen) *
1661 (id3->length / 10000));
1663 else {
1664 /* no TOC exists. set a rough estimate using average bitrate */
1665 int tpk = id3->length /
1666 ((id3->filesize - id3->first_frame_offset - id3->id3v1len) /
1667 1024);
1668 id3->elapsed = offset / 1024 * tpk;
1671 else
1673 /* constant bitrate, use exact calculation */
1674 if (id3->bitrate != 0)
1675 id3->elapsed = offset / (id3->bitrate / 8);
1679 /* Load one track by making the appropriate bufopen calls. Return true if
1680 everything required was loaded correctly, false if not. */
1681 static bool audio_load_track(int offset, bool start_play)
1683 const char *trackname;
1684 char msgbuf[80];
1685 int fd = -1;
1686 int file_offset = 0;
1687 struct mp3entry id3;
1689 /* Stop buffer filling if there is no free track entries.
1690 Don't fill up the last track entry (we wan't to store next track
1691 metadata there). */
1692 if (!audio_free_track_count())
1694 logf("No free tracks");
1695 return false;
1698 last_peek_offset++;
1699 tracks[track_widx].taginfo_ready = false;
1701 peek_again:
1702 logf("Buffering track:%d/%d", track_widx, track_ridx);
1703 /* Get track name from current playlist read position. */
1704 while ((trackname = playlist_peek(last_peek_offset)) != NULL)
1706 /* Handle broken playlists. */
1707 fd = open(trackname, O_RDONLY);
1708 if (fd < 0)
1710 logf("Open failed");
1711 /* Skip invalid entry from playlist. */
1712 playlist_skip_entry(NULL, last_peek_offset);
1714 else
1715 break;
1718 if (!trackname)
1720 logf("End-of-playlist");
1721 playlist_end = true;
1722 memset(&lasttrack_id3, 0, sizeof(struct mp3entry));
1723 filling = STATE_FINISHED;
1724 return false;
1727 tracks[track_widx].filesize = filesize(fd);
1729 if ((unsigned)offset > tracks[track_widx].filesize)
1730 offset = 0;
1732 /* Set default values */
1733 if (start_play)
1735 buf_set_watermark(AUDIO_DEFAULT_WATERMARK);
1736 dsp_configure(ci.dsp, DSP_RESET, 0);
1737 track_changed = true;
1738 playlist_update_resume_info(audio_current_track());
1741 /* Get track metadata if we don't already have it. */
1742 if (tracks[track_widx].id3_hid < 0)
1744 if (get_metadata(&id3, fd, trackname))
1746 send_event(PLAYBACK_EVENT_TRACK_BUFFER, &id3);
1748 tracks[track_widx].id3_hid =
1749 bufalloc(&id3, sizeof(struct mp3entry), TYPE_ID3);
1751 if (tracks[track_widx].id3_hid < 0)
1753 last_peek_offset--;
1754 close(fd);
1755 copy_mp3entry(&lasttrack_id3, &id3);
1756 goto buffer_full;
1759 if (track_widx == track_ridx)
1760 copy_mp3entry(&curtrack_id3, &id3);
1762 if (start_play)
1764 track_changed = true;
1765 playlist_update_resume_info(audio_current_track());
1768 else
1770 logf("mde:%s!",trackname);
1772 /* Skip invalid entry from playlist. */
1773 playlist_skip_entry(NULL, last_peek_offset);
1774 close(fd);
1775 goto peek_again;
1780 close(fd);
1782 #if 0
1783 if (cuesheet_is_enabled() && tracks[track_widx].id3.cuesheet_type == 1)
1785 char cuepath[MAX_PATH];
1787 struct cuesheet *cue = start_play ? curr_cue : temp_cue;
1789 if (look_for_cuesheet_file(trackname, cuepath) &&
1790 parse_cuesheet(cuepath, cue))
1792 strcpy((cue)->audio_filename, trackname);
1793 if (start_play)
1794 cue_spoof_id3(curr_cue, &tracks[track_widx].id3);
1797 #endif
1799 struct mp3entry *track_id3;
1801 if (track_widx == track_ridx)
1802 track_id3 = &curtrack_id3;
1803 else
1804 track_id3 = bufgetid3(tracks[track_widx].id3_hid);
1806 #ifdef HAVE_ALBUMART
1807 if (tracks[track_widx].aa_hid < 0 && gui_sync_wps_uses_albumart())
1809 char aa_path[MAX_PATH];
1810 if (find_albumart(track_id3, aa_path, sizeof(aa_path)))
1811 tracks[track_widx].aa_hid = bufopen(aa_path, 0, TYPE_BITMAP);
1813 #endif
1815 /* Load the codec. */
1816 if (!audio_loadcodec(start_play))
1818 if (tracks[track_widx].codec_hid == ERR_BUFFER_FULL)
1820 /* No space for codec on buffer, not an error */
1821 goto buffer_full;
1824 /* This is an error condition, either no codec was found, or reading
1825 * the codec file failed part way through, either way, skip the track */
1826 snprintf(msgbuf, sizeof(msgbuf)-1, "No codec for: %s", trackname);
1827 /* We should not use gui_syncplash from audio thread! */
1828 gui_syncsplash(HZ*2, msgbuf);
1829 /* Skip invalid entry from playlist. */
1830 playlist_skip_entry(NULL, last_peek_offset);
1831 goto peek_again;
1834 track_id3->elapsed = 0;
1836 enum data_type type = TYPE_PACKET_AUDIO;
1838 switch (track_id3->codectype) {
1839 case AFMT_MPA_L1:
1840 case AFMT_MPA_L2:
1841 case AFMT_MPA_L3:
1842 if (offset > 0) {
1843 file_offset = offset;
1844 track_id3->offset = offset;
1845 audio_set_elapsed(track_id3);
1847 break;
1849 case AFMT_WAVPACK:
1850 if (offset > 0) {
1851 file_offset = offset;
1852 track_id3->offset = offset;
1853 track_id3->elapsed = track_id3->length / 2;
1855 break;
1857 case AFMT_OGG_VORBIS:
1858 case AFMT_SPEEX:
1859 case AFMT_FLAC:
1860 case AFMT_PCM_WAV:
1861 case AFMT_A52:
1862 case AFMT_AAC:
1863 case AFMT_MPC:
1864 case AFMT_APE:
1865 if (offset > 0)
1866 track_id3->offset = offset;
1867 break;
1869 case AFMT_NSF:
1870 case AFMT_SPC:
1871 case AFMT_SID:
1872 logf("Loading atomic %d",track_id3->codectype);
1873 type = TYPE_ATOMIC_AUDIO;
1874 break;
1877 logf("alt:%s", trackname);
1879 if (file_offset > AUDIO_REBUFFER_GUESS_SIZE)
1880 file_offset -= AUDIO_REBUFFER_GUESS_SIZE;
1881 else if (track_id3->first_frame_offset)
1882 file_offset = track_id3->first_frame_offset;
1883 else
1884 file_offset = 0;
1886 tracks[track_widx].audio_hid = bufopen(trackname, file_offset, type);
1888 if (tracks[track_widx].audio_hid < 0)
1889 goto buffer_full;
1891 /* All required data is now available for the codec. */
1892 tracks[track_widx].taginfo_ready = true;
1894 if (start_play)
1896 ci.curpos=file_offset;
1897 buf_request_buffer_handle(tracks[track_widx].audio_hid);
1900 track_widx = (track_widx + 1) & MAX_TRACK_MASK;
1902 return true;
1904 buffer_full:
1905 logf("buffer is full for now");
1906 filling = STATE_FULL;
1907 return false;
1910 static void audio_fill_file_buffer(bool start_play, size_t offset)
1912 struct queue_event ev;
1913 bool had_next_track = audio_next_track() != NULL;
1914 bool continue_buffering;
1916 filling = STATE_FILLING;
1918 /* No need to rebuffer if there are track skips pending. */
1919 if (ci.new_track != 0)
1920 return;
1922 /* Must reset the buffer before use if trashed or voice only - voice
1923 file size shouldn't have changed so we can go straight from
1924 BUFFER_STATE_VOICED_ONLY to BUFFER_STATE_INITIALIZED */
1925 if (buffer_state != BUFFER_STATE_INITIALIZED)
1926 audio_reset_buffer();
1928 logf("Starting buffer fill");
1930 if (!start_play)
1931 audio_clear_track_entries();
1933 /* Save the current resume position once. */
1934 playlist_update_resume_info(audio_current_track());
1936 continue_buffering = audio_load_track(offset, start_play);
1937 do {
1938 sleep(1);
1939 if (queue_peek(&audio_queue, &ev))
1940 /* There's a message in the queue. break the loop to treat it */
1941 break;
1942 continue_buffering = audio_load_track(0, false);
1943 } while (continue_buffering);
1945 if (!had_next_track && audio_next_track())
1946 track_changed = true;
1950 static void audio_rebuffer(void)
1952 logf("Forcing rebuffer");
1954 clear_track_info(CUR_TI);
1956 /* Reset track pointers */
1957 track_widx = track_ridx;
1958 audio_clear_track_entries();
1960 /* Fill the buffer */
1961 last_peek_offset = -1;
1962 ci.curpos = 0;
1964 if (!CUR_TI->taginfo_ready)
1965 memset(&curtrack_id3, 0, sizeof(struct mp3entry));
1967 audio_fill_file_buffer(false, 0);
1970 /* Called on request from the codec to get a new track. This is the codec part
1971 of the track transition. */
1972 static int audio_check_new_track(void)
1974 int track_count = audio_track_count();
1975 int old_track_ridx = track_ridx;
1976 int i, idx;
1977 int next_playlist_index;
1978 bool forward;
1979 bool end_of_playlist; /* Temporary flag, not the same as playlist_end */
1981 /* Now it's good time to send track unbuffer events. */
1982 send_event(PLAYBACK_EVENT_TRACK_FINISH, &curtrack_id3);
1984 if (dir_skip)
1986 dir_skip = false;
1987 if (playlist_next_dir(ci.new_track))
1989 ci.new_track = 0;
1990 audio_rebuffer();
1991 goto skip_done;
1993 else
1995 LOGFQUEUE("audio >|= codec Q_CODEC_REQUEST_FAILED");
1996 return Q_CODEC_REQUEST_FAILED;
2000 if (new_playlist)
2001 ci.new_track = 0;
2003 end_of_playlist = playlist_peek(automatic_skip ? ci.new_track : 0) == NULL;
2004 auto_dir_skip = end_of_playlist && global_settings.next_folder;
2006 /* If the playlist isn't that big */
2007 if (automatic_skip && !playlist_check(ci.new_track))
2009 if (ci.new_track >= 0)
2011 LOGFQUEUE("audio >|= codec Q_CODEC_REQUEST_FAILED");
2012 return Q_CODEC_REQUEST_FAILED;
2014 /* Find the beginning backward if the user over-skips it */
2015 while (!playlist_check(++ci.new_track))
2016 if (ci.new_track >= 0)
2018 LOGFQUEUE("audio >|= codec Q_CODEC_REQUEST_FAILED");
2019 return Q_CODEC_REQUEST_FAILED;
2023 /* Update the playlist */
2024 last_peek_offset -= ci.new_track;
2026 if (auto_dir_skip)
2028 /* If the track change was the result of an auto dir skip,
2029 we need to update the playlist now */
2030 next_playlist_index = playlist_next(ci.new_track);
2032 if (next_playlist_index < 0)
2034 LOGFQUEUE("audio >|= codec Q_CODEC_REQUEST_FAILED");
2035 return Q_CODEC_REQUEST_FAILED;
2039 if (new_playlist)
2041 ci.new_track = 1;
2042 new_playlist = false;
2045 /* Save the track metadata to allow the WPS to display it
2046 while PCM finishes playing that track */
2047 copy_mp3entry(&prevtrack_id3, &curtrack_id3);
2049 /* Update the main buffer copy of the track metadata with the one
2050 the codec has been using (for the unbuffer callbacks) */
2051 if (CUR_TI->id3_hid >= 0)
2052 copy_mp3entry(bufgetid3(CUR_TI->id3_hid), &curtrack_id3);
2054 /* Save a pointer to the old track to allow later clearing */
2055 prev_ti = CUR_TI;
2057 for (i = 0; i < ci.new_track; i++)
2059 idx = (track_ridx + i) & MAX_TRACK_MASK;
2060 struct mp3entry *id3 = bufgetid3(tracks[idx].id3_hid);
2061 ssize_t offset = buf_handle_offset(tracks[idx].audio_hid);
2062 if (!id3 || offset < 0 || (unsigned)offset > id3->first_frame_offset)
2064 /* We don't have all the audio data for that track, so clear it,
2065 but keep the metadata. */
2066 if (tracks[idx].audio_hid >= 0 && bufclose(tracks[idx].audio_hid))
2068 tracks[idx].audio_hid = -1;
2069 tracks[idx].filesize = 0;
2074 /* Move to the new track */
2075 track_ridx = (track_ridx + ci.new_track) & MAX_TRACK_MASK;
2077 buf_set_base_handle(CUR_TI->audio_hid);
2079 if (automatic_skip)
2081 playlist_end = false;
2082 wps_offset = -ci.new_track;
2083 track_changed = true;
2086 /* If it is not safe to even skip this many track entries */
2087 if (ci.new_track >= track_count || ci.new_track <= track_count - MAX_TRACK)
2089 ci.new_track = 0;
2090 audio_rebuffer();
2091 goto skip_done;
2094 forward = ci.new_track > 0;
2095 ci.new_track = 0;
2097 /* If the target track is clearly not in memory */
2098 if (CUR_TI->filesize == 0 || !CUR_TI->taginfo_ready)
2100 audio_rebuffer();
2101 goto skip_done;
2104 /* When skipping backwards, it is possible that we've found a track that's
2105 * buffered, but which is around the track-wrap and therefor not the track
2106 * we are looking for */
2107 if (!forward)
2109 int cur_idx = track_ridx;
2110 bool taginfo_ready = true;
2111 /* We've wrapped the buffer backwards if new > old */
2112 bool wrap = track_ridx > old_track_ridx;
2114 while (1)
2116 cur_idx = (cur_idx + 1) & MAX_TRACK_MASK;
2118 /* if we've advanced past the wrap when cur_idx is zeroed */
2119 if (!cur_idx)
2120 wrap = false;
2122 /* if we aren't still on the wrap and we've caught the old track */
2123 if (!(wrap || cur_idx < old_track_ridx))
2124 break;
2126 /* If we hit a track in between without valid tag info, bail */
2127 if (!tracks[cur_idx].taginfo_ready)
2129 taginfo_ready = false;
2130 break;
2133 if (!taginfo_ready)
2135 audio_rebuffer();
2139 skip_done:
2140 audio_update_trackinfo();
2141 LOGFQUEUE("audio >|= codec Q_CODEC_REQUEST_COMPLETE");
2142 return Q_CODEC_REQUEST_COMPLETE;
2145 unsigned long audio_prev_elapsed(void)
2147 return prev_track_elapsed;
2150 static void audio_stop_codec_flush(void)
2152 ci.stop_codec = true;
2153 pcmbuf_pause(true);
2155 while (audio_codec_loaded)
2156 yield();
2158 /* If the audio codec is not loaded any more, and the audio is still
2159 * playing, it is now and _only_ now safe to call this function from the
2160 * audio thread */
2161 if (pcm_is_playing())
2163 pcmbuf_play_stop();
2164 pcmbuf_queue_clear();
2166 pcmbuf_pause(paused);
2169 static void audio_stop_playback(void)
2171 /* If we were playing, save resume information */
2172 if (playing)
2174 struct mp3entry *id3 = NULL;
2176 if (!playlist_end || !ci.stop_codec)
2178 /* Set this early, the outside code yields and may allow the codec
2179 to try to wait for a reply on a buffer wait */
2180 ci.stop_codec = true;
2181 id3 = audio_current_track();
2184 /* Save the current playing spot, or NULL if the playlist has ended */
2185 playlist_update_resume_info(id3);
2187 /* TODO: Create auto bookmark too? */
2189 prev_track_elapsed = curtrack_id3.elapsed;
2192 paused = false;
2193 audio_stop_codec_flush();
2194 playing = false;
2196 filling = STATE_IDLE;
2198 /* Mark all entries null. */
2199 audio_clear_track_entries();
2201 /* Close all tracks */
2202 audio_release_tracks();
2204 unregister_buffering_callback(buffering_audio_callback);
2206 memset(&curtrack_id3, 0, sizeof(struct mp3entry));
2209 static void audio_play_start(size_t offset)
2211 int i;
2213 #if INPUT_SRC_CAPS != 0
2214 audio_set_input_source(AUDIO_SRC_PLAYBACK, SRCF_PLAYBACK);
2215 audio_set_output_source(AUDIO_SRC_PLAYBACK);
2216 #endif
2218 /* Wait for any previously playing audio to flush - TODO: Not necessary? */
2219 paused = false;
2220 audio_stop_codec_flush();
2222 track_changed = true;
2223 playlist_end = false;
2225 playing = true;
2227 ci.new_track = 0;
2228 ci.seek_time = 0;
2229 wps_offset = 0;
2231 sound_set_volume(global_settings.volume);
2232 track_widx = track_ridx = 0;
2234 /* Clear all track entries. */
2235 for (i = 0; i < MAX_TRACK; i++) {
2236 clear_track_info(&tracks[i]);
2239 last_peek_offset = -1;
2241 /* Officially playing */
2242 queue_reply(&audio_queue, 1);
2244 #ifndef HAVE_FLASH_STORAGE
2245 set_filebuf_watermark(buffer_margin, 0);
2246 #endif
2248 audio_fill_file_buffer(true, offset);
2249 register_buffering_callback(buffering_audio_callback);
2251 LOGFQUEUE("audio > audio Q_AUDIO_TRACK_CHANGED");
2252 queue_post(&audio_queue, Q_AUDIO_TRACK_CHANGED, 0);
2256 /* Invalidates all but currently playing track. */
2257 static void audio_invalidate_tracks(void)
2259 if (audio_have_tracks())
2261 last_peek_offset = 0;
2262 playlist_end = false;
2263 track_widx = track_ridx;
2265 /* Mark all other entries null (also buffered wrong metadata). */
2266 audio_clear_track_entries();
2268 track_widx = (track_widx + 1) & MAX_TRACK_MASK;
2270 audio_fill_file_buffer(false, 0);
2274 static void audio_new_playlist(void)
2276 /* Prepare to start a new fill from the beginning of the playlist */
2277 last_peek_offset = -1;
2278 if (audio_have_tracks())
2280 if (paused)
2281 skipped_during_pause = true;
2282 playlist_end = false;
2283 track_widx = track_ridx;
2284 audio_clear_track_entries();
2286 track_widx = (track_widx + 1) & MAX_TRACK_MASK;
2288 /* Mark the current track as invalid to prevent skipping back to it */
2289 CUR_TI->taginfo_ready = false;
2292 /* Signal the codec to initiate a track change forward */
2293 new_playlist = true;
2294 ci.new_track = 1;
2296 /* Officially playing */
2297 queue_reply(&audio_queue, 1);
2299 audio_fill_file_buffer(false, 0);
2302 /* Called on manual track skip */
2303 static void audio_initiate_track_change(long direction)
2305 logf("audio_initiate_track_change(%ld)", direction);
2307 playlist_end = false;
2308 ci.new_track += direction;
2309 wps_offset -= direction;
2310 if (paused)
2311 skipped_during_pause = true;
2314 /* Called on manual dir skip */
2315 static void audio_initiate_dir_change(long direction)
2317 playlist_end = false;
2318 dir_skip = true;
2319 ci.new_track = direction;
2320 if (paused)
2321 skipped_during_pause = true;
2324 /* Called when PCM track change is complete */
2325 static void audio_finalise_track_change(void)
2327 logf("audio_finalise_track_change");
2329 if (automatic_skip)
2331 if (!auto_dir_skip)
2332 playlist_next(-wps_offset);
2334 wps_offset = 0;
2335 automatic_skip = false;
2338 auto_dir_skip = false;
2340 /* Invalidate prevtrack_id3 */
2341 prevtrack_id3.path[0] = 0;
2343 if (prev_ti && prev_ti->audio_hid < 0)
2345 /* No audio left so we clear all the track info. */
2346 clear_track_info(prev_ti);
2349 if (prev_ti && prev_ti->id3_hid >= 0)
2351 /* Reset the elapsed time to force the progressbar to be empty if
2352 the user skips back to this track */
2353 bufgetid3(prev_ti->id3_hid)->elapsed = 0;
2356 send_event(PLAYBACK_EVENT_TRACK_CHANGE, &curtrack_id3);
2358 track_changed = true;
2359 playlist_update_resume_info(audio_current_track());
2363 * Layout audio buffer as follows - iram buffer depends on target:
2364 * [|SWAP:iram][|TALK]|MALLOC|FILE|GUARD|PCM|[SWAP:dram[|iram]|]
2366 static void audio_reset_buffer(void)
2368 /* see audio_get_recording_buffer if this is modified */
2369 logf("audio_reset_buffer");
2371 /* If the setup of anything allocated before the file buffer is
2372 changed, do check the adjustments after the buffer_alloc call
2373 as it will likely be affected and need sliding over */
2375 /* Initially set up file buffer as all space available */
2376 malloc_buf = audiobuf + talk_get_bufsize();
2377 /* Align the malloc buf to line size. Especially important to cf
2378 targets that do line reads/writes. */
2379 malloc_buf = (unsigned char *)(((uintptr_t)malloc_buf + 15) & ~15);
2380 filebuf = malloc_buf + MALLOC_BUFSIZE; /* filebuf line align implied */
2381 filebuflen = audiobufend - filebuf;
2383 filebuflen &= ~15;
2385 /* Subtract whatever the pcm buffer says it used plus the guard buffer */
2386 filebuflen -= pcmbuf_init(filebuf + filebuflen) + GUARD_BUFSIZE;
2388 /* Make sure filebuflen is a longword multiple after adjustment - filebuf
2389 will already be line aligned */
2390 filebuflen &= ~3;
2392 buffering_reset(filebuf, filebuflen);
2394 /* Clear any references to the file buffer */
2395 buffer_state = BUFFER_STATE_INITIALIZED;
2397 #if defined(ROCKBOX_HAS_LOGF) && defined(LOGF_ENABLE)
2398 /* Make sure everything adds up - yes, some info is a bit redundant but
2399 aids viewing and the sumation of certain variables should add up to
2400 the location of others. */
2402 size_t pcmbufsize;
2403 const unsigned char *pcmbuf = pcmbuf_get_meminfo(&pcmbufsize);
2404 logf("mabuf: %08X", (unsigned)malloc_buf);
2405 logf("mabufe: %08X", (unsigned)(malloc_buf + MALLOC_BUFSIZE));
2406 logf("fbuf: %08X", (unsigned)filebuf);
2407 logf("fbufe: %08X", (unsigned)(filebuf + filebuflen));
2408 logf("gbuf: %08X", (unsigned)(filebuf + filebuflen));
2409 logf("gbufe: %08X", (unsigned)(filebuf + filebuflen + GUARD_BUFSIZE));
2410 logf("pcmb: %08X", (unsigned)pcmbuf);
2411 logf("pcmbe: %08X", (unsigned)(pcmbuf + pcmbufsize));
2413 #endif
2416 static void audio_thread(void)
2418 struct queue_event ev;
2420 pcm_postinit();
2422 audio_thread_ready = true;
2424 while (1)
2426 cancel_cpu_boost();
2427 if (!pcmbuf_queue_scan(&ev))
2428 queue_wait_w_tmo(&audio_queue, &ev, HZ/2);
2430 switch (ev.id) {
2432 case Q_AUDIO_FILL_BUFFER:
2433 LOGFQUEUE("audio < Q_AUDIO_FILL_BUFFER");
2434 audio_fill_file_buffer(false, 0);
2435 break;
2437 case Q_AUDIO_PLAY:
2438 LOGFQUEUE("audio < Q_AUDIO_PLAY");
2439 if (playing && ev.data <= 0)
2440 audio_new_playlist();
2441 else
2443 audio_stop_playback();
2444 audio_play_start((size_t)ev.data);
2446 break;
2448 case Q_AUDIO_STOP:
2449 LOGFQUEUE("audio < Q_AUDIO_STOP");
2450 if (playing)
2451 audio_stop_playback();
2452 if (ev.data != 0)
2453 queue_clear(&audio_queue);
2454 break;
2456 case Q_AUDIO_PAUSE:
2457 LOGFQUEUE("audio < Q_AUDIO_PAUSE");
2458 if (!(bool) ev.data && skipped_during_pause && !pcmbuf_is_crossfade_active())
2459 pcmbuf_play_stop(); /* Flush old track on resume after skip */
2460 skipped_during_pause = false;
2461 if (!playing)
2462 break;
2463 pcmbuf_pause((bool)ev.data);
2464 paused = (bool)ev.data;
2465 break;
2467 case Q_AUDIO_SKIP:
2468 LOGFQUEUE("audio < Q_AUDIO_SKIP");
2469 audio_initiate_track_change((long)ev.data);
2470 break;
2472 case Q_AUDIO_PRE_FF_REWIND:
2473 LOGFQUEUE("audio < Q_AUDIO_PRE_FF_REWIND");
2474 if (!playing)
2475 break;
2476 pcmbuf_pause(true);
2477 break;
2479 case Q_AUDIO_FF_REWIND:
2480 LOGFQUEUE("audio < Q_AUDIO_FF_REWIND");
2481 if (!playing)
2482 break;
2483 if (automatic_skip)
2485 /* An automatic track skip is in progress. Finalize it,
2486 then go back to the previous track */
2487 audio_finalise_track_change();
2488 ci.new_track = -1;
2490 ci.seek_time = (long)ev.data+1;
2491 break;
2493 case Q_AUDIO_CHECK_NEW_TRACK:
2494 LOGFQUEUE("audio < Q_AUDIO_CHECK_NEW_TRACK");
2495 queue_reply(&audio_queue, audio_check_new_track());
2496 break;
2498 case Q_AUDIO_DIR_SKIP:
2499 LOGFQUEUE("audio < Q_AUDIO_DIR_SKIP");
2500 playlist_end = false;
2501 audio_initiate_dir_change(ev.data);
2502 break;
2504 case Q_AUDIO_FLUSH:
2505 LOGFQUEUE("audio < Q_AUDIO_FLUSH");
2506 audio_invalidate_tracks();
2507 break;
2509 case Q_AUDIO_TRACK_CHANGED:
2510 /* PCM track change done */
2511 LOGFQUEUE("audio < Q_AUDIO_TRACK_CHANGED");
2512 audio_finalise_track_change();
2513 break;
2515 #ifndef SIMULATOR
2516 case SYS_USB_CONNECTED:
2517 LOGFQUEUE("audio < SYS_USB_CONNECTED");
2518 if (playing)
2519 audio_stop_playback();
2520 #ifdef PLAYBACK_VOICE
2521 voice_stop();
2522 #endif
2523 usb_acknowledge(SYS_USB_CONNECTED_ACK);
2524 usb_wait_for_disconnect(&audio_queue);
2526 /* Mark all entries null. */
2527 audio_clear_track_entries();
2529 /* release tracks to make sure all handles are closed */
2530 audio_release_tracks();
2531 break;
2532 #endif
2534 case SYS_TIMEOUT:
2535 LOGFQUEUE_SYS_TIMEOUT("audio < SYS_TIMEOUT");
2536 if (filling == STATE_FILLING)
2537 audio_fill_file_buffer(false, 0);
2538 break;
2540 default:
2541 LOGFQUEUE("audio < default");
2542 break;
2543 } /* end switch */
2544 } /* end while */
2547 /* Initialize the audio system - called from init() in main.c.
2548 * Last function because of all the references to internal symbols
2550 void audio_init(void)
2552 struct thread_entry *audio_thread_p;
2554 /* Can never do this twice */
2555 if (audio_is_initialized)
2557 logf("audio: already initialized");
2558 return;
2561 logf("audio: initializing");
2563 /* Initialize queues before giving control elsewhere in case it likes
2564 to send messages. Thread creation will be delayed however so nothing
2565 starts running until ready if something yields such as talk_init. */
2566 queue_init(&audio_queue, true);
2567 queue_init(&codec_queue, false);
2568 queue_init(&pcmbuf_queue, false);
2570 pcm_init();
2572 /* Initialize codec api. */
2573 ci.read_filebuf = codec_filebuf_callback;
2574 ci.pcmbuf_insert = codec_pcmbuf_insert_callback;
2575 ci.get_codec_memory = codec_get_memory_callback;
2576 ci.request_buffer = codec_request_buffer_callback;
2577 ci.advance_buffer = codec_advance_buffer_callback;
2578 ci.advance_buffer_loc = codec_advance_buffer_loc_callback;
2579 ci.request_next_track = codec_request_next_track_callback;
2580 ci.mp3_get_filepos = codec_mp3_get_filepos_callback;
2581 ci.seek_buffer = codec_seek_buffer_callback;
2582 ci.seek_complete = codec_seek_complete_callback;
2583 ci.set_elapsed = codec_set_elapsed_callback;
2584 ci.set_offset = codec_set_offset_callback;
2585 ci.configure = codec_configure_callback;
2586 ci.discard_codec = codec_discard_codec_callback;
2587 ci.dsp = (struct dsp_config *)dsp_configure(NULL, DSP_MYDSP,
2588 CODEC_IDX_AUDIO);
2590 /* initialize the buffer */
2591 filebuf = audiobuf;
2593 /* audio_reset_buffer must to know the size of voice buffer so init
2594 talk first */
2595 talk_init();
2597 codec_thread_p = create_thread(
2598 codec_thread, codec_stack, sizeof(codec_stack),
2599 CREATE_THREAD_FROZEN,
2600 codec_thread_name IF_PRIO(, PRIORITY_PLAYBACK)
2601 IF_COP(, CPU));
2603 queue_enable_queue_send(&codec_queue, &codec_queue_sender_list,
2604 codec_thread_p);
2606 audio_thread_p = create_thread(audio_thread, audio_stack,
2607 sizeof(audio_stack), CREATE_THREAD_FROZEN,
2608 audio_thread_name IF_PRIO(, PRIORITY_USER_INTERFACE)
2609 IF_COP(, CPU));
2611 queue_enable_queue_send(&audio_queue, &audio_queue_sender_list,
2612 audio_thread_p);
2614 #ifdef PLAYBACK_VOICE
2615 voice_thread_init();
2616 #endif
2618 /* Set crossfade setting for next buffer init which should be about... */
2619 pcmbuf_crossfade_enable(global_settings.crossfade);
2621 /* initialize the buffering system */
2623 buffering_init();
2624 /* ...now! Set up the buffers */
2625 audio_reset_buffer();
2627 int i;
2628 for(i = 0; i < MAX_TRACK; i++)
2630 tracks[i].audio_hid = -1;
2631 tracks[i].id3_hid = -1;
2632 tracks[i].codec_hid = -1;
2633 #ifdef HAVE_ALBUMART
2634 tracks[i].aa_hid = -1;
2635 #endif
2638 /* Probably safe to say */
2639 audio_is_initialized = true;
2641 sound_settings_apply();
2642 #ifndef HAVE_FLASH_STORAGE
2643 audio_set_buffer_margin(global_settings.buffer_margin);
2644 #endif
2646 /* it's safe to let the threads run now */
2647 #ifdef PLAYBACK_VOICE
2648 voice_thread_resume();
2649 #endif
2650 thread_thaw(codec_thread_p);
2651 thread_thaw(audio_thread_p);
2653 } /* audio_init */
2655 void audio_wait_for_init(void)
2657 /* audio thread will only set this once after it finished the final
2658 * audio hardware init so this little construct is safe - even
2659 * cross-core. */
2660 while (!audio_thread_ready)
2662 sleep(0);