Video plugin: Fix OSD for font_height != 8. Don't fiddle with the framebuffer directl...
[kugel-rb.git] / apps / playback.c
blobec4f4197a407adeeb92fbe2d961fd22a54d8a24f
1 /***************************************************************************
2 * __________ __ ___.
3 * Open \______ \ ____ ____ | | _\_ |__ _______ ___
4 * Source | _// _ \_/ ___\| |/ /| __ \ / _ \ \/ /
5 * Jukebox | | ( <_> ) \___| < | \_\ ( <_> > < <
6 * Firmware |____|_ /\____/ \___ >__|_ \|___ /\____/__/\_ \
7 * \/ \/ \/ \/ \/
8 * $Id$
10 * Copyright (C) 2005-2007 Miika Pekkarinen
11 * Copyright (C) 2007-2008 Nicolas Pennequin
13 * This program is free software; you can redistribute it and/or
14 * modify it under the terms of the GNU General Public License
15 * as published by the Free Software Foundation; either version 2
16 * of the License, or (at your option) any later version.
18 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
19 * KIND, either express or implied.
21 ****************************************************************************/
23 /* TODO: Pause should be handled in here, rather than PCMBUF so that voice can
24 * play whilst audio is paused */
26 #include <stdio.h>
27 #include <string.h>
28 #include <stdlib.h>
29 #include <ctype.h>
31 #include "system.h"
32 #include "thread.h"
33 #include "file.h"
34 #include "panic.h"
35 #include "memory.h"
36 #include "lcd.h"
37 #include "font.h"
38 #include "button.h"
39 #include "kernel.h"
40 #include "tree.h"
41 #include "debug.h"
42 #include "sprintf.h"
43 #include "settings.h"
44 #include "codecs.h"
45 #include "audio.h"
46 #include "buffering.h"
47 #include "appevents.h"
48 #include "voice_thread.h"
49 #include "mp3_playback.h"
50 #include "usb.h"
51 #include "status.h"
52 #include "storage.h"
53 #include "screens.h"
54 #include "playlist.h"
55 #include "playback.h"
56 #include "pcmbuf.h"
57 #include "buffer.h"
58 #include "dsp.h"
59 #include "abrepeat.h"
60 #include "cuesheet.h"
61 #ifdef HAVE_TAGCACHE
62 #include "tagcache.h"
63 #endif
64 #ifdef HAVE_LCD_BITMAP
65 #include "icons.h"
66 #include "peakmeter.h"
67 #include "action.h"
68 #include "albumart.h"
69 #endif
70 #include "lang.h"
71 #include "bookmark.h"
72 #include "misc.h"
73 #include "sound.h"
74 #include "metadata.h"
75 #include "splash.h"
76 #include "talk.h"
77 #include "ata_idle_notify.h"
79 #ifdef HAVE_RECORDING
80 #include "recording.h"
81 #include "talk.h"
82 #include "pcm_record.h"
83 #endif
85 #define PLAYBACK_VOICE
87 /* default point to start buffer refill */
88 #define AUDIO_DEFAULT_WATERMARK (1024*512)
89 /* amount of guess-space to allow for codecs that must hunt and peck
90 * for their correct seeek target, 32k seems a good size */
91 #define AUDIO_REBUFFER_GUESS_SIZE (1024*32)
93 /* Define LOGF_ENABLE to enable logf output in this file */
94 /*#define LOGF_ENABLE*/
95 #include "logf.h"
97 /* macros to enable logf for queues
98 logging on SYS_TIMEOUT can be disabled */
99 #ifdef SIMULATOR
100 /* Define this for logf output of all queuing except SYS_TIMEOUT */
101 #define PLAYBACK_LOGQUEUES
102 /* Define this to logf SYS_TIMEOUT messages */
103 /*#define PLAYBACK_LOGQUEUES_SYS_TIMEOUT*/
104 #endif
106 #ifdef PLAYBACK_LOGQUEUES
107 #define LOGFQUEUE logf
108 #else
109 #define LOGFQUEUE(...)
110 #endif
112 #ifdef PLAYBACK_LOGQUEUES_SYS_TIMEOUT
113 #define LOGFQUEUE_SYS_TIMEOUT logf
114 #else
115 #define LOGFQUEUE_SYS_TIMEOUT(...)
116 #endif
119 /* Define one constant that includes recording related functionality */
120 #if defined(HAVE_RECORDING) && !defined(SIMULATOR)
121 #define AUDIO_HAVE_RECORDING
122 #endif
124 enum {
125 Q_NULL = 0,
126 Q_AUDIO_PLAY = 1,
127 Q_AUDIO_STOP,
128 Q_AUDIO_PAUSE,
129 Q_AUDIO_SKIP,
130 Q_AUDIO_PRE_FF_REWIND,
131 Q_AUDIO_FF_REWIND,
132 Q_AUDIO_CHECK_NEW_TRACK,
133 Q_AUDIO_FLUSH,
134 Q_AUDIO_TRACK_CHANGED,
135 Q_AUDIO_DIR_SKIP,
136 Q_AUDIO_POSTINIT,
137 Q_AUDIO_FILL_BUFFER,
138 Q_AUDIO_FINISH_LOAD,
139 Q_CODEC_REQUEST_COMPLETE,
140 Q_CODEC_REQUEST_FAILED,
142 Q_CODEC_LOAD,
143 Q_CODEC_LOAD_DISK,
145 #ifdef AUDIO_HAVE_RECORDING
146 Q_ENCODER_LOAD_DISK,
147 Q_ENCODER_RECORD,
148 #endif
151 enum filling_state {
152 STATE_IDLE, /* audio is stopped: nothing to do */
153 STATE_FILLING, /* adding tracks to the buffer */
154 STATE_FULL, /* can't add any more tracks */
155 STATE_END_OF_PLAYLIST, /* all remaining tracks have been added */
156 STATE_FINISHED, /* all remaining tracks are fully buffered */
159 #if MEM > 1
160 #define MAX_TRACK 128
161 #else
162 #define MAX_TRACK 32
163 #endif
165 #define MAX_TRACK_MASK (MAX_TRACK-1)
167 /* As defined in plugins/lib/xxx2wav.h */
168 #if MEM > 1
169 #define GUARD_BUFSIZE (32*1024)
170 #else
171 #define GUARD_BUFSIZE (8*1024)
172 #endif
174 /* As defined in plugin.lds */
175 #if defined(CPU_PP)
176 #define CODEC_IRAM_ORIGIN ((unsigned char *)0x4000c000)
177 #define CODEC_IRAM_SIZE ((size_t)0xc000)
178 #elif defined(IAUDIO_X5) || defined(IAUDIO_M5)
179 #define CODEC_IRAM_ORIGIN ((unsigned char *)0x10010000)
180 #define CODEC_IRAM_SIZE ((size_t)0x10000)
181 #else
182 #define CODEC_IRAM_ORIGIN ((unsigned char *)0x1000c000)
183 #define CODEC_IRAM_SIZE ((size_t)0xc000)
184 #endif
186 bool audio_is_initialized = false;
187 static bool audio_thread_ready SHAREDBSS_ATTR = false;
189 /* Variables are commented with the threads that use them: *
190 * A=audio, C=codec, V=voice. A suffix of - indicates that *
191 * the variable is read but not updated on that thread. */
192 /* TBD: Split out "audio" and "playback" (ie. calling) threads */
194 /* Main state control */
195 static volatile bool audio_codec_loaded SHAREDBSS_ATTR = false; /* Codec loaded? (C/A-) */
196 static volatile bool playing SHAREDBSS_ATTR = false; /* Is audio playing? (A) */
197 static volatile bool paused SHAREDBSS_ATTR = false; /* Is audio paused? (A/C-) */
199 /* Ring buffer where compressed audio and codecs are loaded */
200 static unsigned char *filebuf = NULL; /* Start of buffer (A/C-) */
201 static unsigned char *malloc_buf = NULL; /* Start of malloc buffer (A/C-) */
202 /* FIXME: make filebuflen static */
203 size_t filebuflen = 0; /* Size of buffer (A/C-) */
204 /* FIXME: make buf_ridx (C/A-) */
206 /* Possible arrangements of the buffer */
207 #define BUFFER_STATE_TRASHED -1 /* trashed; must be reset */
208 #define BUFFER_STATE_INITIALIZED 0 /* voice+audio OR audio-only */
209 #define BUFFER_STATE_VOICED_ONLY 1 /* voice-only */
210 static int buffer_state = BUFFER_STATE_TRASHED; /* Buffer state */
212 /* Used to keep the WPS up-to-date during track transtition */
213 static struct mp3entry prevtrack_id3;
215 /* Used to provide the codec with a pointer */
216 static struct mp3entry curtrack_id3;
218 /* Used to make next track info available while playing last track on buffer */
219 static struct mp3entry lasttrack_id3;
221 /* Track info structure about songs in the file buffer (A/C-) */
222 struct track_info {
223 int audio_hid; /* The ID for the track's buffer handle */
224 int id3_hid; /* The ID for the track's metadata handle */
225 int codec_hid; /* The ID for the track's codec handle */
226 #ifdef HAVE_ALBUMART
227 int aa_hid; /* The ID for the track's album art handle */
228 #endif
230 size_t filesize; /* File total length */
232 bool taginfo_ready; /* Is metadata read */
235 static struct track_info tracks[MAX_TRACK];
236 static volatile int track_ridx = 0; /* Track being decoded (A/C-) */
237 static int track_widx = 0; /* Track being buffered (A) */
239 #define CUR_TI (&tracks[track_ridx]) /* Playing track info pointer (A/C-) */
240 static struct track_info *prev_ti = NULL; /* Pointer to the previously played
241 track */
243 /* Set by the audio thread when the current track information has updated
244 * and the WPS may need to update its cached information */
245 static bool track_changed = false;
247 /* Information used only for filling the buffer */
248 /* Playlist steps from playing track to next track to be buffered (A) */
249 static int last_peek_offset = 0;
251 /* Scrobbler support */
252 static unsigned long prev_track_elapsed = 0; /* Previous track elapsed time (C/A-)*/
254 static enum filling_state filling;
256 /* Track change controls */
257 static bool automatic_skip = false; /* Who initiated in-progress skip? (C/A-) */
258 static bool dir_skip = false; /* Is a directory skip pending? (A) */
259 static bool new_playlist = false; /* Are we starting a new playlist? (A) */
260 static int wps_offset = 0; /* Pending track change offset, to keep WPS responsive (A) */
261 static bool skipped_during_pause = false; /* Do we need to clear the PCM buffer when playback resumes (A) */
263 static bool start_play_g = false; /* Used by audio_load_track to notify
264 audio_finish_load_track about start_play */
266 /* True when a track load is in progress, i.e. audio_load_track() has returned
267 * but audio_finish_load_track() hasn't been called yet. Used to avoid allowing
268 * audio_load_track() to get called twice in a row, which would cause problems.
270 static bool track_load_started = false;
272 /* Set to true if the codec thread should send an audio stop request
273 * (typically because the end of the playlist has been reached).
275 static bool codec_requested_stop = false;
277 static size_t buffer_margin = 0; /* Buffer margin aka anti-skip buffer (A/C-) */
279 /* Multiple threads */
280 /* Set the watermark to trigger buffer fill (A/C) FIXME */
281 static void set_filebuf_watermark(int seconds, size_t max);
283 /* Audio thread */
284 static struct event_queue audio_queue SHAREDBSS_ATTR;
285 static struct queue_sender_list audio_queue_sender_list SHAREDBSS_ATTR;
286 static long audio_stack[(DEFAULT_STACK_SIZE + 0x1000)/sizeof(long)];
287 static const char audio_thread_name[] = "audio";
289 static void audio_thread(void);
290 static void audio_initiate_track_change(long direction);
291 static bool audio_have_tracks(void);
292 static void audio_reset_buffer(void);
293 static void audio_stop_playback(void);
295 /* Codec thread */
296 extern struct codec_api ci;
297 static struct event_queue codec_queue SHAREDBSS_ATTR;
298 static struct queue_sender_list codec_queue_sender_list;
299 static long codec_stack[(DEFAULT_STACK_SIZE + 0x2000)/sizeof(long)]
300 IBSS_ATTR;
301 static const char codec_thread_name[] = "codec";
302 struct thread_entry *codec_thread_p; /* For modifying thread priority later. */
304 /* PCM buffer messaging */
305 static struct event_queue pcmbuf_queue SHAREDBSS_ATTR;
307 /* Function to be called by pcm buffer callbacks.
308 * Permissible Context(s): Audio interrupt
310 static void pcmbuf_callback_queue_post(long id, intptr_t data)
312 /* No lock since we're already in audio interrupt context */
313 queue_post(&pcmbuf_queue, id, data);
316 /* Scan the pcmbuf queue and return true if a message pulled.
317 * Permissible Context(s): Thread
319 static bool pcmbuf_queue_scan(struct queue_event *ev)
321 if (!queue_empty(&pcmbuf_queue))
323 /* Transfer message to audio queue */
324 pcm_play_lock();
325 /* Pull message - never, ever any blocking call! */
326 queue_wait_w_tmo(&pcmbuf_queue, ev, 0);
327 pcm_play_unlock();
328 return true;
331 return false;
334 /* Clear the pcmbuf queue of messages
335 * Permissible Context(s): Thread
337 static void pcmbuf_queue_clear(void)
339 pcm_play_lock();
340 queue_clear(&pcmbuf_queue);
341 pcm_play_unlock();
344 /* --- Helper functions --- */
346 static struct mp3entry *bufgetid3(int handle_id)
348 if (handle_id < 0)
349 return NULL;
351 struct mp3entry *id3;
352 ssize_t ret = bufgetdata(handle_id, 0, (void *)&id3);
354 if (ret < 0 || ret != sizeof(struct mp3entry))
355 return NULL;
357 return id3;
360 static bool clear_track_info(struct track_info *track)
362 /* bufclose returns true if the handle is not found, or if it is closed
363 * successfully, so these checks are safe on non-existant handles */
364 if (!track)
365 return false;
367 if (track->codec_hid >= 0) {
368 if (bufclose(track->codec_hid))
369 track->codec_hid = -1;
370 else
371 return false;
374 if (track->id3_hid >= 0) {
375 if (bufclose(track->id3_hid))
376 track->id3_hid = -1;
377 else
378 return false;
381 if (track->audio_hid >= 0) {
382 if (bufclose(track->audio_hid))
383 track->audio_hid = -1;
384 else
385 return false;
388 #ifdef HAVE_ALBUMART
389 if (track->aa_hid >= 0) {
390 if (bufclose(track->aa_hid))
391 track->aa_hid = -1;
392 else
393 return false;
395 #endif
397 track->filesize = 0;
398 track->taginfo_ready = false;
400 return true;
403 /* --- External interfaces --- */
405 /* This sends a stop message and the audio thread will dump all it's
406 subsequenct messages */
407 void audio_hard_stop(void)
409 /* Stop playback */
410 LOGFQUEUE("audio >| audio Q_AUDIO_STOP: 1");
411 queue_send(&audio_queue, Q_AUDIO_STOP, 1);
412 #ifdef PLAYBACK_VOICE
413 voice_stop();
414 #endif
417 bool audio_restore_playback(int type)
419 switch (type)
421 case AUDIO_WANT_PLAYBACK:
422 if (buffer_state != BUFFER_STATE_INITIALIZED)
423 audio_reset_buffer();
424 return true;
425 case AUDIO_WANT_VOICE:
426 if (buffer_state == BUFFER_STATE_TRASHED)
427 audio_reset_buffer();
428 return true;
429 default:
430 return false;
434 unsigned char *audio_get_buffer(bool talk_buf, size_t *buffer_size)
436 unsigned char *buf, *end;
438 if (audio_is_initialized)
440 audio_hard_stop();
442 /* else buffer_state will be BUFFER_STATE_TRASHED at this point */
444 if (buffer_size == NULL)
446 /* Special case for talk_init to use since it already knows it's
447 trashed */
448 buffer_state = BUFFER_STATE_TRASHED;
449 return NULL;
452 if (talk_buf || buffer_state == BUFFER_STATE_TRASHED
453 || !talk_voice_required())
455 logf("get buffer: talk, audio");
456 /* Ok to use everything from audiobuf to audiobufend - voice is loaded,
457 the talk buffer is not needed because voice isn't being used, or
458 could be BUFFER_STATE_TRASHED already. If state is
459 BUFFER_STATE_VOICED_ONLY, no problem as long as memory isn't written
460 without the caller knowing what's going on. Changing certain settings
461 may move it to a worse condition but the memory in use by something
462 else will remain undisturbed.
464 if (buffer_state != BUFFER_STATE_TRASHED)
466 talk_buffer_steal();
467 buffer_state = BUFFER_STATE_TRASHED;
470 buf = audiobuf;
471 end = audiobufend;
473 else
475 /* Safe to just return this if already BUFFER_STATE_VOICED_ONLY or
476 still BUFFER_STATE_INITIALIZED */
477 /* Skip talk buffer and move pcm buffer to end to maximize available
478 contiguous memory - no audio running means voice will not need the
479 swap space */
480 logf("get buffer: audio");
481 buf = audiobuf + talk_get_bufsize();
482 end = audiobufend - pcmbuf_init(audiobufend);
483 buffer_state = BUFFER_STATE_VOICED_ONLY;
486 *buffer_size = end - buf;
488 return buf;
491 #ifdef HAVE_RECORDING
492 unsigned char *audio_get_recording_buffer(size_t *buffer_size)
494 /* Stop audio, voice and obtain all available buffer space */
495 audio_hard_stop();
496 talk_buffer_steal();
498 unsigned char *end = audiobufend;
499 buffer_state = BUFFER_STATE_TRASHED;
500 *buffer_size = end - audiobuf;
502 return (unsigned char *)audiobuf;
505 bool audio_load_encoder(int afmt)
507 #ifndef SIMULATOR
508 const char *enc_fn = get_codec_filename(afmt | CODEC_TYPE_ENCODER);
509 if (!enc_fn)
510 return false;
512 audio_remove_encoder();
513 ci.enc_codec_loaded = 0; /* clear any previous error condition */
515 LOGFQUEUE("codec > Q_ENCODER_LOAD_DISK");
516 queue_post(&codec_queue, Q_ENCODER_LOAD_DISK, (intptr_t)enc_fn);
518 while (ci.enc_codec_loaded == 0)
519 yield();
521 logf("codec loaded: %d", ci.enc_codec_loaded);
523 return ci.enc_codec_loaded > 0;
524 #else
525 (void)afmt;
526 return true;
527 #endif
528 } /* audio_load_encoder */
530 void audio_remove_encoder(void)
532 #ifndef SIMULATOR
533 /* force encoder codec unload (if currently loaded) */
534 if (ci.enc_codec_loaded <= 0)
535 return;
537 ci.stop_encoder = true;
538 while (ci.enc_codec_loaded > 0)
539 yield();
540 #endif
541 } /* audio_remove_encoder */
543 #endif /* HAVE_RECORDING */
545 #ifdef HAVE_ALBUMART
546 int audio_current_aa_hid(void)
548 int cur_idx;
549 int offset = ci.new_track + wps_offset;
551 cur_idx = track_ridx + offset;
552 cur_idx &= MAX_TRACK_MASK;
554 return tracks[cur_idx].aa_hid;
556 #endif
558 struct mp3entry* audio_current_track(void)
560 const char *filename;
561 static struct mp3entry temp_id3;
562 struct playlist_track_info trackinfo;
563 int cur_idx;
564 int offset = ci.new_track + wps_offset;
566 cur_idx = (track_ridx + offset) & MAX_TRACK_MASK;
568 if (cur_idx == track_ridx && *curtrack_id3.path)
570 /* The usual case */
571 return &curtrack_id3;
573 else if (automatic_skip && offset == -1 && *prevtrack_id3.path)
575 /* We're in a track transition. The codec has moved on to the nex track,
576 but the audio being played is still the same (now previous) track.
577 prevtrack_id3.elapsed is being updated in an ISR by
578 codec_pcmbuf_position_callback */
579 return &prevtrack_id3;
581 else if (tracks[cur_idx].id3_hid >= 0)
583 /* Get the ID3 metadata from the main buffer */
584 struct mp3entry *ret = bufgetid3(tracks[cur_idx].id3_hid);
585 if (ret) return ret;
588 /* We didn't find the ID3 metadata, so we fill temp_id3 with the little info
589 we have and return that. */
591 memset(&temp_id3, 0, sizeof(struct mp3entry));
593 playlist_get_track_info(NULL, playlist_next(0)+wps_offset, &trackinfo);
594 filename = trackinfo.filename;
595 if (!filename)
596 filename = "No file!";
598 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
599 if (tagcache_fill_tags(&temp_id3, filename))
600 return &temp_id3;
601 #endif
603 strncpy(temp_id3.path, filename, sizeof(temp_id3.path)-1);
604 temp_id3.title = strrchr(temp_id3.path, '/');
605 if (!temp_id3.title)
606 temp_id3.title = &temp_id3.path[0];
607 else
608 temp_id3.title++;
610 return &temp_id3;
613 struct mp3entry* audio_next_track(void)
615 int next_idx;
616 int offset = ci.new_track + wps_offset;
618 if (!audio_have_tracks())
619 return NULL;
621 if (wps_offset == -1 && *prevtrack_id3.path)
623 /* We're in a track transition. The next track for the WPS is the one
624 currently being decoded. */
625 return &curtrack_id3;
628 next_idx = (track_ridx + offset + 1) & MAX_TRACK_MASK;
630 if (tracks[next_idx].id3_hid >= 0)
631 return bufgetid3(tracks[next_idx].id3_hid);
633 if (next_idx == track_widx)
635 /* The next track hasn't been buffered yet, so we return the static
636 version of its metadata. */
637 return &lasttrack_id3;
640 return NULL;
643 bool audio_has_changed_track(void)
645 if (track_changed)
647 track_changed = false;
648 return true;
651 return false;
654 void audio_play(long offset)
656 logf("audio_play");
658 #ifdef PLAYBACK_VOICE
659 /* Truncate any existing voice output so we don't have spelling
660 * etc. over the first part of the played track */
661 talk_force_shutup();
662 #endif
664 /* Start playback */
665 LOGFQUEUE("audio >| audio Q_AUDIO_PLAY: %ld", offset);
666 /* Don't return until playback has actually started */
667 queue_send(&audio_queue, Q_AUDIO_PLAY, offset);
670 void audio_stop(void)
672 /* Stop playback */
673 LOGFQUEUE("audio >| audio Q_AUDIO_STOP");
674 /* Don't return until playback has actually stopped */
675 queue_send(&audio_queue, Q_AUDIO_STOP, 0);
678 void audio_pause(void)
680 LOGFQUEUE("audio >| audio Q_AUDIO_PAUSE");
681 /* Don't return until playback has actually paused */
682 queue_send(&audio_queue, Q_AUDIO_PAUSE, true);
685 void audio_resume(void)
687 LOGFQUEUE("audio >| audio Q_AUDIO_PAUSE resume");
688 /* Don't return until playback has actually resumed */
689 queue_send(&audio_queue, Q_AUDIO_PAUSE, false);
692 static void audio_skip(int direction)
694 if (playlist_check(ci.new_track + wps_offset + direction))
696 if (global_settings.beep)
697 pcmbuf_beep(5000, 100, 2500*global_settings.beep);
699 LOGFQUEUE("audio > audio Q_AUDIO_SKIP %d", direction);
700 queue_post(&audio_queue, Q_AUDIO_SKIP, direction);
701 /* Update wps while our message travels inside deep playback queues. */
702 wps_offset += direction;
703 track_changed = true;
705 else
707 /* No more tracks. */
708 if (global_settings.beep)
709 pcmbuf_beep(1000, 100, 1000*global_settings.beep);
713 void audio_next(void)
715 audio_skip(1);
718 void audio_prev(void)
720 audio_skip(-1);
723 void audio_next_dir(void)
725 LOGFQUEUE("audio > audio Q_AUDIO_DIR_SKIP 1");
726 queue_post(&audio_queue, Q_AUDIO_DIR_SKIP, 1);
729 void audio_prev_dir(void)
731 LOGFQUEUE("audio > audio Q_AUDIO_DIR_SKIP -1");
732 queue_post(&audio_queue, Q_AUDIO_DIR_SKIP, -1);
735 void audio_pre_ff_rewind(void)
737 LOGFQUEUE("audio > audio Q_AUDIO_PRE_FF_REWIND");
738 queue_post(&audio_queue, Q_AUDIO_PRE_FF_REWIND, 0);
741 void audio_ff_rewind(long newpos)
743 LOGFQUEUE("audio > audio Q_AUDIO_FF_REWIND");
744 queue_post(&audio_queue, Q_AUDIO_FF_REWIND, newpos);
747 void audio_flush_and_reload_tracks(void)
749 LOGFQUEUE("audio > audio Q_AUDIO_FLUSH");
750 queue_post(&audio_queue, Q_AUDIO_FLUSH, 0);
753 void audio_error_clear(void)
755 #ifdef AUDIO_HAVE_RECORDING
756 pcm_rec_error_clear();
757 #endif
760 int audio_status(void)
762 int ret = 0;
764 if (playing)
765 ret |= AUDIO_STATUS_PLAY;
767 if (paused)
768 ret |= AUDIO_STATUS_PAUSE;
770 #ifdef HAVE_RECORDING
771 /* Do this here for constitency with mpeg.c version */
772 ret |= pcm_rec_status();
773 #endif
775 return ret;
778 int audio_get_file_pos(void)
780 return 0;
783 #ifdef HAVE_DISK_STORAGE
784 void audio_set_buffer_margin(int setting)
786 static const int lookup[] = {5, 15, 30, 60, 120, 180, 300, 600};
787 buffer_margin = lookup[setting];
788 logf("buffer margin: %ld", (long)buffer_margin);
789 set_filebuf_watermark(buffer_margin, 0);
791 #endif
793 /* Take necessary steps to enable or disable the crossfade setting */
794 void audio_set_crossfade(int enable)
796 size_t offset;
797 bool was_playing;
798 size_t size;
800 /* Tell it the next setting to use */
801 pcmbuf_crossfade_enable(enable);
803 /* Return if size hasn't changed or this is too early to determine
804 which in the second case there's no way we could be playing
805 anything at all */
806 if (pcmbuf_is_same_size())
808 /* This function is a copout and just syncs some variables -
809 to be removed at a later date */
810 pcmbuf_crossfade_enable_finished();
811 return;
814 offset = 0;
815 was_playing = playing;
817 /* Playback has to be stopped before changing the buffer size */
818 if (was_playing)
820 /* Store the track resume position */
821 offset = curtrack_id3.offset;
822 splash(0, str(LANG_RESTARTING_PLAYBACK));
825 /* Blast it - audio buffer will have to be setup again next time
826 something plays */
827 audio_get_buffer(true, &size);
829 /* Restart playback if audio was running previously */
830 if (was_playing)
831 audio_play(offset);
834 /* --- Routines called from multiple threads --- */
836 static void set_filebuf_watermark(int seconds, size_t max)
838 size_t bytes;
840 if (!filebuf)
841 return; /* Audio buffers not yet set up */
843 bytes = seconds?MAX(curtrack_id3.bitrate * seconds * (1000/8), max):max;
844 bytes = MIN(bytes, filebuflen / 2);
845 buf_set_watermark(bytes);
848 const char *get_codec_filename(int cod_spec)
850 const char *fname;
852 #ifdef HAVE_RECORDING
853 /* Can choose decoder or encoder if one available */
854 int type = cod_spec & CODEC_TYPE_MASK;
855 int afmt = cod_spec & CODEC_AFMT_MASK;
857 if ((unsigned)afmt >= AFMT_NUM_CODECS)
858 type = AFMT_UNKNOWN | (type & CODEC_TYPE_MASK);
860 fname = (type == CODEC_TYPE_ENCODER) ?
861 audio_formats[afmt].codec_enc_root_fn :
862 audio_formats[afmt].codec_root_fn;
864 logf("%s: %d - %s",
865 (type == CODEC_TYPE_ENCODER) ? "Encoder" : "Decoder",
866 afmt, fname ? fname : "<unknown>");
867 #else /* !HAVE_RECORDING */
868 /* Always decoder */
869 if ((unsigned)cod_spec >= AFMT_NUM_CODECS)
870 cod_spec = AFMT_UNKNOWN;
871 fname = audio_formats[cod_spec].codec_root_fn;
872 logf("Codec: %d - %s", cod_spec, fname ? fname : "<unknown>");
873 #endif /* HAVE_RECORDING */
875 return fname;
876 } /* get_codec_filename */
878 /* --- Codec thread --- */
879 static bool codec_pcmbuf_insert_callback(
880 const void *ch1, const void *ch2, int count)
882 const char *src[2] = { ch1, ch2 };
884 while (count > 0)
886 int out_count = dsp_output_count(ci.dsp, count);
887 int inp_count;
888 char *dest;
890 /* Prevent audio from a previous track from playing */
891 if (ci.new_track || ci.stop_codec)
892 return true;
894 while ((dest = pcmbuf_request_buffer(&out_count)) == NULL)
896 cancel_cpu_boost();
897 sleep(1);
898 if (ci.seek_time || ci.new_track || ci.stop_codec)
899 return true;
902 /* Get the real input_size for output_size bytes, guarding
903 * against resampling buffer overflows. */
904 inp_count = dsp_input_count(ci.dsp, out_count);
906 if (inp_count <= 0)
907 return true;
909 /* Input size has grown, no error, just don't write more than length */
910 if (inp_count > count)
911 inp_count = count;
913 out_count = dsp_process(ci.dsp, dest, src, inp_count);
915 if (out_count <= 0)
916 return true;
918 pcmbuf_write_complete(out_count);
920 count -= inp_count;
923 return true;
924 } /* codec_pcmbuf_insert_callback */
926 static void* codec_get_buffer(size_t *size)
928 if (codec_size >= CODEC_SIZE)
929 return NULL;
930 *size = CODEC_SIZE - codec_size;
931 return &codecbuf[codec_size];
934 /* Between the codec and PCM track change, we need to keep updating the
935 "elapsed" value of the previous (to the codec, but current to the
936 user/PCM/WPS) track, so that the progressbar reaches the end.
937 During that transition, the WPS will display prevtrack_id3. */
938 static void codec_pcmbuf_position_callback(size_t size) ICODE_ATTR;
939 static void codec_pcmbuf_position_callback(size_t size)
941 /* This is called from an ISR, so be quick */
942 unsigned int time = size * 1000 / 4 / NATIVE_FREQUENCY +
943 prevtrack_id3.elapsed;
945 if (time >= prevtrack_id3.length)
947 pcmbuf_set_position_callback(NULL);
948 prevtrack_id3.elapsed = prevtrack_id3.length;
950 else
951 prevtrack_id3.elapsed = time;
954 static void codec_set_elapsed_callback(unsigned int value)
956 unsigned int latency;
957 if (ci.seek_time)
958 return;
960 #ifdef AB_REPEAT_ENABLE
961 ab_position_report(value);
962 #endif
964 latency = pcmbuf_get_latency();
965 if (value < latency)
966 curtrack_id3.elapsed = 0;
967 else if (value - latency > curtrack_id3.elapsed ||
968 value - latency < curtrack_id3.elapsed - 2)
970 curtrack_id3.elapsed = value - latency;
974 static void codec_set_offset_callback(size_t value)
976 unsigned int latency;
978 if (ci.seek_time)
979 return;
981 latency = pcmbuf_get_latency() * curtrack_id3.bitrate / 8;
982 if (value < latency)
983 curtrack_id3.offset = 0;
984 else
985 curtrack_id3.offset = value - latency;
988 static void codec_advance_buffer_counters(size_t amount)
990 bufadvance(CUR_TI->audio_hid, amount);
991 ci.curpos += amount;
994 /* copy up-to size bytes into ptr and return the actual size copied */
995 static size_t codec_filebuf_callback(void *ptr, size_t size)
997 ssize_t copy_n;
999 if (ci.stop_codec || !playing)
1000 return 0;
1002 copy_n = bufread(CUR_TI->audio_hid, size, ptr);
1004 /* Nothing requested OR nothing left */
1005 if (copy_n == 0)
1006 return 0;
1008 /* Update read and other position pointers */
1009 codec_advance_buffer_counters(copy_n);
1011 /* Return the actual amount of data copied to the buffer */
1012 return copy_n;
1013 } /* codec_filebuf_callback */
1015 static void* codec_request_buffer_callback(size_t *realsize, size_t reqsize)
1017 size_t copy_n = reqsize;
1018 ssize_t ret;
1019 void *ptr;
1021 if (!playing)
1023 *realsize = 0;
1024 return NULL;
1027 ret = bufgetdata(CUR_TI->audio_hid, reqsize, &ptr);
1028 if (ret >= 0)
1029 copy_n = MIN((size_t)ret, reqsize);
1031 if (copy_n == 0)
1033 *realsize = 0;
1034 return NULL;
1037 *realsize = copy_n;
1039 return ptr;
1040 } /* codec_request_buffer_callback */
1042 static int get_codec_base_type(int type)
1044 switch (type) {
1045 case AFMT_MPA_L1:
1046 case AFMT_MPA_L2:
1047 case AFMT_MPA_L3:
1048 return AFMT_MPA_L3;
1051 return type;
1054 static void codec_advance_buffer_callback(size_t amount)
1056 codec_advance_buffer_counters(amount);
1057 codec_set_offset_callback(ci.curpos);
1060 static void codec_advance_buffer_loc_callback(void *ptr)
1062 size_t amount = buf_get_offset(CUR_TI->audio_hid, ptr);
1063 codec_advance_buffer_callback(amount);
1066 static void codec_seek_complete_callback(void)
1068 logf("seek_complete");
1069 if (pcm_is_paused())
1071 /* If this is not a seamless seek, clear the buffer */
1072 pcmbuf_play_stop();
1073 dsp_configure(ci.dsp, DSP_FLUSH, 0);
1075 /* If playback was not 'deliberately' paused, unpause now */
1076 if (!paused)
1077 pcmbuf_pause(false);
1079 ci.seek_time = 0;
1082 static bool codec_seek_buffer_callback(size_t newpos)
1084 logf("codec_seek_buffer_callback");
1086 int ret = bufseek(CUR_TI->audio_hid, newpos);
1087 if (ret == 0) {
1088 ci.curpos = newpos;
1089 return true;
1091 else {
1092 return false;
1096 static void codec_configure_callback(int setting, intptr_t value)
1098 switch (setting) {
1099 case CODEC_SET_FILEBUF_WATERMARK:
1100 set_filebuf_watermark(buffer_margin, value);
1101 break;
1103 default:
1104 if (!dsp_configure(ci.dsp, setting, value))
1105 { logf("Illegal key:%d", setting); }
1109 static void codec_track_changed(void)
1111 LOGFQUEUE("codec > audio Q_AUDIO_TRACK_CHANGED");
1112 queue_post(&audio_queue, Q_AUDIO_TRACK_CHANGED, 0);
1115 static void codec_pcmbuf_track_changed_callback(void)
1117 pcmbuf_set_position_callback(NULL);
1118 pcmbuf_callback_queue_post(Q_AUDIO_TRACK_CHANGED, 0);
1121 static void codec_discard_codec_callback(void)
1123 if (CUR_TI->codec_hid >= 0)
1125 bufclose(CUR_TI->codec_hid);
1126 CUR_TI->codec_hid = -1;
1130 static inline void codec_gapless_track_change(void)
1132 /* callback keeps the progress bar moving while the pcmbuf empties */
1133 pcmbuf_set_position_callback(codec_pcmbuf_position_callback);
1134 /* set the pcmbuf callback for when the track really changes */
1135 pcmbuf_set_event_handler(codec_pcmbuf_track_changed_callback);
1138 static inline void codec_crossfade_track_change(void)
1140 /* Initiate automatic crossfade mode */
1141 pcmbuf_crossfade_init(false);
1142 /* Notify the wps that the track change starts now */
1143 codec_track_changed();
1146 static void codec_track_skip_done(bool was_manual)
1148 /* Manual track change (always crossfade or flush audio). */
1149 if (was_manual)
1151 pcmbuf_crossfade_init(true);
1152 LOGFQUEUE("codec > audio Q_AUDIO_TRACK_CHANGED");
1153 queue_post(&audio_queue, Q_AUDIO_TRACK_CHANGED, 0);
1155 /* Automatic track change w/crossfade, if not in "Track Skip Only" mode. */
1156 else if (pcmbuf_is_crossfade_enabled() && !pcmbuf_is_crossfade_active()
1157 && global_settings.crossfade != CROSSFADE_ENABLE_TRACKSKIP)
1159 if (global_settings.crossfade == CROSSFADE_ENABLE_SHUFFLE_AND_TRACKSKIP)
1161 if (global_settings.playlist_shuffle)
1162 /* shuffle mode is on, so crossfade: */
1163 codec_crossfade_track_change();
1164 else
1165 /* shuffle mode is off, so do a gapless track change */
1166 codec_gapless_track_change();
1168 else
1169 /* normal crossfade: */
1170 codec_crossfade_track_change();
1172 else
1173 /* normal gapless playback. */
1174 codec_gapless_track_change();
1177 static bool codec_load_next_track(void)
1179 intptr_t result = Q_CODEC_REQUEST_FAILED;
1181 prev_track_elapsed = curtrack_id3.elapsed;
1183 #ifdef AB_REPEAT_ENABLE
1184 ab_end_of_track_report();
1185 #endif
1187 logf("Request new track");
1189 if (ci.new_track == 0)
1191 ci.new_track++;
1192 automatic_skip = true;
1195 if (!ci.stop_codec)
1197 trigger_cpu_boost();
1198 LOGFQUEUE("codec >| audio Q_AUDIO_CHECK_NEW_TRACK");
1199 result = queue_send(&audio_queue, Q_AUDIO_CHECK_NEW_TRACK, 0);
1202 switch (result)
1204 case Q_CODEC_REQUEST_COMPLETE:
1205 LOGFQUEUE("codec |< Q_CODEC_REQUEST_COMPLETE");
1206 codec_track_skip_done(!automatic_skip);
1207 return true;
1209 case Q_CODEC_REQUEST_FAILED:
1210 LOGFQUEUE("codec |< Q_CODEC_REQUEST_FAILED");
1211 ci.new_track = 0;
1212 ci.stop_codec = true;
1213 codec_requested_stop = true;
1214 return false;
1216 default:
1217 LOGFQUEUE("codec |< default");
1218 ci.stop_codec = true;
1219 codec_requested_stop = true;
1220 return false;
1224 static bool codec_request_next_track_callback(void)
1226 int prev_codectype;
1228 if (ci.stop_codec || !playing)
1229 return false;
1231 prev_codectype = get_codec_base_type(curtrack_id3.codectype);
1233 if (!codec_load_next_track())
1234 return false;
1236 /* Seek to the beginning of the new track because if the struct
1237 mp3entry was buffered, "elapsed" might not be zero (if the track has
1238 been played already but not unbuffered) */
1239 codec_seek_buffer_callback(curtrack_id3.first_frame_offset);
1241 /* Check if the next codec is the same file. */
1242 if (prev_codectype == get_codec_base_type(curtrack_id3.codectype))
1244 logf("New track loaded");
1245 codec_discard_codec_callback();
1246 return true;
1248 else
1250 logf("New codec:%d/%d", curtrack_id3.codectype, prev_codectype);
1251 return false;
1255 static void codec_thread(void)
1257 struct queue_event ev;
1258 int status;
1260 while (1) {
1261 status = 0;
1263 if (!pcmbuf_is_crossfade_active()) {
1264 cancel_cpu_boost();
1267 queue_wait(&codec_queue, &ev);
1268 codec_requested_stop = false;
1270 switch (ev.id) {
1271 case Q_CODEC_LOAD_DISK:
1272 LOGFQUEUE("codec < Q_CODEC_LOAD_DISK");
1273 queue_reply(&codec_queue, 1);
1274 audio_codec_loaded = true;
1275 ci.stop_codec = false;
1276 status = codec_load_file((const char *)ev.data, &ci);
1277 break;
1279 case Q_CODEC_LOAD:
1280 LOGFQUEUE("codec < Q_CODEC_LOAD");
1281 if (CUR_TI->codec_hid < 0) {
1282 logf("Codec slot is empty!");
1283 /* Wait for the pcm buffer to go empty */
1284 while (pcm_is_playing())
1285 yield();
1286 /* This must be set to prevent an infinite loop */
1287 ci.stop_codec = true;
1288 LOGFQUEUE("codec > codec Q_AUDIO_PLAY");
1289 queue_post(&codec_queue, Q_AUDIO_PLAY, 0);
1290 break;
1293 audio_codec_loaded = true;
1294 ci.stop_codec = false;
1295 status = codec_load_buf(CUR_TI->codec_hid, &ci);
1296 break;
1298 #ifdef AUDIO_HAVE_RECORDING
1299 case Q_ENCODER_LOAD_DISK:
1300 LOGFQUEUE("codec < Q_ENCODER_LOAD_DISK");
1301 audio_codec_loaded = false; /* Not audio codec! */
1302 logf("loading encoder");
1303 ci.stop_encoder = false;
1304 status = codec_load_file((const char *)ev.data, &ci);
1305 logf("encoder stopped");
1306 break;
1307 #endif /* AUDIO_HAVE_RECORDING */
1309 default:
1310 LOGFQUEUE("codec < default");
1313 if (audio_codec_loaded)
1315 if (ci.stop_codec)
1317 status = CODEC_OK;
1318 if (!playing)
1319 pcmbuf_play_stop();
1322 audio_codec_loaded = false;
1325 switch (ev.id) {
1326 case Q_CODEC_LOAD_DISK:
1327 case Q_CODEC_LOAD:
1328 LOGFQUEUE("codec < Q_CODEC_LOAD");
1329 if (playing)
1331 if (ci.new_track || status != CODEC_OK)
1333 if (!ci.new_track)
1335 logf("Codec failure");
1336 splash(HZ*2, "Codec failure");
1339 if (!codec_load_next_track())
1341 LOGFQUEUE("codec > audio Q_AUDIO_STOP");
1342 /* End of playlist */
1343 queue_post(&audio_queue, Q_AUDIO_STOP, 0);
1344 break;
1347 else
1349 logf("Codec finished");
1350 if (ci.stop_codec)
1352 /* Wait for the audio to stop playing before
1353 * triggering the WPS exit */
1354 while(pcm_is_playing())
1356 curtrack_id3.elapsed =
1357 curtrack_id3.length - pcmbuf_get_latency();
1358 sleep(1);
1361 if (codec_requested_stop)
1363 LOGFQUEUE("codec > audio Q_AUDIO_STOP");
1364 queue_post(&audio_queue, Q_AUDIO_STOP, 0);
1366 break;
1370 if (CUR_TI->codec_hid >= 0)
1372 LOGFQUEUE("codec > codec Q_CODEC_LOAD");
1373 queue_post(&codec_queue, Q_CODEC_LOAD, 0);
1375 else
1377 const char *codec_fn =
1378 get_codec_filename(curtrack_id3.codectype);
1379 if (codec_fn)
1381 LOGFQUEUE("codec > codec Q_CODEC_LOAD_DISK");
1382 queue_post(&codec_queue, Q_CODEC_LOAD_DISK,
1383 (intptr_t)codec_fn);
1387 break;
1389 #ifdef AUDIO_HAVE_RECORDING
1390 case Q_ENCODER_LOAD_DISK:
1391 LOGFQUEUE("codec < Q_ENCODER_LOAD_DISK");
1393 if (status == CODEC_OK)
1394 break;
1396 logf("Encoder failure");
1397 splash(HZ*2, "Encoder failure");
1399 if (ci.enc_codec_loaded < 0)
1400 break;
1402 logf("Encoder failed to load");
1403 ci.enc_codec_loaded = -1;
1404 break;
1405 #endif /* AUDIO_HAVE_RECORDING */
1407 default:
1408 LOGFQUEUE("codec < default");
1410 } /* end switch */
1415 /* --- Buffering callbacks --- */
1417 static void buffering_low_buffer_callback(void *data)
1419 (void)data;
1420 logf("low buffer callback");
1422 if (filling == STATE_FULL || filling == STATE_END_OF_PLAYLIST) {
1423 /* force a refill */
1424 LOGFQUEUE("buffering > audio Q_AUDIO_FILL_BUFFER");
1425 queue_post(&audio_queue, Q_AUDIO_FILL_BUFFER, 0);
1429 static void buffering_handle_rebuffer_callback(void *data)
1431 (void)data;
1432 LOGFQUEUE("audio >| audio Q_AUDIO_FLUSH");
1433 queue_post(&audio_queue, Q_AUDIO_FLUSH, 0);
1436 static void buffering_handle_finished_callback(int *data)
1438 logf("handle %d finished buffering", *data);
1440 if (*data == tracks[track_widx].id3_hid)
1442 /* The metadata handle for the last loaded track has been buffered.
1443 We can ask the audio thread to load the rest of the track's data. */
1444 LOGFQUEUE("audio >| audio Q_AUDIO_FINISH_LOAD");
1445 queue_post(&audio_queue, Q_AUDIO_FINISH_LOAD, 0);
1447 else
1449 /* This is most likely an audio handle, so we strip the useless
1450 trailing tags that are left. */
1451 strip_tags(*data);
1453 if (*data == tracks[track_widx-1].audio_hid
1454 && filling == STATE_END_OF_PLAYLIST)
1456 /* This was the last track in the playlist.
1457 We now have all the data we need. */
1458 logf("last track finished buffering");
1459 filling = STATE_FINISHED;
1465 /* --- Audio thread --- */
1467 static bool audio_have_tracks(void)
1469 return (audio_track_count() != 0);
1472 static int audio_free_track_count(void)
1474 /* Used tracks + free tracks adds up to MAX_TRACK - 1 */
1475 return MAX_TRACK - 1 - audio_track_count();
1478 int audio_track_count(void)
1480 /* Calculate difference from track_ridx to track_widx
1481 * taking into account a possible wrap-around. */
1482 return (MAX_TRACK + track_widx - track_ridx) & MAX_TRACK_MASK;
1485 long audio_filebufused(void)
1487 return (long) buf_used();
1490 /* Update track info after successful a codec track change */
1491 static void audio_update_trackinfo(void)
1493 /* Load the curent track's metadata into curtrack_id3 */
1494 if (CUR_TI->id3_hid >= 0)
1495 copy_mp3entry(&curtrack_id3, bufgetid3(CUR_TI->id3_hid));
1497 /* Reset current position */
1498 curtrack_id3.elapsed = 0;
1499 curtrack_id3.offset = 0;
1501 /* Update the codec API */
1502 ci.filesize = CUR_TI->filesize;
1503 ci.id3 = &curtrack_id3;
1504 ci.curpos = 0;
1505 ci.taginfo_ready = &CUR_TI->taginfo_ready;
1508 /* Clear tracks between write and read, non inclusive */
1509 static void audio_clear_track_entries(void)
1511 int cur_idx = track_widx;
1513 logf("Clearing tracks:%d/%d", track_ridx, track_widx);
1515 /* Loop over all tracks from write-to-read */
1516 while (1)
1518 cur_idx = (cur_idx + 1) & MAX_TRACK_MASK;
1520 if (cur_idx == track_ridx)
1521 break;
1523 clear_track_info(&tracks[cur_idx]);
1527 /* Clear all tracks */
1528 static bool audio_release_tracks(void)
1530 int i, cur_idx;
1532 logf("releasing all tracks");
1534 for(i = 0; i < MAX_TRACK; i++)
1536 cur_idx = (track_ridx + i) & MAX_TRACK_MASK;
1537 if (!clear_track_info(&tracks[cur_idx]))
1538 return false;
1541 return true;
1544 static bool audio_loadcodec(bool start_play)
1546 int prev_track;
1547 char codec_path[MAX_PATH]; /* Full path to codec */
1548 const struct mp3entry *id3, *prev_id3;
1550 if (tracks[track_widx].id3_hid < 0) {
1551 return false;
1554 id3 = bufgetid3(tracks[track_widx].id3_hid);
1555 if (!id3)
1556 return false;
1558 const char *codec_fn = get_codec_filename(id3->codectype);
1559 if (codec_fn == NULL)
1560 return false;
1562 tracks[track_widx].codec_hid = -1;
1564 if (start_play)
1566 /* Load the codec directly from disk and save some memory. */
1567 track_ridx = track_widx;
1568 ci.filesize = CUR_TI->filesize;
1569 ci.id3 = &curtrack_id3;
1570 ci.taginfo_ready = &CUR_TI->taginfo_ready;
1571 ci.curpos = 0;
1572 LOGFQUEUE("codec > codec Q_CODEC_LOAD_DISK");
1573 queue_post(&codec_queue, Q_CODEC_LOAD_DISK, (intptr_t)codec_fn);
1574 return true;
1576 else
1578 /* If we already have another track than this one buffered */
1579 if (track_widx != track_ridx)
1581 prev_track = (track_widx - 1) & MAX_TRACK_MASK;
1583 id3 = bufgetid3(tracks[track_widx].id3_hid);
1584 prev_id3 = bufgetid3(tracks[prev_track].id3_hid);
1586 /* If the previous codec is the same as this one, there is no need
1587 * to put another copy of it on the file buffer */
1588 if (id3 && prev_id3 &&
1589 get_codec_base_type(id3->codectype) ==
1590 get_codec_base_type(prev_id3->codectype)
1591 && audio_codec_loaded)
1593 logf("Reusing prev. codec");
1594 return true;
1599 codec_get_full_path(codec_path, codec_fn);
1601 tracks[track_widx].codec_hid = bufopen(codec_path, 0, TYPE_CODEC);
1602 if (tracks[track_widx].codec_hid < 0)
1603 return false;
1605 logf("Loaded codec");
1607 return true;
1610 /* Load metadata for the next track (with bufopen). The rest of the track
1611 loading will be handled by audio_finish_load_track once the metadata has been
1612 actually loaded by the buffering thread. */
1613 static bool audio_load_track(size_t offset, bool start_play)
1615 const char *trackname;
1616 int fd = -1;
1618 if (track_load_started) {
1619 /* There is already a track load in progress, so track_widx hasn't been
1620 incremented yet. Loading another track would overwrite the one that
1621 hasn't finished loading. */
1622 logf("audio_load_track(): a track load is already in progress");
1623 return false;
1626 start_play_g = start_play; /* will be read by audio_finish_load_track */
1628 /* Stop buffer filling if there is no free track entries.
1629 Don't fill up the last track entry (we wan't to store next track
1630 metadata there). */
1631 if (!audio_free_track_count())
1633 logf("No free tracks");
1634 return false;
1637 last_peek_offset++;
1638 tracks[track_widx].taginfo_ready = false;
1640 logf("Buffering track:%d/%d", track_widx, track_ridx);
1641 /* Get track name from current playlist read position. */
1642 while ((trackname = playlist_peek(last_peek_offset)) != NULL)
1644 /* Handle broken playlists. */
1645 fd = open(trackname, O_RDONLY);
1646 if (fd < 0)
1648 logf("Open failed");
1649 /* Skip invalid entry from playlist. */
1650 playlist_skip_entry(NULL, last_peek_offset);
1652 else
1653 break;
1656 if (!trackname)
1658 logf("End-of-playlist");
1659 memset(&lasttrack_id3, 0, sizeof(struct mp3entry));
1660 filling = STATE_END_OF_PLAYLIST;
1662 if (curtrack_id3.length == 0 && curtrack_id3.filesize == 0)
1664 /* Stop playback if no valid track was found. */
1665 audio_stop_playback();
1668 return false;
1671 tracks[track_widx].filesize = filesize(fd);
1673 if (offset > tracks[track_widx].filesize)
1674 offset = 0;
1676 /* Set default values */
1677 if (start_play)
1679 buf_set_watermark(AUDIO_DEFAULT_WATERMARK);
1680 dsp_configure(ci.dsp, DSP_RESET, 0);
1681 track_changed = true;
1682 playlist_update_resume_info(audio_current_track());
1685 /* Get track metadata if we don't already have it. */
1686 if (tracks[track_widx].id3_hid < 0)
1688 tracks[track_widx].id3_hid = bufopen(trackname, 0, TYPE_ID3);
1690 if (tracks[track_widx].id3_hid < 0)
1692 /* Buffer is full. */
1693 get_metadata(&lasttrack_id3, fd, trackname);
1694 last_peek_offset--;
1695 close(fd);
1696 logf("buffer is full for now");
1697 filling = STATE_FULL;
1698 return false;
1701 if (track_widx == track_ridx)
1703 /* TODO: Superfluos buffering call? */
1704 buf_request_buffer_handle(tracks[track_widx].id3_hid);
1705 copy_mp3entry(&curtrack_id3, bufgetid3(tracks[track_widx].id3_hid));
1706 curtrack_id3.offset = offset;
1709 if (start_play)
1711 track_changed = true;
1712 playlist_update_resume_info(audio_current_track());
1716 close(fd);
1717 track_load_started = true; /* Remember that we've started loading a track */
1718 return true;
1721 /* Second part of the track loading: We now have the metadata available, so we
1722 can load the codec, the album art and finally the audio data.
1723 This is called on the audio thread after the buffering thread calls the
1724 buffering_handle_finished_callback callback. */
1725 static void audio_finish_load_track(void)
1727 size_t file_offset = 0;
1728 size_t offset = 0;
1729 bool start_play = start_play_g;
1731 #if 0
1732 if (cuesheet_is_enabled() && tracks[track_widx].id3.cuesheet_type == 1)
1734 char cuepath[MAX_PATH];
1736 struct cuesheet *cue = start_play ? curr_cue : temp_cue;
1738 if (look_for_cuesheet_file(trackname, cuepath) &&
1739 parse_cuesheet(cuepath, cue))
1741 strcpy((cue)->audio_filename, trackname);
1742 if (start_play)
1743 cue_spoof_id3(curr_cue, &tracks[track_widx].id3);
1746 #endif
1748 track_load_started = false;
1750 if (tracks[track_widx].id3_hid < 0) {
1751 logf("no metatdata");
1752 return;
1755 struct mp3entry *track_id3;
1757 if (track_widx == track_ridx)
1758 track_id3 = &curtrack_id3;
1759 else
1760 track_id3 = bufgetid3(tracks[track_widx].id3_hid);
1762 if (track_id3->length == 0 && track_id3->filesize == 0)
1764 logf("audio_finish_load_track: invalid metadata");
1766 /* Invalid metadata */
1767 bufclose(tracks[track_widx].id3_hid);
1768 tracks[track_widx].id3_hid = -1;
1770 /* Skip invalid entry from playlist. */
1771 playlist_skip_entry(NULL, last_peek_offset--);
1773 /* load next track */
1774 LOGFQUEUE("audio > audio Q_AUDIO_FILL_BUFFER %d", (int)start_play);
1775 queue_post(&audio_queue, Q_AUDIO_FILL_BUFFER, start_play);
1777 return;
1780 #ifdef HAVE_ALBUMART
1781 if (tracks[track_widx].aa_hid < 0 && gui_sync_wps_uses_albumart())
1783 char aa_path[MAX_PATH];
1784 if (find_albumart(track_id3, aa_path, sizeof(aa_path)))
1785 tracks[track_widx].aa_hid = bufopen(aa_path, 0, TYPE_BITMAP);
1787 #endif
1789 /* Load the codec. */
1790 if (!audio_loadcodec(start_play))
1792 if (tracks[track_widx].codec_hid == ERR_BUFFER_FULL)
1794 /* No space for codec on buffer, not an error */
1795 return;
1798 /* This is an error condition, either no codec was found, or reading
1799 * the codec file failed part way through, either way, skip the track */
1800 /* FIXME: We should not use splashf from audio thread! */
1801 splashf(HZ*2, "No codec for: %s", track_id3->path);
1802 /* Skip invalid entry from playlist. */
1803 playlist_skip_entry(NULL, last_peek_offset);
1804 return;
1807 track_id3->elapsed = 0;
1808 offset = track_id3->offset;
1810 enum data_type type = TYPE_PACKET_AUDIO;
1812 switch (track_id3->codectype) {
1813 case AFMT_MPA_L1:
1814 case AFMT_MPA_L2:
1815 case AFMT_MPA_L3:
1816 if (offset > 0) {
1817 file_offset = offset;
1818 track_id3->offset = offset;
1820 break;
1822 case AFMT_WAVPACK:
1823 if (offset > 0) {
1824 file_offset = offset;
1825 track_id3->offset = offset;
1826 track_id3->elapsed = track_id3->length / 2;
1828 break;
1830 case AFMT_OGG_VORBIS:
1831 case AFMT_SPEEX:
1832 case AFMT_FLAC:
1833 case AFMT_PCM_WAV:
1834 case AFMT_A52:
1835 case AFMT_AAC:
1836 case AFMT_MPC:
1837 case AFMT_APE:
1838 case AFMT_WMA:
1839 if (offset > 0)
1840 track_id3->offset = offset;
1841 break;
1843 case AFMT_NSF:
1844 case AFMT_SPC:
1845 case AFMT_SID:
1846 logf("Loading atomic %d",track_id3->codectype);
1847 type = TYPE_ATOMIC_AUDIO;
1848 break;
1851 logf("alt:%s", track_id3->path);
1853 if (file_offset > AUDIO_REBUFFER_GUESS_SIZE)
1854 file_offset -= AUDIO_REBUFFER_GUESS_SIZE;
1855 else if (track_id3->first_frame_offset)
1856 file_offset = track_id3->first_frame_offset;
1857 else
1858 file_offset = 0;
1860 tracks[track_widx].audio_hid = bufopen(track_id3->path, file_offset, type);
1862 if (tracks[track_widx].audio_hid < 0)
1863 return;
1865 /* All required data is now available for the codec. */
1866 tracks[track_widx].taginfo_ready = true;
1868 if (start_play)
1870 ci.curpos=file_offset;
1871 buf_request_buffer_handle(tracks[track_widx].audio_hid);
1874 track_widx = (track_widx + 1) & MAX_TRACK_MASK;
1876 send_event(PLAYBACK_EVENT_TRACK_BUFFER, track_id3);
1878 /* load next track */
1879 LOGFQUEUE("audio > audio Q_AUDIO_FILL_BUFFER");
1880 queue_post(&audio_queue, Q_AUDIO_FILL_BUFFER, 0);
1882 return;
1885 static void audio_fill_file_buffer(bool start_play, size_t offset)
1887 bool had_next_track = audio_next_track() != NULL;
1889 filling = STATE_FILLING;
1890 trigger_cpu_boost();
1892 /* No need to rebuffer if there are track skips pending. */
1893 if (ci.new_track != 0)
1894 return;
1896 /* Must reset the buffer before use if trashed or voice only - voice
1897 file size shouldn't have changed so we can go straight from
1898 BUFFER_STATE_VOICED_ONLY to BUFFER_STATE_INITIALIZED */
1899 if (buffer_state != BUFFER_STATE_INITIALIZED)
1900 audio_reset_buffer();
1902 logf("Starting buffer fill");
1904 if (!start_play)
1905 audio_clear_track_entries();
1907 /* Save the current resume position once. */
1908 playlist_update_resume_info(audio_current_track());
1910 audio_load_track(offset, start_play);
1912 if (!had_next_track && audio_next_track())
1913 track_changed = true;
1916 static void audio_rebuffer(void)
1918 logf("Forcing rebuffer");
1920 clear_track_info(CUR_TI);
1922 /* Reset track pointers */
1923 track_widx = track_ridx;
1924 audio_clear_track_entries();
1926 /* Reset a possibly interrupted track load */
1927 track_load_started = false;
1929 /* Fill the buffer */
1930 last_peek_offset = -1;
1931 ci.curpos = 0;
1933 if (!CUR_TI->taginfo_ready)
1934 memset(&curtrack_id3, 0, sizeof(struct mp3entry));
1936 audio_fill_file_buffer(false, 0);
1939 /* Called on request from the codec to get a new track. This is the codec part
1940 of the track transition. */
1941 static int audio_check_new_track(void)
1943 int track_count = audio_track_count();
1944 int old_track_ridx = track_ridx;
1945 int i, idx;
1946 bool forward;
1948 /* Now it's good time to send track finish events. */
1949 send_event(PLAYBACK_EVENT_TRACK_FINISH, &curtrack_id3);
1950 if (dir_skip)
1952 dir_skip = false;
1953 if (playlist_next_dir(ci.new_track))
1955 ci.new_track = 0;
1956 audio_rebuffer();
1957 goto skip_done;
1959 else
1961 LOGFQUEUE("audio >|= codec Q_CODEC_REQUEST_FAILED");
1962 return Q_CODEC_REQUEST_FAILED;
1966 if (new_playlist)
1967 ci.new_track = 0;
1969 /* If the playlist isn't that big */
1970 if (automatic_skip)
1972 while (!playlist_check(ci.new_track))
1974 if (ci.new_track >= 0)
1976 LOGFQUEUE("audio >|= codec Q_CODEC_REQUEST_FAILED");
1977 return Q_CODEC_REQUEST_FAILED;
1979 ci.new_track++;
1983 /* Update the playlist */
1984 last_peek_offset -= ci.new_track;
1986 if (playlist_next(ci.new_track) < 0)
1988 LOGFQUEUE("audio >|= codec Q_CODEC_REQUEST_FAILED");
1989 return Q_CODEC_REQUEST_FAILED;
1992 if (new_playlist)
1994 ci.new_track = 1;
1995 new_playlist = false;
1998 /* Save the track metadata to allow the WPS to display it
1999 while PCM finishes playing that track */
2000 copy_mp3entry(&prevtrack_id3, &curtrack_id3);
2002 /* Update the main buffer copy of the track metadata with the one
2003 the codec has been using (for the unbuffer callbacks) */
2004 if (CUR_TI->id3_hid >= 0)
2005 copy_mp3entry(bufgetid3(CUR_TI->id3_hid), &curtrack_id3);
2007 /* Save a pointer to the old track to allow later clearing */
2008 prev_ti = CUR_TI;
2010 for (i = 0; i < ci.new_track; i++)
2012 idx = (track_ridx + i) & MAX_TRACK_MASK;
2013 struct mp3entry *id3 = bufgetid3(tracks[idx].id3_hid);
2014 ssize_t offset = buf_handle_offset(tracks[idx].audio_hid);
2015 if (!id3 || offset < 0 || (unsigned)offset > id3->first_frame_offset)
2017 /* We don't have all the audio data for that track, so clear it,
2018 but keep the metadata. */
2019 if (tracks[idx].audio_hid >= 0 && bufclose(tracks[idx].audio_hid))
2021 tracks[idx].audio_hid = -1;
2022 tracks[idx].filesize = 0;
2027 /* Move to the new track */
2028 track_ridx = (track_ridx + ci.new_track) & MAX_TRACK_MASK;
2030 buf_set_base_handle(CUR_TI->audio_hid);
2032 if (automatic_skip)
2034 wps_offset = -ci.new_track;
2035 track_changed = true;
2038 /* If it is not safe to even skip this many track entries */
2039 if (ci.new_track >= track_count || ci.new_track <= track_count - MAX_TRACK)
2041 ci.new_track = 0;
2042 audio_rebuffer();
2043 goto skip_done;
2046 forward = ci.new_track > 0;
2047 ci.new_track = 0;
2049 /* If the target track is clearly not in memory */
2050 if (CUR_TI->filesize == 0 || !CUR_TI->taginfo_ready)
2052 audio_rebuffer();
2053 goto skip_done;
2056 /* When skipping backwards, it is possible that we've found a track that's
2057 * buffered, but which is around the track-wrap and therefore not the track
2058 * we are looking for */
2059 if (!forward)
2061 int cur_idx = track_ridx;
2062 bool taginfo_ready = true;
2063 /* We've wrapped the buffer backwards if new > old */
2064 bool wrap = track_ridx > old_track_ridx;
2066 while (1)
2068 cur_idx = (cur_idx + 1) & MAX_TRACK_MASK;
2070 /* if we've advanced past the wrap when cur_idx is zeroed */
2071 if (!cur_idx)
2072 wrap = false;
2074 /* if we aren't still on the wrap and we've caught the old track */
2075 if (!(wrap || cur_idx < old_track_ridx))
2076 break;
2078 /* If we hit a track in between without valid tag info, bail */
2079 if (!tracks[cur_idx].taginfo_ready)
2081 taginfo_ready = false;
2082 break;
2085 if (!taginfo_ready)
2087 audio_rebuffer();
2091 skip_done:
2092 audio_update_trackinfo();
2093 LOGFQUEUE("audio >|= codec Q_CODEC_REQUEST_COMPLETE");
2094 return Q_CODEC_REQUEST_COMPLETE;
2097 unsigned long audio_prev_elapsed(void)
2099 return prev_track_elapsed;
2102 static void audio_stop_codec_flush(void)
2104 ci.stop_codec = true;
2105 pcmbuf_pause(true);
2107 while (audio_codec_loaded)
2108 yield();
2110 /* If the audio codec is not loaded any more, and the audio is still
2111 * playing, it is now and _only_ now safe to call this function from the
2112 * audio thread */
2113 if (pcm_is_playing())
2115 pcmbuf_play_stop();
2116 pcmbuf_queue_clear();
2118 pcmbuf_pause(paused);
2121 static void audio_stop_playback(void)
2123 /* If we were playing, save resume information */
2124 if (playing)
2126 struct mp3entry *id3 = NULL;
2128 if (!ci.stop_codec)
2130 /* Set this early, the outside code yields and may allow the codec
2131 to try to wait for a reply on a buffer wait */
2132 ci.stop_codec = true;
2133 id3 = audio_current_track();
2136 /* Save the current playing spot, or NULL if the playlist has ended */
2137 playlist_update_resume_info(id3);
2139 /* TODO: Create auto bookmark too? */
2141 prev_track_elapsed = curtrack_id3.elapsed;
2143 remove_event(BUFFER_EVENT_BUFFER_LOW, buffering_low_buffer_callback);
2146 audio_stop_codec_flush();
2147 paused = false;
2148 playing = false;
2149 track_load_started = false;
2151 filling = STATE_IDLE;
2153 /* Mark all entries null. */
2154 audio_clear_track_entries();
2156 /* Close all tracks */
2157 audio_release_tracks();
2159 memset(&curtrack_id3, 0, sizeof(struct mp3entry));
2162 static void audio_play_start(size_t offset)
2164 int i;
2166 #if INPUT_SRC_CAPS != 0
2167 audio_set_input_source(AUDIO_SRC_PLAYBACK, SRCF_PLAYBACK);
2168 audio_set_output_source(AUDIO_SRC_PLAYBACK);
2169 #endif
2171 /* Wait for any previously playing audio to flush - TODO: Not necessary? */
2172 paused = false;
2173 audio_stop_codec_flush();
2175 track_changed = true;
2177 playing = true;
2178 track_load_started = false;
2180 ci.new_track = 0;
2181 ci.seek_time = 0;
2182 wps_offset = 0;
2184 sound_set_volume(global_settings.volume);
2185 track_widx = track_ridx = 0;
2187 /* Clear all track entries. */
2188 for (i = 0; i < MAX_TRACK; i++) {
2189 clear_track_info(&tracks[i]);
2192 last_peek_offset = -1;
2194 /* Officially playing */
2195 queue_reply(&audio_queue, 1);
2197 #ifdef HAVE_DISK_STORAGE
2198 set_filebuf_watermark(buffer_margin, 0);
2199 #endif
2201 audio_fill_file_buffer(true, offset);
2203 add_event(BUFFER_EVENT_BUFFER_LOW, false, buffering_low_buffer_callback);
2205 LOGFQUEUE("audio > audio Q_AUDIO_TRACK_CHANGED");
2206 queue_post(&audio_queue, Q_AUDIO_TRACK_CHANGED, 0);
2210 /* Invalidates all but currently playing track. */
2211 static void audio_invalidate_tracks(void)
2213 if (audio_have_tracks())
2215 last_peek_offset = 0;
2216 track_widx = track_ridx;
2218 /* Mark all other entries null (also buffered wrong metadata). */
2219 audio_clear_track_entries();
2221 track_widx = (track_widx + 1) & MAX_TRACK_MASK;
2223 audio_fill_file_buffer(false, 0);
2227 static void audio_new_playlist(void)
2229 /* Prepare to start a new fill from the beginning of the playlist */
2230 last_peek_offset = -1;
2231 if (audio_have_tracks())
2233 if (paused)
2234 skipped_during_pause = true;
2235 track_widx = track_ridx;
2236 audio_clear_track_entries();
2238 track_widx = (track_widx + 1) & MAX_TRACK_MASK;
2240 /* Mark the current track as invalid to prevent skipping back to it */
2241 CUR_TI->taginfo_ready = false;
2244 /* Signal the codec to initiate a track change forward */
2245 new_playlist = true;
2246 ci.new_track = 1;
2248 /* Officially playing */
2249 queue_reply(&audio_queue, 1);
2251 audio_fill_file_buffer(false, 0);
2254 /* Called on manual track skip */
2255 static void audio_initiate_track_change(long direction)
2257 logf("audio_initiate_track_change(%ld)", direction);
2259 ci.new_track += direction;
2260 wps_offset -= direction;
2261 if (paused)
2262 skipped_during_pause = true;
2265 /* Called on manual dir skip */
2266 static void audio_initiate_dir_change(long direction)
2268 dir_skip = true;
2269 ci.new_track = direction;
2270 if (paused)
2271 skipped_during_pause = true;
2274 /* Called when PCM track change is complete */
2275 static void audio_finalise_track_change(void)
2277 logf("audio_finalise_track_change");
2279 if (automatic_skip)
2281 wps_offset = 0;
2282 automatic_skip = false;
2284 /* Invalidate prevtrack_id3 */
2285 prevtrack_id3.path[0] = 0;
2287 if (prev_ti && prev_ti->audio_hid < 0)
2289 /* No audio left so we clear all the track info. */
2290 clear_track_info(prev_ti);
2293 if (prev_ti && prev_ti->id3_hid >= 0)
2295 /* Reset the elapsed time to force the progressbar to be empty if
2296 the user skips back to this track */
2297 bufgetid3(prev_ti->id3_hid)->elapsed = 0;
2301 send_event(PLAYBACK_EVENT_TRACK_CHANGE, &curtrack_id3);
2303 track_changed = true;
2304 playlist_update_resume_info(audio_current_track());
2308 * Layout audio buffer as follows - iram buffer depends on target:
2309 * [|SWAP:iram][|TALK]|FILE|GUARD|PCM|[SWAP:dram[|iram]|]
2311 static void audio_reset_buffer(void)
2313 /* see audio_get_recording_buffer if this is modified */
2314 logf("audio_reset_buffer");
2316 /* If the setup of anything allocated before the file buffer is
2317 changed, do check the adjustments after the buffer_alloc call
2318 as it will likely be affected and need sliding over */
2320 /* Initially set up file buffer as all space available */
2321 malloc_buf = audiobuf + talk_get_bufsize();
2322 /* Align the malloc buf to line size. Especially important to cf
2323 targets that do line reads/writes. */
2324 malloc_buf = (unsigned char *)(((uintptr_t)malloc_buf + 15) & ~15);
2325 filebuf = malloc_buf; /* filebuf line align implied */
2326 filebuflen = audiobufend - filebuf;
2328 filebuflen &= ~15;
2330 /* Subtract whatever the pcm buffer says it used plus the guard buffer */
2331 filebuflen -= pcmbuf_init(filebuf + filebuflen) + GUARD_BUFSIZE;
2333 /* Make sure filebuflen is a longword multiple after adjustment - filebuf
2334 will already be line aligned */
2335 filebuflen &= ~3;
2337 buffering_reset(filebuf, filebuflen);
2339 /* Clear any references to the file buffer */
2340 buffer_state = BUFFER_STATE_INITIALIZED;
2342 #if defined(ROCKBOX_HAS_LOGF) && defined(LOGF_ENABLE)
2343 /* Make sure everything adds up - yes, some info is a bit redundant but
2344 aids viewing and the sumation of certain variables should add up to
2345 the location of others. */
2347 size_t pcmbufsize;
2348 const unsigned char *pcmbuf = pcmbuf_get_meminfo(&pcmbufsize);
2349 logf("mabuf: %08X", (unsigned)malloc_buf);
2350 logf("fbuf: %08X", (unsigned)filebuf);
2351 logf("fbufe: %08X", (unsigned)(filebuf + filebuflen));
2352 logf("gbuf: %08X", (unsigned)(filebuf + filebuflen));
2353 logf("gbufe: %08X", (unsigned)(filebuf + filebuflen + GUARD_BUFSIZE));
2354 logf("pcmb: %08X", (unsigned)pcmbuf);
2355 logf("pcmbe: %08X", (unsigned)(pcmbuf + pcmbufsize));
2357 #endif
2360 static void audio_thread(void)
2362 struct queue_event ev;
2364 pcm_postinit();
2366 audio_thread_ready = true;
2368 while (1)
2370 if (filling != STATE_FILLING) {
2371 cancel_cpu_boost();
2374 if (!pcmbuf_queue_scan(&ev))
2375 queue_wait_w_tmo(&audio_queue, &ev, HZ/2);
2377 switch (ev.id) {
2379 case Q_AUDIO_FILL_BUFFER:
2380 LOGFQUEUE("audio < Q_AUDIO_FILL_BUFFER %d", (int)ev.data);
2381 audio_fill_file_buffer((bool)ev.data, 0);
2382 break;
2384 case Q_AUDIO_FINISH_LOAD:
2385 LOGFQUEUE("audio < Q_AUDIO_FINISH_LOAD");
2386 audio_finish_load_track();
2387 break;
2389 case Q_AUDIO_PLAY:
2390 LOGFQUEUE("audio < Q_AUDIO_PLAY");
2391 if (playing && ev.data <= 0)
2392 audio_new_playlist();
2393 else
2395 audio_stop_playback();
2396 audio_play_start((size_t)ev.data);
2398 break;
2400 case Q_AUDIO_STOP:
2401 LOGFQUEUE("audio < Q_AUDIO_STOP");
2402 if (playing)
2403 audio_stop_playback();
2404 if (ev.data != 0)
2405 queue_clear(&audio_queue);
2406 break;
2408 case Q_AUDIO_PAUSE:
2409 LOGFQUEUE("audio < Q_AUDIO_PAUSE");
2410 if (!(bool) ev.data && skipped_during_pause && !pcmbuf_is_crossfade_active())
2411 pcmbuf_play_stop(); /* Flush old track on resume after skip */
2412 skipped_during_pause = false;
2413 if (!playing)
2414 break;
2415 pcmbuf_pause((bool)ev.data);
2416 paused = (bool)ev.data;
2417 break;
2419 case Q_AUDIO_SKIP:
2420 LOGFQUEUE("audio < Q_AUDIO_SKIP");
2421 audio_initiate_track_change((long)ev.data);
2422 break;
2424 case Q_AUDIO_PRE_FF_REWIND:
2425 LOGFQUEUE("audio < Q_AUDIO_PRE_FF_REWIND");
2426 if (!playing)
2427 break;
2428 pcmbuf_pause(true);
2429 break;
2431 case Q_AUDIO_FF_REWIND:
2432 LOGFQUEUE("audio < Q_AUDIO_FF_REWIND");
2433 if (!playing)
2434 break;
2435 if (automatic_skip)
2437 /* An automatic track skip is in progress. Finalize it,
2438 then go back to the previous track */
2439 audio_finalise_track_change();
2440 ci.new_track = -1;
2442 ci.seek_time = (long)ev.data+1;
2443 break;
2445 case Q_AUDIO_CHECK_NEW_TRACK:
2446 LOGFQUEUE("audio < Q_AUDIO_CHECK_NEW_TRACK");
2447 queue_reply(&audio_queue, audio_check_new_track());
2448 break;
2450 case Q_AUDIO_DIR_SKIP:
2451 LOGFQUEUE("audio < Q_AUDIO_DIR_SKIP");
2452 audio_initiate_dir_change(ev.data);
2453 break;
2455 case Q_AUDIO_FLUSH:
2456 LOGFQUEUE("audio < Q_AUDIO_FLUSH");
2457 audio_invalidate_tracks();
2458 break;
2460 case Q_AUDIO_TRACK_CHANGED:
2461 /* PCM track change done */
2462 LOGFQUEUE("audio < Q_AUDIO_TRACK_CHANGED");
2463 audio_finalise_track_change();
2464 break;
2466 #ifndef SIMULATOR
2467 case SYS_USB_CONNECTED:
2468 LOGFQUEUE("audio < SYS_USB_CONNECTED");
2469 if (playing)
2470 audio_stop_playback();
2471 #ifdef PLAYBACK_VOICE
2472 voice_stop();
2473 #endif
2474 usb_acknowledge(SYS_USB_CONNECTED_ACK);
2475 usb_wait_for_disconnect(&audio_queue);
2477 /* Mark all entries null. */
2478 audio_clear_track_entries();
2480 /* release tracks to make sure all handles are closed */
2481 audio_release_tracks();
2482 break;
2483 #endif
2485 case SYS_TIMEOUT:
2486 LOGFQUEUE_SYS_TIMEOUT("audio < SYS_TIMEOUT");
2487 break;
2489 default:
2490 LOGFQUEUE("audio < default");
2491 break;
2492 } /* end switch */
2493 } /* end while */
2496 /* Initialize the audio system - called from init() in main.c.
2497 * Last function because of all the references to internal symbols
2499 void audio_init(void)
2501 struct thread_entry *audio_thread_p;
2503 /* Can never do this twice */
2504 if (audio_is_initialized)
2506 logf("audio: already initialized");
2507 return;
2510 logf("audio: initializing");
2512 /* Initialize queues before giving control elsewhere in case it likes
2513 to send messages. Thread creation will be delayed however so nothing
2514 starts running until ready if something yields such as talk_init. */
2515 queue_init(&audio_queue, true);
2516 queue_init(&codec_queue, false);
2517 queue_init(&pcmbuf_queue, false);
2519 pcm_init();
2521 /* Initialize codec api. */
2522 ci.read_filebuf = codec_filebuf_callback;
2523 ci.pcmbuf_insert = codec_pcmbuf_insert_callback;
2524 ci.codec_get_buffer = codec_get_buffer;
2525 ci.request_buffer = codec_request_buffer_callback;
2526 ci.advance_buffer = codec_advance_buffer_callback;
2527 ci.advance_buffer_loc = codec_advance_buffer_loc_callback;
2528 ci.request_next_track = codec_request_next_track_callback;
2529 ci.seek_buffer = codec_seek_buffer_callback;
2530 ci.seek_complete = codec_seek_complete_callback;
2531 ci.set_elapsed = codec_set_elapsed_callback;
2532 ci.set_offset = codec_set_offset_callback;
2533 ci.configure = codec_configure_callback;
2534 ci.discard_codec = codec_discard_codec_callback;
2535 ci.dsp = (struct dsp_config *)dsp_configure(NULL, DSP_MYDSP,
2536 CODEC_IDX_AUDIO);
2538 /* initialize the buffer */
2539 filebuf = audiobuf;
2541 /* audio_reset_buffer must to know the size of voice buffer so init
2542 talk first */
2543 talk_init();
2545 codec_thread_p = create_thread(
2546 codec_thread, codec_stack, sizeof(codec_stack),
2547 CREATE_THREAD_FROZEN,
2548 codec_thread_name IF_PRIO(, PRIORITY_PLAYBACK)
2549 IF_COP(, CPU));
2551 queue_enable_queue_send(&codec_queue, &codec_queue_sender_list,
2552 codec_thread_p);
2554 audio_thread_p = create_thread(audio_thread, audio_stack,
2555 sizeof(audio_stack), CREATE_THREAD_FROZEN,
2556 audio_thread_name IF_PRIO(, PRIORITY_USER_INTERFACE)
2557 IF_COP(, CPU));
2559 queue_enable_queue_send(&audio_queue, &audio_queue_sender_list,
2560 audio_thread_p);
2562 #ifdef PLAYBACK_VOICE
2563 voice_thread_init();
2564 #endif
2566 /* Set crossfade setting for next buffer init which should be about... */
2567 pcmbuf_crossfade_enable(global_settings.crossfade);
2569 /* initialize the buffering system */
2571 buffering_init();
2572 /* ...now! Set up the buffers */
2573 audio_reset_buffer();
2575 int i;
2576 for(i = 0; i < MAX_TRACK; i++)
2578 tracks[i].audio_hid = -1;
2579 tracks[i].id3_hid = -1;
2580 tracks[i].codec_hid = -1;
2581 #ifdef HAVE_ALBUMART
2582 tracks[i].aa_hid = -1;
2583 #endif
2586 add_event(BUFFER_EVENT_REBUFFER, false, buffering_handle_rebuffer_callback);
2587 add_event(BUFFER_EVENT_FINISHED, false, buffering_handle_finished_callback);
2589 /* Probably safe to say */
2590 audio_is_initialized = true;
2592 sound_settings_apply();
2593 #ifdef HAVE_DISK_STORAGE
2594 audio_set_buffer_margin(global_settings.buffer_margin);
2595 #endif
2597 /* it's safe to let the threads run now */
2598 #ifdef PLAYBACK_VOICE
2599 voice_thread_resume();
2600 #endif
2601 thread_thaw(codec_thread_p);
2602 thread_thaw(audio_thread_p);
2604 } /* audio_init */
2606 bool audio_is_thread_ready(void)
2608 return audio_thread_ready;