Fix 'make fullinstall'
[kugel-rb.git] / apps / playback.c
blobd974480c35f9a5a7d86e2c344867bf16de4dba2d
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 "storage.h"
52 #include "screens.h"
53 #include "playlist.h"
54 #include "playback.h"
55 #include "pcmbuf.h"
56 #include "buffer.h"
57 #include "dsp.h"
58 #include "abrepeat.h"
59 #include "cuesheet.h"
60 #ifdef HAVE_TAGCACHE
61 #include "tagcache.h"
62 #endif
63 #ifdef HAVE_LCD_BITMAP
64 #include "icons.h"
65 #include "peakmeter.h"
66 #include "action.h"
67 #include "albumart.h"
68 #endif
69 #include "lang.h"
70 #include "bookmark.h"
71 #include "misc.h"
72 #include "sound.h"
73 #include "metadata.h"
74 #include "splash.h"
75 #include "talk.h"
76 #include "ata_idle_notify.h"
78 #ifdef HAVE_RECORDING
79 #include "recording.h"
80 #include "talk.h"
81 #include "pcm_record.h"
82 #endif
84 #ifdef IPOD_ACCESSORY_PROTOCOL
85 #include "iap.h"
86 #endif
88 #define PLAYBACK_VOICE
90 /* amount of guess-space to allow for codecs that must hunt and peck
91 * for their correct seeek target, 32k seems a good size */
92 #define AUDIO_REBUFFER_GUESS_SIZE (1024*32)
94 /* Define LOGF_ENABLE to enable logf output in this file */
95 /*#define LOGF_ENABLE*/
96 #include "logf.h"
98 /* macros to enable logf for queues
99 logging on SYS_TIMEOUT can be disabled */
100 #ifdef SIMULATOR
101 /* Define this for logf output of all queuing except SYS_TIMEOUT */
102 #define PLAYBACK_LOGQUEUES
103 /* Define this to logf SYS_TIMEOUT messages */
104 /*#define PLAYBACK_LOGQUEUES_SYS_TIMEOUT*/
105 #endif
107 #ifdef PLAYBACK_LOGQUEUES
108 #define LOGFQUEUE logf
109 #else
110 #define LOGFQUEUE(...)
111 #endif
113 #ifdef PLAYBACK_LOGQUEUES_SYS_TIMEOUT
114 #define LOGFQUEUE_SYS_TIMEOUT logf
115 #else
116 #define LOGFQUEUE_SYS_TIMEOUT(...)
117 #endif
120 /* Define one constant that includes recording related functionality */
121 #if defined(HAVE_RECORDING) && !defined(SIMULATOR)
122 #define AUDIO_HAVE_RECORDING
123 #endif
125 enum {
126 Q_NULL = 0,
127 Q_AUDIO_PLAY = 1,
128 Q_AUDIO_STOP,
129 Q_AUDIO_PAUSE,
130 Q_AUDIO_SKIP,
131 Q_AUDIO_PRE_FF_REWIND,
132 Q_AUDIO_FF_REWIND,
133 Q_AUDIO_CHECK_NEW_TRACK,
134 Q_AUDIO_FLUSH,
135 Q_AUDIO_TRACK_CHANGED,
136 Q_AUDIO_DIR_SKIP,
137 Q_AUDIO_POSTINIT,
138 Q_AUDIO_FILL_BUFFER,
139 Q_AUDIO_FINISH_LOAD,
140 Q_CODEC_REQUEST_COMPLETE,
141 Q_CODEC_REQUEST_FAILED,
143 Q_CODEC_LOAD,
144 Q_CODEC_LOAD_DISK,
146 #ifdef AUDIO_HAVE_RECORDING
147 Q_ENCODER_LOAD_DISK,
148 Q_ENCODER_RECORD,
149 #endif
151 Q_CODEC_DO_CALLBACK,
154 enum filling_state {
155 STATE_IDLE, /* audio is stopped: nothing to do */
156 STATE_FILLING, /* adding tracks to the buffer */
157 STATE_FULL, /* can't add any more tracks */
158 STATE_END_OF_PLAYLIST, /* all remaining tracks have been added */
159 STATE_FINISHED, /* all remaining tracks are fully buffered */
162 #define MAX_TRACK 128
164 #define MAX_TRACK_MASK (MAX_TRACK-1)
166 /* As defined in plugins/lib/xxx2wav.h */
167 #define GUARD_BUFSIZE (32*1024)
169 /* As defined in plugin.lds */
170 #if defined(CPU_PP)
171 #define CODEC_IRAM_ORIGIN ((unsigned char *)0x4000c000)
172 #define CODEC_IRAM_SIZE ((size_t)0xc000)
173 #elif defined(IAUDIO_X5) || defined(IAUDIO_M5)
174 #define CODEC_IRAM_ORIGIN ((unsigned char *)0x10010000)
175 #define CODEC_IRAM_SIZE ((size_t)0x10000)
176 #else
177 #define CODEC_IRAM_ORIGIN ((unsigned char *)0x1000c000)
178 #define CODEC_IRAM_SIZE ((size_t)0xc000)
179 #endif
181 bool audio_is_initialized = false;
182 static bool audio_thread_ready SHAREDBSS_ATTR = false;
184 /* Variables are commented with the threads that use them: *
185 * A=audio, C=codec, V=voice. A suffix of - indicates that *
186 * the variable is read but not updated on that thread. */
187 /* TBD: Split out "audio" and "playback" (ie. calling) threads */
189 /* Main state control */
190 static volatile bool audio_codec_loaded SHAREDBSS_ATTR = false; /* Codec loaded? (C/A-) */
191 static volatile bool playing SHAREDBSS_ATTR = false; /* Is audio playing? (A) */
192 static volatile bool paused SHAREDBSS_ATTR = false; /* Is audio paused? (A/C-) */
194 /* Ring buffer where compressed audio and codecs are loaded */
195 static unsigned char *filebuf = NULL; /* Start of buffer (A/C-) */
196 static unsigned char *malloc_buf = NULL; /* Start of malloc buffer (A/C-) */
197 /* FIXME: make filebuflen static */
198 size_t filebuflen = 0; /* Size of buffer (A/C-) */
199 /* FIXME: make buf_ridx (C/A-) */
201 /* Possible arrangements of the buffer */
202 static int buffer_state = AUDIOBUF_STATE_TRASHED; /* Buffer state */
204 /* These are used to store the current and next (or prev if the current is the last)
205 * mp3entry's in a round-robin system. This guarentees that the pointer returned
206 * by audio_current/next_track will be valid for the full duration of the
207 * currently playing track */
208 static struct mp3entry mp3entry_buf[2];
209 static struct mp3entry *thistrack_id3, /* the currently playing track */
210 *othertrack_id3; /* prev track during track-change-transition, or end of playlist,
211 * next track otherwise */
212 static struct mp3entry unbuffered_id3; /* the id3 for the first unbuffered track */
214 /* Track info structure about songs in the file buffer (A/C-) */
215 struct track_info {
216 int audio_hid; /* The ID for the track's buffer handle */
217 int id3_hid; /* The ID for the track's metadata handle */
218 int codec_hid; /* The ID for the track's codec handle */
219 #ifdef HAVE_ALBUMART
220 int aa_hid; /* The ID for the track's album art handle */
221 #endif
223 size_t filesize; /* File total length */
225 bool taginfo_ready; /* Is metadata read */
228 static struct track_info tracks[MAX_TRACK];
229 static volatile int track_ridx = 0; /* Track being decoded (A/C-) */
230 static int track_widx = 0; /* Track being buffered (A) */
232 #define CUR_TI (&tracks[track_ridx]) /* Playing track info pointer (A/C-) */
233 static struct track_info *prev_ti = NULL; /* Pointer to the previously played
234 track */
236 /* Information used only for filling the buffer */
237 /* Playlist steps from playing track to next track to be buffered (A) */
238 static int last_peek_offset = 0;
240 /* Scrobbler support */
241 static unsigned long prev_track_elapsed = 0; /* Previous track elapsed time (C/A-)*/
243 static enum filling_state filling;
245 /* Track change controls */
246 static bool automatic_skip = false; /* Who initiated in-progress skip? (C/A-) */
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 static bool start_play_g = false; /* Used by audio_load_track to notify
253 audio_finish_load_track about start_play */
255 /* True when a track load is in progress, i.e. audio_load_track() has returned
256 * but audio_finish_load_track() hasn't been called yet. Used to avoid allowing
257 * audio_load_track() to get called twice in a row, which would cause problems.
259 static bool track_load_started = false;
261 /* Set to true if the codec thread should send an audio stop request
262 * (typically because the end of the playlist has been reached).
264 static bool codec_requested_stop = false;
266 #ifdef HAVE_DISK_STORAGE
267 static size_t buffer_margin = 0; /* Buffer margin aka anti-skip buffer (A/C-) */
268 #endif
270 /* Multiple threads */
271 /* Set the watermark to trigger buffer fill (A/C) */
272 static void set_filebuf_watermark(void);
274 /* Audio thread */
275 static struct event_queue audio_queue SHAREDBSS_ATTR;
276 static struct queue_sender_list audio_queue_sender_list SHAREDBSS_ATTR;
277 static long audio_stack[(DEFAULT_STACK_SIZE + 0x1000)/sizeof(long)];
278 static const char audio_thread_name[] = "audio";
280 static void audio_thread(void);
281 static void audio_initiate_track_change(long direction);
282 static bool audio_have_tracks(void);
283 static void audio_reset_buffer(void);
284 static void audio_stop_playback(void);
286 /* Codec thread */
287 extern struct codec_api ci;
288 static struct event_queue codec_queue SHAREDBSS_ATTR;
289 static struct queue_sender_list codec_queue_sender_list;
290 static long codec_stack[(DEFAULT_STACK_SIZE + 0x2000)/sizeof(long)]
291 IBSS_ATTR;
292 static const char codec_thread_name[] = "codec";
293 unsigned int codec_thread_id; /* For modifying thread priority later. */
295 /* PCM buffer messaging */
296 static struct event_queue pcmbuf_queue SHAREDBSS_ATTR;
298 /* Function to be called by pcm buffer callbacks.
299 * Permissible Context(s): Audio interrupt
301 static void pcmbuf_callback_queue_post(long id, intptr_t data)
303 /* No lock since we're already in audio interrupt context */
304 queue_post(&pcmbuf_queue, id, data);
307 /* Scan the pcmbuf queue and return true if a message pulled.
308 * Permissible Context(s): Thread
310 static bool pcmbuf_queue_scan(struct queue_event *ev)
312 if (!queue_empty(&pcmbuf_queue))
314 /* Transfer message to audio queue */
315 pcm_play_lock();
316 /* Pull message - never, ever any blocking call! */
317 queue_wait_w_tmo(&pcmbuf_queue, ev, 0);
318 pcm_play_unlock();
319 return true;
322 return false;
325 /* Clear the pcmbuf queue of messages
326 * Permissible Context(s): Thread
328 static void pcmbuf_queue_clear(void)
330 pcm_play_lock();
331 queue_clear(&pcmbuf_queue);
332 pcm_play_unlock();
335 /* --- Helper functions --- */
337 static struct mp3entry *bufgetid3(int handle_id)
339 if (handle_id < 0)
340 return NULL;
342 struct mp3entry *id3;
343 ssize_t ret = bufgetdata(handle_id, 0, (void *)&id3);
345 if (ret < 0 || ret != sizeof(struct mp3entry))
346 return NULL;
348 return id3;
351 static bool clear_track_info(struct track_info *track)
353 /* bufclose returns true if the handle is not found, or if it is closed
354 * successfully, so these checks are safe on non-existant handles */
355 if (!track)
356 return false;
358 if (track->codec_hid >= 0) {
359 if (bufclose(track->codec_hid))
360 track->codec_hid = -1;
361 else
362 return false;
365 if (track->id3_hid >= 0) {
366 if (bufclose(track->id3_hid))
367 track->id3_hid = -1;
368 else
369 return false;
372 if (track->audio_hid >= 0) {
373 if (bufclose(track->audio_hid))
374 track->audio_hid = -1;
375 else
376 return false;
379 #ifdef HAVE_ALBUMART
380 if (track->aa_hid >= 0) {
381 if (bufclose(track->aa_hid))
382 track->aa_hid = -1;
383 else
384 return false;
386 #endif
388 track->filesize = 0;
389 track->taginfo_ready = false;
391 return true;
394 /* --- External interfaces --- */
396 /* This sends a stop message and the audio thread will dump all it's
397 subsequenct messages */
398 void audio_hard_stop(void)
400 /* Stop playback */
401 LOGFQUEUE("audio >| audio Q_AUDIO_STOP: 1");
402 queue_send(&audio_queue, Q_AUDIO_STOP, 1);
403 #ifdef PLAYBACK_VOICE
404 voice_stop();
405 #endif
408 bool audio_restore_playback(int type)
410 switch (type)
412 case AUDIO_WANT_PLAYBACK:
413 if (buffer_state != AUDIOBUF_STATE_INITIALIZED)
414 audio_reset_buffer();
415 return true;
416 case AUDIO_WANT_VOICE:
417 if (buffer_state == AUDIOBUF_STATE_TRASHED)
418 audio_reset_buffer();
419 return true;
420 default:
421 return false;
425 unsigned char *audio_get_buffer(bool talk_buf, size_t *buffer_size)
427 unsigned char *buf, *end;
429 if (audio_is_initialized)
431 audio_hard_stop();
433 /* else buffer_state will be AUDIOBUF_STATE_TRASHED at this point */
435 /* Reset the buffering thread so that it doesn't try to use the data */
436 buffering_reset(filebuf, filebuflen);
438 if (buffer_size == NULL)
440 /* Special case for talk_init to use since it already knows it's
441 trashed */
442 buffer_state = AUDIOBUF_STATE_TRASHED;
443 return NULL;
446 if (talk_buf || buffer_state == AUDIOBUF_STATE_TRASHED
447 || !talk_voice_required())
449 logf("get buffer: talk, audio");
450 /* Ok to use everything from audiobuf to audiobufend - voice is loaded,
451 the talk buffer is not needed because voice isn't being used, or
452 could be AUDIOBUF_STATE_TRASHED already. If state is
453 AUDIOBUF_STATE_VOICED_ONLY, no problem as long as memory isn't written
454 without the caller knowing what's going on. Changing certain settings
455 may move it to a worse condition but the memory in use by something
456 else will remain undisturbed.
458 if (buffer_state != AUDIOBUF_STATE_TRASHED)
460 talk_buffer_steal();
461 buffer_state = AUDIOBUF_STATE_TRASHED;
464 buf = audiobuf;
465 end = audiobufend;
467 else
469 /* Safe to just return this if already AUDIOBUF_STATE_VOICED_ONLY or
470 still AUDIOBUF_STATE_INITIALIZED */
471 /* Skip talk buffer and move pcm buffer to end to maximize available
472 contiguous memory - no audio running means voice will not need the
473 swap space */
474 logf("get buffer: audio");
475 buf = audiobuf + talk_get_bufsize();
476 end = audiobufend - pcmbuf_init(audiobufend);
477 buffer_state = AUDIOBUF_STATE_VOICED_ONLY;
480 *buffer_size = end - buf;
482 return buf;
485 int audio_buffer_state(void)
487 return buffer_state;
490 #ifdef HAVE_RECORDING
491 unsigned char *audio_get_recording_buffer(size_t *buffer_size)
493 /* Stop audio, voice and obtain all available buffer space */
494 audio_hard_stop();
495 talk_buffer_steal();
497 unsigned char *end = audiobufend;
498 buffer_state = AUDIOBUF_STATE_TRASHED;
499 *buffer_size = end - audiobuf;
501 return (unsigned char *)audiobuf;
504 bool audio_load_encoder(int afmt)
506 #ifndef SIMULATOR
507 const char *enc_fn = get_codec_filename(afmt | CODEC_TYPE_ENCODER);
508 if (!enc_fn)
509 return false;
511 audio_remove_encoder();
512 ci.enc_codec_loaded = 0; /* clear any previous error condition */
514 LOGFQUEUE("codec > Q_ENCODER_LOAD_DISK");
515 queue_post(&codec_queue, Q_ENCODER_LOAD_DISK, (intptr_t)enc_fn);
517 while (ci.enc_codec_loaded == 0)
518 yield();
520 logf("codec loaded: %d", ci.enc_codec_loaded);
522 return ci.enc_codec_loaded > 0;
523 #else
524 (void)afmt;
525 return true;
526 #endif
527 } /* audio_load_encoder */
529 void audio_remove_encoder(void)
531 #ifndef SIMULATOR
532 /* force encoder codec unload (if currently loaded) */
533 if (ci.enc_codec_loaded <= 0)
534 return;
536 ci.stop_encoder = true;
537 while (ci.enc_codec_loaded > 0)
538 yield();
539 #endif
540 } /* audio_remove_encoder */
542 #endif /* HAVE_RECORDING */
544 #ifdef HAVE_ALBUMART
545 int audio_current_aa_hid(void)
547 int cur_idx;
548 int offset = ci.new_track + wps_offset;
550 cur_idx = track_ridx + offset;
551 cur_idx &= MAX_TRACK_MASK;
553 return tracks[cur_idx].aa_hid;
555 #endif
557 struct mp3entry* audio_current_track(void)
559 const char *filename;
560 static struct mp3entry temp_id3;
561 struct playlist_track_info trackinfo;
562 int cur_idx;
563 int offset = ci.new_track + wps_offset;
565 cur_idx = (track_ridx + offset) & MAX_TRACK_MASK;
567 if (cur_idx == track_ridx && *thistrack_id3->path)
569 /* The usual case */
570 return thistrack_id3;
572 else if (automatic_skip && offset == -1 && *othertrack_id3->path)
574 /* We're in a track transition. The codec has moved on to the next track,
575 but the audio being played is still the same (now previous) track.
576 othertrack_id3.elapsed is being updated in an ISR by
577 codec_pcmbuf_position_callback */
578 return othertrack_id3;
580 else if (tracks[cur_idx].id3_hid >= 0)
582 /* The current track's info has been buffered but not read yet, so get it */
583 if (bufread(tracks[cur_idx].id3_hid, sizeof(struct mp3entry), &temp_id3)
584 == sizeof(struct mp3entry))
585 return &temp_id3;
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 && *thistrack_id3->path)
623 /* We're in a track transition. The next track for the WPS is the one
624 currently being decoded. */
625 return thistrack_id3;
628 next_idx = (track_ridx + offset + 1) & MAX_TRACK_MASK;
630 if (tracks[next_idx].id3_hid >= 0)
632 if (bufread(tracks[next_idx].id3_hid, sizeof(struct mp3entry), othertrack_id3)
633 == sizeof(struct mp3entry))
634 return othertrack_id3;
635 else
636 return NULL;
639 if (next_idx == track_widx)
641 /* The next track hasn't been buffered yet, so we return the static
642 version of its metadata. */
643 return &unbuffered_id3;
646 return NULL;
649 void audio_play(long offset)
651 logf("audio_play");
653 #ifdef PLAYBACK_VOICE
654 /* Truncate any existing voice output so we don't have spelling
655 * etc. over the first part of the played track */
656 talk_force_shutup();
657 #endif
659 /* Start playback */
660 LOGFQUEUE("audio >| audio Q_AUDIO_PLAY: %ld", offset);
661 /* Don't return until playback has actually started */
662 queue_send(&audio_queue, Q_AUDIO_PLAY, offset);
665 void audio_stop(void)
667 /* Stop playback */
668 LOGFQUEUE("audio >| audio Q_AUDIO_STOP");
669 /* Don't return until playback has actually stopped */
670 queue_send(&audio_queue, Q_AUDIO_STOP, 0);
673 void audio_pause(void)
675 LOGFQUEUE("audio >| audio Q_AUDIO_PAUSE");
676 /* Don't return until playback has actually paused */
677 queue_send(&audio_queue, Q_AUDIO_PAUSE, true);
680 void audio_resume(void)
682 LOGFQUEUE("audio >| audio Q_AUDIO_PAUSE resume");
683 /* Don't return until playback has actually resumed */
684 queue_send(&audio_queue, Q_AUDIO_PAUSE, false);
687 void audio_skip(int direction)
689 if (playlist_check(ci.new_track + wps_offset + direction))
691 if (global_settings.beep)
692 pcmbuf_beep(2000, 100, 2500*global_settings.beep);
694 LOGFQUEUE("audio > audio Q_AUDIO_SKIP %d", direction);
695 queue_post(&audio_queue, Q_AUDIO_SKIP, direction);
696 /* Update wps while our message travels inside deep playback queues. */
697 wps_offset += direction;
699 else
701 /* No more tracks. */
702 if (global_settings.beep)
703 pcmbuf_beep(1000, 100, 1500*global_settings.beep);
707 void audio_next(void)
709 audio_skip(1);
712 void audio_prev(void)
714 audio_skip(-1);
717 void audio_next_dir(void)
719 LOGFQUEUE("audio > audio Q_AUDIO_DIR_SKIP 1");
720 queue_post(&audio_queue, Q_AUDIO_DIR_SKIP, 1);
723 void audio_prev_dir(void)
725 LOGFQUEUE("audio > audio Q_AUDIO_DIR_SKIP -1");
726 queue_post(&audio_queue, Q_AUDIO_DIR_SKIP, -1);
729 void audio_pre_ff_rewind(void)
731 LOGFQUEUE("audio > audio Q_AUDIO_PRE_FF_REWIND");
732 queue_post(&audio_queue, Q_AUDIO_PRE_FF_REWIND, 0);
735 void audio_ff_rewind(long newpos)
737 LOGFQUEUE("audio > audio Q_AUDIO_FF_REWIND");
738 queue_post(&audio_queue, Q_AUDIO_FF_REWIND, newpos);
741 void audio_flush_and_reload_tracks(void)
743 LOGFQUEUE("audio > audio Q_AUDIO_FLUSH");
744 queue_post(&audio_queue, Q_AUDIO_FLUSH, 0);
747 void audio_error_clear(void)
749 #ifdef AUDIO_HAVE_RECORDING
750 pcm_rec_error_clear();
751 #endif
754 int audio_status(void)
756 int ret = 0;
758 if (playing)
759 ret |= AUDIO_STATUS_PLAY;
761 if (paused)
762 ret |= AUDIO_STATUS_PAUSE;
764 #ifdef HAVE_RECORDING
765 /* Do this here for constitency with mpeg.c version */
766 ret |= pcm_rec_status();
767 #endif
769 return ret;
772 int audio_get_file_pos(void)
774 return 0;
777 #ifdef HAVE_DISK_STORAGE
778 void audio_set_buffer_margin(int setting)
780 static const int lookup[] = {5, 15, 30, 60, 120, 180, 300, 600};
781 buffer_margin = lookup[setting];
782 logf("buffer margin: %ld", (long)buffer_margin);
783 set_filebuf_watermark();
785 #endif
787 /* Take necessary steps to enable or disable the crossfade setting */
788 void audio_set_crossfade(int enable)
790 size_t offset;
791 bool was_playing;
792 size_t size;
794 /* Tell it the next setting to use */
795 pcmbuf_crossfade_enable(enable);
797 /* Return if size hasn't changed or this is too early to determine
798 which in the second case there's no way we could be playing
799 anything at all */
800 if (pcmbuf_is_same_size())
802 /* This function is a copout and just syncs some variables -
803 to be removed at a later date */
804 pcmbuf_crossfade_enable_finished();
805 return;
808 offset = 0;
809 was_playing = playing;
811 /* Playback has to be stopped before changing the buffer size */
812 if (was_playing)
814 /* Store the track resume position */
815 offset = thistrack_id3->offset;
818 /* Blast it - audio buffer will have to be setup again next time
819 something plays */
820 audio_get_buffer(true, &size);
822 /* Restart playback if audio was running previously */
823 if (was_playing)
824 audio_play(offset);
827 /* --- Routines called from multiple threads --- */
829 static void set_filebuf_watermark(void)
831 if (!filebuf)
832 return; /* Audio buffers not yet set up */
834 #ifdef HAVE_FLASH_STORAGE
835 int seconds = 1;
836 #else
837 int seconds;
838 int spinup = ata_spinup_time();
839 if (spinup)
840 seconds = (spinup / HZ) + 1;
841 else
842 seconds = 5;
843 #endif
845 /* bitrate of last track in buffer dictates watermark */
846 struct mp3entry* id3 = NULL;
847 if (tracks[track_widx].taginfo_ready)
848 id3 = bufgetid3(tracks[track_widx].id3_hid);
849 else
850 id3 = bufgetid3(tracks[track_widx-1].id3_hid);
851 if (!id3) {
852 logf("fwmark: No id3 for last track (r%d/w%d), aborting!", track_ridx, track_widx);
853 return;
855 size_t bytes = id3->bitrate * (1000/8) * seconds;
856 buf_set_watermark(bytes);
857 logf("fwmark: %d", bytes);
860 const char *get_codec_filename(int cod_spec)
862 const char *fname;
864 #ifdef HAVE_RECORDING
865 /* Can choose decoder or encoder if one available */
866 int type = cod_spec & CODEC_TYPE_MASK;
867 int afmt = cod_spec & CODEC_AFMT_MASK;
869 if ((unsigned)afmt >= AFMT_NUM_CODECS)
870 type = AFMT_UNKNOWN | (type & CODEC_TYPE_MASK);
872 fname = (type == CODEC_TYPE_ENCODER) ?
873 audio_formats[afmt].codec_enc_root_fn :
874 audio_formats[afmt].codec_root_fn;
876 logf("%s: %d - %s",
877 (type == CODEC_TYPE_ENCODER) ? "Encoder" : "Decoder",
878 afmt, fname ? fname : "<unknown>");
879 #else /* !HAVE_RECORDING */
880 /* Always decoder */
881 if ((unsigned)cod_spec >= AFMT_NUM_CODECS)
882 cod_spec = AFMT_UNKNOWN;
883 fname = audio_formats[cod_spec].codec_root_fn;
884 logf("Codec: %d - %s", cod_spec, fname ? fname : "<unknown>");
885 #endif /* HAVE_RECORDING */
887 return fname;
888 } /* get_codec_filename */
890 /* --- Codec thread --- */
891 static bool codec_pcmbuf_insert_callback(
892 const void *ch1, const void *ch2, int count)
894 const char *src[2] = { ch1, ch2 };
896 while (count > 0)
898 int out_count = dsp_output_count(ci.dsp, count);
899 int inp_count;
900 char *dest;
902 /* Prevent audio from a previous track from playing */
903 if (ci.new_track || ci.stop_codec)
904 return true;
906 while ((dest = pcmbuf_request_buffer(&out_count)) == NULL)
908 cancel_cpu_boost();
909 sleep(1);
910 if (ci.seek_time || ci.new_track || ci.stop_codec)
911 return true;
914 /* Get the real input_size for output_size bytes, guarding
915 * against resampling buffer overflows. */
916 inp_count = dsp_input_count(ci.dsp, out_count);
918 if (inp_count <= 0)
919 return true;
921 /* Input size has grown, no error, just don't write more than length */
922 if (inp_count > count)
923 inp_count = count;
925 out_count = dsp_process(ci.dsp, dest, src, inp_count);
927 if (out_count <= 0)
928 return true;
930 pcmbuf_write_complete(out_count);
932 count -= inp_count;
935 return true;
936 } /* codec_pcmbuf_insert_callback */
938 static void* codec_get_buffer(size_t *size)
940 if (codec_size >= CODEC_SIZE)
941 return NULL;
942 *size = CODEC_SIZE - codec_size;
943 return &codecbuf[codec_size];
946 /* Between the codec and PCM track change, we need to keep updating the
947 "elapsed" value of the previous (to the codec, but current to the
948 user/PCM/WPS) track, so that the progressbar reaches the end.
949 During that transition, the WPS will display prevtrack_id3. */
950 static void codec_pcmbuf_position_callback(size_t size) ICODE_ATTR;
951 static void codec_pcmbuf_position_callback(size_t size)
953 /* This is called from an ISR, so be quick */
954 unsigned int time = size * 1000 / 4 / NATIVE_FREQUENCY +
955 othertrack_id3->elapsed;
957 if (time >= othertrack_id3->length)
959 pcmbuf_set_position_callback(NULL);
960 othertrack_id3->elapsed = othertrack_id3->length;
962 else
963 othertrack_id3->elapsed = time;
966 static void codec_set_elapsed_callback(unsigned int value)
968 unsigned int latency;
969 if (ci.seek_time)
970 return;
972 #ifdef AB_REPEAT_ENABLE
973 ab_position_report(value);
974 #endif
976 latency = pcmbuf_get_latency();
977 if (value < latency)
978 thistrack_id3->elapsed = 0;
979 else if (value - latency > thistrack_id3->elapsed ||
980 value - latency < thistrack_id3->elapsed - 2)
982 thistrack_id3->elapsed = value - latency;
986 static void codec_set_offset_callback(size_t value)
988 unsigned int latency;
990 if (ci.seek_time)
991 return;
993 latency = pcmbuf_get_latency() * thistrack_id3->bitrate / 8;
994 if (value < latency)
995 thistrack_id3->offset = 0;
996 else
997 thistrack_id3->offset = value - latency;
1000 static void codec_advance_buffer_counters(size_t amount)
1002 bufadvance(CUR_TI->audio_hid, amount);
1003 ci.curpos += amount;
1006 /* copy up-to size bytes into ptr and return the actual size copied */
1007 static size_t codec_filebuf_callback(void *ptr, size_t size)
1009 ssize_t copy_n;
1011 if (ci.stop_codec || !playing)
1012 return 0;
1014 copy_n = bufread(CUR_TI->audio_hid, size, ptr);
1016 /* Nothing requested OR nothing left */
1017 if (copy_n == 0)
1018 return 0;
1020 /* Update read and other position pointers */
1021 codec_advance_buffer_counters(copy_n);
1023 /* Return the actual amount of data copied to the buffer */
1024 return copy_n;
1025 } /* codec_filebuf_callback */
1027 static void* codec_request_buffer_callback(size_t *realsize, size_t reqsize)
1029 size_t copy_n = reqsize;
1030 ssize_t ret;
1031 void *ptr;
1033 if (!playing)
1035 *realsize = 0;
1036 return NULL;
1039 ret = bufgetdata(CUR_TI->audio_hid, reqsize, &ptr);
1040 if (ret >= 0)
1041 copy_n = MIN((size_t)ret, reqsize);
1043 if (copy_n == 0)
1045 *realsize = 0;
1046 return NULL;
1049 *realsize = copy_n;
1051 return ptr;
1052 } /* codec_request_buffer_callback */
1054 static int get_codec_base_type(int type)
1056 switch (type) {
1057 case AFMT_MPA_L1:
1058 case AFMT_MPA_L2:
1059 case AFMT_MPA_L3:
1060 return AFMT_MPA_L3;
1063 return type;
1066 static void codec_advance_buffer_callback(size_t amount)
1068 codec_advance_buffer_counters(amount);
1069 codec_set_offset_callback(ci.curpos);
1072 static void codec_advance_buffer_loc_callback(void *ptr)
1074 size_t amount = buf_get_offset(CUR_TI->audio_hid, ptr);
1075 codec_advance_buffer_callback(amount);
1078 static void codec_seek_complete_callback(void)
1080 logf("seek_complete");
1081 if (pcm_is_paused())
1083 /* If this is not a seamless seek, clear the buffer */
1084 pcmbuf_play_stop();
1085 dsp_configure(ci.dsp, DSP_FLUSH, 0);
1087 /* If playback was not 'deliberately' paused, unpause now */
1088 if (!paused)
1089 pcmbuf_pause(false);
1091 ci.seek_time = 0;
1094 static bool codec_seek_buffer_callback(size_t newpos)
1096 logf("codec_seek_buffer_callback");
1098 int ret = bufseek(CUR_TI->audio_hid, newpos);
1099 if (ret == 0) {
1100 ci.curpos = newpos;
1101 return true;
1103 else {
1104 return false;
1108 static void codec_configure_callback(int setting, intptr_t value)
1110 switch (setting) {
1111 default:
1112 if (!dsp_configure(ci.dsp, setting, value))
1113 { logf("Illegal key:%d", setting); }
1117 static void codec_track_changed(void)
1119 LOGFQUEUE("codec > audio Q_AUDIO_TRACK_CHANGED");
1120 queue_post(&audio_queue, Q_AUDIO_TRACK_CHANGED, 0);
1123 static void codec_pcmbuf_track_changed_callback(void)
1125 pcmbuf_set_position_callback(NULL);
1126 pcmbuf_callback_queue_post(Q_AUDIO_TRACK_CHANGED, 0);
1129 static void codec_discard_codec_callback(void)
1131 if (CUR_TI->codec_hid >= 0)
1133 bufclose(CUR_TI->codec_hid);
1134 CUR_TI->codec_hid = -1;
1138 static inline void codec_gapless_track_change(void)
1140 /* callback keeps the progress bar moving while the pcmbuf empties */
1141 pcmbuf_set_position_callback(codec_pcmbuf_position_callback);
1142 /* set the pcmbuf callback for when the track really changes */
1143 pcmbuf_set_event_handler(codec_pcmbuf_track_changed_callback);
1146 static inline void codec_crossfade_track_change(void)
1148 /* Initiate automatic crossfade mode */
1149 pcmbuf_crossfade_init(false);
1150 /* Notify the wps that the track change starts now */
1151 codec_track_changed();
1154 static void codec_track_skip_done(bool was_manual)
1156 /* Manual track change (always crossfade or flush audio). */
1157 if (was_manual)
1159 pcmbuf_crossfade_init(true);
1160 LOGFQUEUE("codec > audio Q_AUDIO_TRACK_CHANGED");
1161 queue_post(&audio_queue, Q_AUDIO_TRACK_CHANGED, 0);
1163 /* Automatic track change w/crossfade, if not in "Track Skip Only" mode. */
1164 else if (pcmbuf_is_crossfade_enabled() && !pcmbuf_is_crossfade_active()
1165 && global_settings.crossfade != CROSSFADE_ENABLE_TRACKSKIP)
1167 if (global_settings.crossfade == CROSSFADE_ENABLE_SHUFFLE_AND_TRACKSKIP)
1169 if (global_settings.playlist_shuffle)
1170 /* shuffle mode is on, so crossfade: */
1171 codec_crossfade_track_change();
1172 else
1173 /* shuffle mode is off, so do a gapless track change */
1174 codec_gapless_track_change();
1176 else
1177 /* normal crossfade: */
1178 codec_crossfade_track_change();
1180 else
1181 /* normal gapless playback. */
1182 codec_gapless_track_change();
1185 static bool codec_load_next_track(void)
1187 intptr_t result = Q_CODEC_REQUEST_FAILED;
1189 prev_track_elapsed = thistrack_id3->elapsed;
1191 #ifdef AB_REPEAT_ENABLE
1192 ab_end_of_track_report();
1193 #endif
1195 logf("Request new track");
1197 if (ci.new_track == 0)
1199 ci.new_track++;
1200 automatic_skip = true;
1203 if (!ci.stop_codec)
1205 trigger_cpu_boost();
1206 LOGFQUEUE("codec >| audio Q_AUDIO_CHECK_NEW_TRACK");
1207 result = queue_send(&audio_queue, Q_AUDIO_CHECK_NEW_TRACK, 0);
1210 switch (result)
1212 case Q_CODEC_REQUEST_COMPLETE:
1213 LOGFQUEUE("codec |< Q_CODEC_REQUEST_COMPLETE");
1214 codec_track_skip_done(!automatic_skip);
1215 return true;
1217 case Q_CODEC_REQUEST_FAILED:
1218 LOGFQUEUE("codec |< Q_CODEC_REQUEST_FAILED");
1219 ci.new_track = 0;
1220 ci.stop_codec = true;
1221 codec_requested_stop = true;
1222 return false;
1224 default:
1225 LOGFQUEUE("codec |< default");
1226 ci.stop_codec = true;
1227 codec_requested_stop = true;
1228 return false;
1232 static bool codec_request_next_track_callback(void)
1234 int prev_codectype;
1236 if (ci.stop_codec || !playing)
1237 return false;
1239 prev_codectype = get_codec_base_type(thistrack_id3->codectype);
1240 if (!codec_load_next_track())
1241 return false;
1243 /* Seek to the beginning of the new track because if the struct
1244 mp3entry was buffered, "elapsed" might not be zero (if the track has
1245 been played already but not unbuffered) */
1246 codec_seek_buffer_callback(thistrack_id3->first_frame_offset);
1247 /* Check if the next codec is the same file. */
1248 if (prev_codectype == get_codec_base_type(thistrack_id3->codectype))
1250 logf("New track loaded");
1251 codec_discard_codec_callback();
1252 return true;
1254 else
1256 logf("New codec:%d/%d", thistrack_id3->codectype, prev_codectype);
1257 return false;
1261 static void codec_thread(void)
1263 struct queue_event ev;
1264 int status;
1266 while (1) {
1267 status = 0;
1269 if (!pcmbuf_is_crossfade_active()) {
1270 cancel_cpu_boost();
1273 queue_wait(&codec_queue, &ev);
1274 codec_requested_stop = false;
1276 switch (ev.id) {
1277 case Q_CODEC_LOAD_DISK:
1278 LOGFQUEUE("codec < Q_CODEC_LOAD_DISK");
1279 queue_reply(&codec_queue, 1);
1280 audio_codec_loaded = true;
1281 ci.stop_codec = false;
1282 status = codec_load_file((const char *)ev.data, &ci);
1283 LOGFQUEUE("codec_load_file %s %d\n", (const char *)ev.data, status);
1284 break;
1286 case Q_CODEC_LOAD:
1287 LOGFQUEUE("codec < Q_CODEC_LOAD");
1288 if (CUR_TI->codec_hid < 0) {
1289 logf("Codec slot is empty!");
1290 /* Wait for the pcm buffer to go empty */
1291 while (pcm_is_playing())
1292 yield();
1293 /* This must be set to prevent an infinite loop */
1294 ci.stop_codec = true;
1295 LOGFQUEUE("codec > codec Q_AUDIO_PLAY");
1296 queue_post(&codec_queue, Q_AUDIO_PLAY, 0);
1297 break;
1300 audio_codec_loaded = true;
1301 ci.stop_codec = false;
1302 status = codec_load_buf(CUR_TI->codec_hid, &ci);
1303 LOGFQUEUE("codec_load_buf %d\n", status);
1304 break;
1306 case Q_CODEC_DO_CALLBACK:
1307 LOGFQUEUE("codec < Q_CODEC_DO_CALLBACK");
1308 queue_reply(&codec_queue, 1);
1309 if ((void*)ev.data != NULL)
1311 cpucache_invalidate();
1312 ((void (*)(void))ev.data)();
1313 cpucache_flush();
1315 break;
1317 #ifdef AUDIO_HAVE_RECORDING
1318 case Q_ENCODER_LOAD_DISK:
1319 LOGFQUEUE("codec < Q_ENCODER_LOAD_DISK");
1320 audio_codec_loaded = false; /* Not audio codec! */
1321 logf("loading encoder");
1322 ci.stop_encoder = false;
1323 status = codec_load_file((const char *)ev.data, &ci);
1324 logf("encoder stopped");
1325 break;
1326 #endif /* AUDIO_HAVE_RECORDING */
1328 default:
1329 LOGFQUEUE("codec < default");
1332 if (audio_codec_loaded)
1334 if (ci.stop_codec)
1336 status = CODEC_OK;
1337 if (!playing)
1338 pcmbuf_play_stop();
1341 audio_codec_loaded = false;
1344 switch (ev.id) {
1345 case Q_CODEC_LOAD_DISK:
1346 case Q_CODEC_LOAD:
1347 LOGFQUEUE("codec < Q_CODEC_LOAD");
1348 if (playing)
1350 if (ci.new_track || status != CODEC_OK)
1352 if (!ci.new_track)
1354 logf("Codec failure, %d %d", ci.new_track, status);
1355 splash(HZ*2, "Codec failure");
1358 if (!codec_load_next_track())
1360 LOGFQUEUE("codec > audio Q_AUDIO_STOP");
1361 /* End of playlist */
1362 queue_post(&audio_queue, Q_AUDIO_STOP, 0);
1363 break;
1366 else
1368 logf("Codec finished");
1369 if (ci.stop_codec)
1371 /* Wait for the audio to stop playing before
1372 * triggering the WPS exit */
1373 while(pcm_is_playing())
1375 /* There has been one too many struct pointer swaps by now
1376 * so even though it says othertrack_id3, its the correct one! */
1377 othertrack_id3->elapsed =
1378 othertrack_id3->length - pcmbuf_get_latency();
1379 sleep(1);
1382 if (codec_requested_stop)
1384 LOGFQUEUE("codec > audio Q_AUDIO_STOP");
1385 queue_post(&audio_queue, Q_AUDIO_STOP, 0);
1387 break;
1391 if (CUR_TI->codec_hid >= 0)
1393 LOGFQUEUE("codec > codec Q_CODEC_LOAD");
1394 queue_post(&codec_queue, Q_CODEC_LOAD, 0);
1396 else
1398 const char *codec_fn =
1399 get_codec_filename(thistrack_id3->codectype);
1400 if (codec_fn)
1402 LOGFQUEUE("codec > codec Q_CODEC_LOAD_DISK");
1403 queue_post(&codec_queue, Q_CODEC_LOAD_DISK,
1404 (intptr_t)codec_fn);
1408 break;
1410 #ifdef AUDIO_HAVE_RECORDING
1411 case Q_ENCODER_LOAD_DISK:
1412 LOGFQUEUE("codec < Q_ENCODER_LOAD_DISK");
1414 if (status == CODEC_OK)
1415 break;
1417 logf("Encoder failure");
1418 splash(HZ*2, "Encoder failure");
1420 if (ci.enc_codec_loaded < 0)
1421 break;
1423 logf("Encoder failed to load");
1424 ci.enc_codec_loaded = -1;
1425 break;
1426 #endif /* AUDIO_HAVE_RECORDING */
1428 default:
1429 LOGFQUEUE("codec < default");
1431 } /* end switch */
1435 /* Borrow the codec thread and return the ID */
1436 void codec_thread_do_callback(void (*fn)(void), unsigned int *id)
1438 /* Set id before telling thread to call something; it may be
1439 * needed before this function returns. */
1440 if (id != NULL)
1441 *id = codec_thread_id;
1443 /* Codec thread will signal just before entering callback */
1444 LOGFQUEUE("codec >| Q_CODEC_DO_CALLBACK");
1445 queue_send(&codec_queue, Q_CODEC_DO_CALLBACK, (intptr_t)fn);
1448 /* --- Buffering callbacks --- */
1450 static void buffering_low_buffer_callback(void *data)
1452 (void)data;
1453 logf("low buffer callback");
1455 if (filling == STATE_FULL || filling == STATE_END_OF_PLAYLIST) {
1456 /* force a refill */
1457 LOGFQUEUE("buffering > audio Q_AUDIO_FILL_BUFFER");
1458 queue_post(&audio_queue, Q_AUDIO_FILL_BUFFER, 0);
1462 static void buffering_handle_rebuffer_callback(void *data)
1464 (void)data;
1465 LOGFQUEUE("audio >| audio Q_AUDIO_FLUSH");
1466 queue_post(&audio_queue, Q_AUDIO_FLUSH, 0);
1469 static void buffering_handle_finished_callback(int *data)
1471 logf("handle %d finished buffering", *data);
1473 if (*data == tracks[track_widx].id3_hid)
1475 int offset = ci.new_track + wps_offset;
1476 int next_idx = (track_ridx + offset + 1) & MAX_TRACK_MASK;
1477 /* The metadata handle for the last loaded track has been buffered.
1478 We can ask the audio thread to load the rest of the track's data. */
1479 LOGFQUEUE("audio >| audio Q_AUDIO_FINISH_LOAD");
1480 queue_post(&audio_queue, Q_AUDIO_FINISH_LOAD, 0);
1481 if (tracks[next_idx].id3_hid == *data)
1482 send_event(PLAYBACK_EVENT_NEXTTRACKID3_AVAILABLE, NULL);
1484 else
1486 /* This is most likely an audio handle, so we strip the useless
1487 trailing tags that are left. */
1488 strip_tags(*data);
1490 if (*data == tracks[track_widx-1].audio_hid
1491 && filling == STATE_END_OF_PLAYLIST)
1493 /* This was the last track in the playlist.
1494 We now have all the data we need. */
1495 logf("last track finished buffering");
1496 filling = STATE_FINISHED;
1502 /* --- Audio thread --- */
1504 static bool audio_have_tracks(void)
1506 return (audio_track_count() != 0);
1509 static int audio_free_track_count(void)
1511 /* Used tracks + free tracks adds up to MAX_TRACK - 1 */
1512 return MAX_TRACK - 1 - audio_track_count();
1515 int audio_track_count(void)
1517 /* Calculate difference from track_ridx to track_widx
1518 * taking into account a possible wrap-around. */
1519 return (MAX_TRACK + track_widx - track_ridx) & MAX_TRACK_MASK;
1522 long audio_filebufused(void)
1524 return (long) buf_used();
1527 /* Update track info after successful a codec track change */
1528 static void audio_update_trackinfo(void)
1530 /* Load the curent track's metadata into curtrack_id3 */
1531 if (CUR_TI->id3_hid >= 0)
1532 copy_mp3entry(thistrack_id3, bufgetid3(CUR_TI->id3_hid));
1534 /* Reset current position */
1535 thistrack_id3->elapsed = 0;
1536 thistrack_id3->offset = 0;
1538 /* Update the codec API */
1539 ci.filesize = CUR_TI->filesize;
1540 ci.id3 = thistrack_id3;
1541 ci.curpos = 0;
1542 ci.taginfo_ready = &CUR_TI->taginfo_ready;
1545 /* Clear tracks between write and read, non inclusive */
1546 static void audio_clear_track_entries(void)
1548 int cur_idx = track_widx;
1550 logf("Clearing tracks:%d/%d", track_ridx, track_widx);
1552 /* Loop over all tracks from write-to-read */
1553 while (1)
1555 cur_idx = (cur_idx + 1) & MAX_TRACK_MASK;
1557 if (cur_idx == track_ridx)
1558 break;
1560 clear_track_info(&tracks[cur_idx]);
1564 /* Clear all tracks */
1565 static bool audio_release_tracks(void)
1567 int i, cur_idx;
1569 logf("releasing all tracks");
1571 for(i = 0; i < MAX_TRACK; i++)
1573 cur_idx = (track_ridx + i) & MAX_TRACK_MASK;
1574 if (!clear_track_info(&tracks[cur_idx]))
1575 return false;
1578 return true;
1581 static bool audio_loadcodec(bool start_play)
1583 int prev_track;
1584 char codec_path[MAX_PATH]; /* Full path to codec */
1585 const struct mp3entry *id3, *prev_id3;
1587 if (tracks[track_widx].id3_hid < 0) {
1588 return false;
1591 id3 = bufgetid3(tracks[track_widx].id3_hid);
1592 if (!id3)
1593 return false;
1595 const char *codec_fn = get_codec_filename(id3->codectype);
1596 if (codec_fn == NULL)
1597 return false;
1599 tracks[track_widx].codec_hid = -1;
1601 if (start_play)
1603 /* Load the codec directly from disk and save some memory. */
1604 track_ridx = track_widx;
1605 ci.filesize = CUR_TI->filesize;
1606 ci.id3 = thistrack_id3;
1607 ci.taginfo_ready = &CUR_TI->taginfo_ready;
1608 ci.curpos = 0;
1609 LOGFQUEUE("codec > codec Q_CODEC_LOAD_DISK");
1610 queue_post(&codec_queue, Q_CODEC_LOAD_DISK, (intptr_t)codec_fn);
1611 return true;
1613 else
1615 /* If we already have another track than this one buffered */
1616 if (track_widx != track_ridx)
1618 prev_track = (track_widx - 1) & MAX_TRACK_MASK;
1620 id3 = bufgetid3(tracks[track_widx].id3_hid);
1621 prev_id3 = bufgetid3(tracks[prev_track].id3_hid);
1623 /* If the previous codec is the same as this one, there is no need
1624 * to put another copy of it on the file buffer */
1625 if (id3 && prev_id3 &&
1626 get_codec_base_type(id3->codectype) ==
1627 get_codec_base_type(prev_id3->codectype)
1628 && audio_codec_loaded)
1630 logf("Reusing prev. codec");
1631 return true;
1636 codec_get_full_path(codec_path, codec_fn);
1638 tracks[track_widx].codec_hid = bufopen(codec_path, 0, TYPE_CODEC);
1639 if (tracks[track_widx].codec_hid < 0)
1640 return false;
1642 logf("Loaded codec");
1644 return true;
1647 /* Load metadata for the next track (with bufopen). The rest of the track
1648 loading will be handled by audio_finish_load_track once the metadata has been
1649 actually loaded by the buffering thread. */
1650 static bool audio_load_track(size_t offset, bool start_play)
1652 const char *trackname;
1653 int fd = -1;
1655 if (track_load_started) {
1656 /* There is already a track load in progress, so track_widx hasn't been
1657 incremented yet. Loading another track would overwrite the one that
1658 hasn't finished loading. */
1659 logf("audio_load_track(): a track load is already in progress");
1660 return false;
1663 start_play_g = start_play; /* will be read by audio_finish_load_track */
1665 /* Stop buffer filling if there is no free track entries.
1666 Don't fill up the last track entry (we wan't to store next track
1667 metadata there). */
1668 if (!audio_free_track_count())
1670 logf("No free tracks");
1671 return false;
1674 last_peek_offset++;
1675 tracks[track_widx].taginfo_ready = false;
1677 logf("Buffering track:%d/%d", track_widx, track_ridx);
1678 /* Get track name from current playlist read position. */
1679 while ((trackname = playlist_peek(last_peek_offset)) != NULL)
1681 /* Handle broken playlists. */
1682 fd = open(trackname, O_RDONLY);
1683 if (fd < 0)
1685 logf("Open failed");
1686 /* Skip invalid entry from playlist. */
1687 playlist_skip_entry(NULL, last_peek_offset);
1689 else
1690 break;
1693 if (!trackname)
1695 logf("End-of-playlist");
1696 memset(&unbuffered_id3, 0, sizeof(struct mp3entry));
1697 filling = STATE_END_OF_PLAYLIST;
1699 if (thistrack_id3->length == 0 && thistrack_id3->filesize == 0)
1701 /* Stop playback if no valid track was found. */
1702 audio_stop_playback();
1705 return false;
1708 tracks[track_widx].filesize = filesize(fd);
1710 if (offset > tracks[track_widx].filesize)
1711 offset = 0;
1713 /* Set default values */
1714 if (start_play)
1716 buf_set_watermark(filebuflen/2);
1717 dsp_configure(ci.dsp, DSP_RESET, 0);
1718 playlist_update_resume_info(audio_current_track());
1721 /* Get track metadata if we don't already have it. */
1722 if (tracks[track_widx].id3_hid < 0)
1724 tracks[track_widx].id3_hid = bufopen(trackname, 0, TYPE_ID3);
1726 if (tracks[track_widx].id3_hid < 0)
1728 /* Buffer is full. */
1729 get_metadata(&unbuffered_id3, fd, trackname);
1730 last_peek_offset--;
1731 close(fd);
1732 logf("buffer is full for now");
1733 filling = STATE_FULL;
1734 return false;
1737 if (track_widx == track_ridx)
1739 /* TODO: Superfluos buffering call? */
1740 buf_request_buffer_handle(tracks[track_widx].id3_hid);
1741 struct mp3entry *id3 = bufgetid3(tracks[track_widx].id3_hid);
1742 if (id3)
1744 copy_mp3entry(thistrack_id3, id3);
1745 thistrack_id3->offset = offset;
1747 else
1748 memset(thistrack_id3, 0, sizeof(struct mp3entry));
1751 if (start_play)
1753 playlist_update_resume_info(audio_current_track());
1757 close(fd);
1758 track_load_started = true; /* Remember that we've started loading a track */
1759 return true;
1762 /* Second part of the track loading: We now have the metadata available, so we
1763 can load the codec, the album art and finally the audio data.
1764 This is called on the audio thread after the buffering thread calls the
1765 buffering_handle_finished_callback callback. */
1766 static void audio_finish_load_track(void)
1768 size_t file_offset = 0;
1769 size_t offset = 0;
1770 bool start_play = start_play_g;
1772 track_load_started = false;
1774 if (tracks[track_widx].id3_hid < 0) {
1775 logf("no metatdata");
1776 return;
1779 struct mp3entry *track_id3;
1781 if (track_widx == track_ridx)
1782 track_id3 = thistrack_id3;
1783 else
1784 track_id3 = bufgetid3(tracks[track_widx].id3_hid);
1786 if (track_id3->length == 0 && track_id3->filesize == 0)
1788 logf("audio_finish_load_track: invalid metadata");
1790 /* Invalid metadata */
1791 bufclose(tracks[track_widx].id3_hid);
1792 tracks[track_widx].id3_hid = -1;
1794 /* Skip invalid entry from playlist. */
1795 playlist_skip_entry(NULL, last_peek_offset--);
1797 /* load next track */
1798 LOGFQUEUE("audio > audio Q_AUDIO_FILL_BUFFER %d", (int)start_play);
1799 queue_post(&audio_queue, Q_AUDIO_FILL_BUFFER, start_play);
1801 return;
1804 #ifdef HAVE_ALBUMART
1805 if (tracks[track_widx].aa_hid < 0 && gui_sync_wps_uses_albumart())
1807 char aa_path[MAX_PATH];
1808 if (find_albumart(track_id3, aa_path, sizeof(aa_path)))
1810 tracks[track_widx].aa_hid = bufopen(aa_path, 0, TYPE_BITMAP);
1812 if(tracks[track_widx].aa_hid == ERR_BUFFER_FULL)
1814 filling = STATE_FULL;
1815 logf("buffer is full for now");
1816 return; /* No space for track's album art, not an error */
1818 else if (tracks[track_widx].aa_hid < 0)
1820 /* another error, ignore AlbumArt */
1821 logf("Album art loading failed");
1825 #endif
1827 /* Load the codec. */
1828 if (!audio_loadcodec(start_play))
1830 if (tracks[track_widx].codec_hid == ERR_BUFFER_FULL)
1832 /* No space for codec on buffer, not an error */
1833 filling = STATE_FULL;
1834 return;
1837 /* This is an error condition, either no codec was found, or reading
1838 * the codec file failed part way through, either way, skip the track */
1839 /* FIXME: We should not use splashf from audio thread! */
1840 splashf(HZ*2, "No codec for: %s", track_id3->path);
1841 /* Skip invalid entry from playlist. */
1842 playlist_skip_entry(NULL, last_peek_offset);
1843 return;
1846 track_id3->elapsed = 0;
1847 offset = track_id3->offset;
1849 enum data_type type = TYPE_PACKET_AUDIO;
1851 switch (track_id3->codectype) {
1852 case AFMT_MPA_L1:
1853 case AFMT_MPA_L2:
1854 case AFMT_MPA_L3:
1855 if (offset > 0) {
1856 file_offset = offset;
1857 track_id3->offset = offset;
1859 break;
1861 case AFMT_WAVPACK:
1862 if (offset > 0) {
1863 file_offset = offset;
1864 track_id3->offset = offset;
1865 track_id3->elapsed = track_id3->length / 2;
1867 break;
1869 case AFMT_OGG_VORBIS:
1870 case AFMT_SPEEX:
1871 case AFMT_FLAC:
1872 case AFMT_PCM_WAV:
1873 case AFMT_A52:
1874 case AFMT_AAC:
1875 case AFMT_MPC:
1876 case AFMT_APE:
1877 case AFMT_WMA:
1878 if (offset > 0)
1879 track_id3->offset = offset;
1880 break;
1882 case AFMT_NSF:
1883 case AFMT_SPC:
1884 case AFMT_SID:
1885 logf("Loading atomic %d",track_id3->codectype);
1886 type = TYPE_ATOMIC_AUDIO;
1887 break;
1890 logf("alt:%s", track_id3->path);
1892 if (file_offset > AUDIO_REBUFFER_GUESS_SIZE)
1893 file_offset -= AUDIO_REBUFFER_GUESS_SIZE;
1894 else if (track_id3->first_frame_offset)
1895 file_offset = track_id3->first_frame_offset;
1896 else
1897 file_offset = 0;
1899 tracks[track_widx].audio_hid = bufopen(track_id3->path, file_offset, type);
1901 /* No space left, not an error */
1902 if (tracks[track_widx].audio_hid == ERR_BUFFER_FULL)
1904 filling = STATE_FULL;
1905 logf("buffer is full for now");
1906 return;
1908 else if (tracks[track_widx].audio_hid < 0)
1910 /* another error, do not continue either */
1911 logf("Could not add audio data handle");
1912 return;
1915 /* All required data is now available for the codec. */
1916 tracks[track_widx].taginfo_ready = true;
1918 if (start_play)
1920 ci.curpos=file_offset;
1921 buf_request_buffer_handle(tracks[track_widx].audio_hid);
1924 track_widx = (track_widx + 1) & MAX_TRACK_MASK;
1926 send_event(PLAYBACK_EVENT_TRACK_BUFFER, track_id3);
1928 /* load next track */
1929 LOGFQUEUE("audio > audio Q_AUDIO_FILL_BUFFER");
1930 queue_post(&audio_queue, Q_AUDIO_FILL_BUFFER, 0);
1932 return;
1935 static void audio_fill_file_buffer(bool start_play, size_t offset)
1937 filling = STATE_FILLING;
1938 trigger_cpu_boost();
1940 /* No need to rebuffer if there are track skips pending. */
1941 if (ci.new_track != 0)
1942 return;
1944 /* Must reset the buffer before use if trashed or voice only - voice
1945 file size shouldn't have changed so we can go straight from
1946 AUDIOBUF_STATE_VOICED_ONLY to AUDIOBUF_STATE_INITIALIZED */
1947 if (buffer_state != AUDIOBUF_STATE_INITIALIZED)
1948 audio_reset_buffer();
1950 logf("Starting buffer fill");
1952 if (!start_play)
1953 audio_clear_track_entries();
1955 /* Save the current resume position once. */
1956 playlist_update_resume_info(audio_current_track());
1958 audio_load_track(offset, start_play);
1961 static void audio_rebuffer(void)
1963 logf("Forcing rebuffer");
1965 clear_track_info(CUR_TI);
1967 /* Reset track pointers */
1968 track_widx = track_ridx;
1969 audio_clear_track_entries();
1971 /* Reset a possibly interrupted track load */
1972 track_load_started = false;
1974 /* Fill the buffer */
1975 last_peek_offset = -1;
1976 ci.curpos = 0;
1978 if (!CUR_TI->taginfo_ready)
1979 memset(thistrack_id3, 0, sizeof(struct mp3entry));
1981 audio_fill_file_buffer(false, 0);
1984 /* Called on request from the codec to get a new track. This is the codec part
1985 of the track transition. */
1986 static int audio_check_new_track(void)
1988 int track_count = audio_track_count();
1989 int old_track_ridx = track_ridx;
1990 int i, idx;
1991 bool forward;
1992 struct mp3entry *temp = thistrack_id3;
1994 /* Now it's good time to send track finish events. */
1995 send_event(PLAYBACK_EVENT_TRACK_FINISH, thistrack_id3);
1996 /* swap the mp3entry pointers */
1997 thistrack_id3 = othertrack_id3;
1998 othertrack_id3 = temp;
1999 ci.id3 = thistrack_id3;
2000 memset(thistrack_id3, 0, sizeof(struct mp3entry));
2002 if (dir_skip)
2004 dir_skip = false;
2005 /* regardless of the return value we need to rebuffer.
2006 if it fails the old playlist will resume, else the
2007 next dir will start playing */
2008 playlist_next_dir(ci.new_track);
2009 ci.new_track = 0;
2010 audio_rebuffer();
2011 goto skip_done;
2014 if (new_playlist)
2015 ci.new_track = 0;
2017 /* If the playlist isn't that big */
2018 if (automatic_skip)
2020 while (!playlist_check(ci.new_track))
2022 if (ci.new_track >= 0)
2024 LOGFQUEUE("audio >|= codec Q_CODEC_REQUEST_FAILED");
2025 return Q_CODEC_REQUEST_FAILED;
2027 ci.new_track++;
2031 /* Update the playlist */
2032 last_peek_offset -= ci.new_track;
2034 if (playlist_next(ci.new_track) < 0)
2036 LOGFQUEUE("audio >|= codec Q_CODEC_REQUEST_FAILED");
2037 return Q_CODEC_REQUEST_FAILED;
2040 if (new_playlist)
2042 ci.new_track = 1;
2043 new_playlist = false;
2046 /* Save a pointer to the old track to allow later clearing */
2047 prev_ti = CUR_TI;
2049 for (i = 0; i < ci.new_track; i++)
2051 idx = (track_ridx + i) & MAX_TRACK_MASK;
2052 struct mp3entry *id3 = bufgetid3(tracks[idx].id3_hid);
2053 ssize_t offset = buf_handle_offset(tracks[idx].audio_hid);
2054 if (!id3 || offset < 0 || (unsigned)offset > id3->first_frame_offset)
2056 /* We don't have all the audio data for that track, so clear it,
2057 but keep the metadata. */
2058 if (tracks[idx].audio_hid >= 0 && bufclose(tracks[idx].audio_hid))
2060 tracks[idx].audio_hid = -1;
2061 tracks[idx].filesize = 0;
2066 /* Move to the new track */
2067 track_ridx = (track_ridx + ci.new_track) & MAX_TRACK_MASK;
2069 buf_set_base_handle(CUR_TI->audio_hid);
2071 if (automatic_skip)
2073 wps_offset = -ci.new_track;
2076 /* If it is not safe to even skip this many track entries */
2077 if (ci.new_track >= track_count || ci.new_track <= track_count - MAX_TRACK)
2079 ci.new_track = 0;
2080 audio_rebuffer();
2081 goto skip_done;
2084 forward = ci.new_track > 0;
2085 ci.new_track = 0;
2087 /* If the target track is clearly not in memory */
2088 if (CUR_TI->filesize == 0 || !CUR_TI->taginfo_ready)
2090 audio_rebuffer();
2091 goto skip_done;
2094 /* When skipping backwards, it is possible that we've found a track that's
2095 * buffered, but which is around the track-wrap and therefore not the track
2096 * we are looking for */
2097 if (!forward)
2099 int cur_idx = track_ridx;
2100 bool taginfo_ready = true;
2101 /* We've wrapped the buffer backwards if new > old */
2102 bool wrap = track_ridx > old_track_ridx;
2104 while (1)
2106 cur_idx = (cur_idx + 1) & MAX_TRACK_MASK;
2108 /* if we've advanced past the wrap when cur_idx is zeroed */
2109 if (!cur_idx)
2110 wrap = false;
2112 /* if we aren't still on the wrap and we've caught the old track */
2113 if (!(wrap || cur_idx < old_track_ridx))
2114 break;
2116 /* If we hit a track in between without valid tag info, bail */
2117 if (!tracks[cur_idx].taginfo_ready)
2119 taginfo_ready = false;
2120 break;
2123 if (!taginfo_ready)
2125 audio_rebuffer();
2129 skip_done:
2130 audio_update_trackinfo();
2131 LOGFQUEUE("audio >|= codec Q_CODEC_REQUEST_COMPLETE");
2132 return Q_CODEC_REQUEST_COMPLETE;
2135 unsigned long audio_prev_elapsed(void)
2137 return prev_track_elapsed;
2140 static void audio_stop_codec_flush(void)
2142 ci.stop_codec = true;
2143 pcmbuf_pause(true);
2145 while (audio_codec_loaded)
2146 yield();
2148 /* If the audio codec is not loaded any more, and the audio is still
2149 * playing, it is now and _only_ now safe to call this function from the
2150 * audio thread */
2151 if (pcm_is_playing())
2153 pcmbuf_play_stop();
2154 pcmbuf_queue_clear();
2156 pcmbuf_pause(paused);
2159 static void audio_stop_playback(void)
2161 /* If we were playing, save resume information */
2162 if (playing)
2164 struct mp3entry *id3 = NULL;
2166 if (!ci.stop_codec)
2168 /* Set this early, the outside code yields and may allow the codec
2169 to try to wait for a reply on a buffer wait */
2170 ci.stop_codec = true;
2171 id3 = audio_current_track();
2174 /* Save the current playing spot, or NULL if the playlist has ended */
2175 playlist_update_resume_info(id3);
2177 /* TODO: Create auto bookmark too? */
2179 prev_track_elapsed = othertrack_id3->elapsed;
2181 remove_event(BUFFER_EVENT_BUFFER_LOW, buffering_low_buffer_callback);
2184 audio_stop_codec_flush();
2185 paused = false;
2186 playing = false;
2187 track_load_started = false;
2189 filling = STATE_IDLE;
2191 /* Mark all entries null. */
2192 audio_clear_track_entries();
2194 /* Close all tracks */
2195 audio_release_tracks();
2198 static void audio_play_start(size_t offset)
2200 int i;
2202 #if INPUT_SRC_CAPS != 0
2203 audio_set_input_source(AUDIO_SRC_PLAYBACK, SRCF_PLAYBACK);
2204 audio_set_output_source(AUDIO_SRC_PLAYBACK);
2205 #endif
2207 /* Wait for any previously playing audio to flush - TODO: Not necessary? */
2208 paused = false;
2209 audio_stop_codec_flush();
2211 playing = true;
2212 track_load_started = false;
2214 ci.new_track = 0;
2215 ci.seek_time = 0;
2216 wps_offset = 0;
2218 sound_set_volume(global_settings.volume);
2219 track_widx = track_ridx = 0;
2221 /* Clear all track entries. */
2222 for (i = 0; i < MAX_TRACK; i++) {
2223 clear_track_info(&tracks[i]);
2226 last_peek_offset = -1;
2228 /* Officially playing */
2229 queue_reply(&audio_queue, 1);
2231 audio_fill_file_buffer(true, offset);
2233 add_event(BUFFER_EVENT_BUFFER_LOW, false, buffering_low_buffer_callback);
2235 LOGFQUEUE("audio > audio Q_AUDIO_TRACK_CHANGED");
2236 queue_post(&audio_queue, Q_AUDIO_TRACK_CHANGED, 0);
2240 /* Invalidates all but currently playing track. */
2241 static void audio_invalidate_tracks(void)
2243 if (audio_have_tracks())
2245 last_peek_offset = 0;
2246 track_widx = track_ridx;
2248 /* Mark all other entries null (also buffered wrong metadata). */
2249 audio_clear_track_entries();
2251 track_widx = (track_widx + 1) & MAX_TRACK_MASK;
2253 audio_fill_file_buffer(false, 0);
2257 static void audio_new_playlist(void)
2259 /* Prepare to start a new fill from the beginning of the playlist */
2260 last_peek_offset = -1;
2261 if (audio_have_tracks())
2263 if (paused)
2264 skipped_during_pause = true;
2265 track_widx = track_ridx;
2266 audio_clear_track_entries();
2268 track_widx = (track_widx + 1) & MAX_TRACK_MASK;
2270 /* Mark the current track as invalid to prevent skipping back to it */
2271 CUR_TI->taginfo_ready = false;
2274 /* Signal the codec to initiate a track change forward */
2275 new_playlist = true;
2276 ci.new_track = 1;
2278 /* Officially playing */
2279 queue_reply(&audio_queue, 1);
2281 audio_fill_file_buffer(false, 0);
2284 /* Called on manual track skip */
2285 static void audio_initiate_track_change(long direction)
2287 logf("audio_initiate_track_change(%ld)", direction);
2289 ci.new_track += direction;
2290 wps_offset -= direction;
2291 if (paused)
2292 skipped_during_pause = true;
2295 /* Called on manual dir skip */
2296 static void audio_initiate_dir_change(long direction)
2298 dir_skip = true;
2299 ci.new_track = direction;
2300 if (paused)
2301 skipped_during_pause = true;
2304 /* Called when PCM track change is complete */
2305 static void audio_finalise_track_change(void)
2307 logf("audio_finalise_track_change");
2309 if (automatic_skip)
2311 wps_offset = 0;
2312 automatic_skip = false;
2314 /* Invalidate prevtrack_id3 */
2315 memset(othertrack_id3, 0, sizeof(struct mp3entry));
2317 if (prev_ti && prev_ti->audio_hid < 0)
2319 /* No audio left so we clear all the track info. */
2320 clear_track_info(prev_ti);
2323 send_event(PLAYBACK_EVENT_TRACK_CHANGE, thistrack_id3);
2324 playlist_update_resume_info(audio_current_track());
2328 * Layout audio buffer as follows - iram buffer depends on target:
2329 * [|SWAP:iram][|TALK]|FILE|GUARD|PCM|[SWAP:dram[|iram]|]
2331 static void audio_reset_buffer(void)
2333 /* see audio_get_recording_buffer if this is modified */
2334 logf("audio_reset_buffer");
2336 /* If the setup of anything allocated before the file buffer is
2337 changed, do check the adjustments after the buffer_alloc call
2338 as it will likely be affected and need sliding over */
2340 /* Initially set up file buffer as all space available */
2341 malloc_buf = audiobuf + talk_get_bufsize();
2342 /* Align the malloc buf to line size. Especially important to cf
2343 targets that do line reads/writes. */
2344 malloc_buf = (unsigned char *)(((uintptr_t)malloc_buf + 15) & ~15);
2345 filebuf = malloc_buf; /* filebuf line align implied */
2346 filebuflen = audiobufend - filebuf;
2348 filebuflen &= ~15;
2350 /* Subtract whatever the pcm buffer says it used plus the guard buffer */
2351 const size_t pcmbuf_size = pcmbuf_init(filebuf + filebuflen) +GUARD_BUFSIZE;
2353 #ifdef DEBUG
2354 if(pcmbuf_size > filebuflen)
2355 panicf("Not enough memory for pcmbuf_init() : %d > %d",
2356 (int)pcmbuf_size, (int)filebuflen);
2357 #endif
2359 filebuflen -= pcmbuf_size;
2361 /* Make sure filebuflen is a longword multiple after adjustment - filebuf
2362 will already be line aligned */
2363 filebuflen &= ~3;
2365 buffering_reset(filebuf, filebuflen);
2367 /* Clear any references to the file buffer */
2368 buffer_state = AUDIOBUF_STATE_INITIALIZED;
2370 #if defined(ROCKBOX_HAS_LOGF) && defined(LOGF_ENABLE)
2371 /* Make sure everything adds up - yes, some info is a bit redundant but
2372 aids viewing and the sumation of certain variables should add up to
2373 the location of others. */
2375 size_t pcmbufsize;
2376 const unsigned char *pcmbuf = pcmbuf_get_meminfo(&pcmbufsize);
2377 logf("mabuf: %08X", (unsigned)malloc_buf);
2378 logf("fbuf: %08X", (unsigned)filebuf);
2379 logf("fbufe: %08X", (unsigned)(filebuf + filebuflen));
2380 logf("gbuf: %08X", (unsigned)(filebuf + filebuflen));
2381 logf("gbufe: %08X", (unsigned)(filebuf + filebuflen + GUARD_BUFSIZE));
2382 logf("pcmb: %08X", (unsigned)pcmbuf);
2383 logf("pcmbe: %08X", (unsigned)(pcmbuf + pcmbufsize));
2385 #endif
2388 static void audio_thread(void)
2390 struct queue_event ev;
2392 pcm_postinit();
2394 audio_thread_ready = true;
2396 while (1)
2398 if (filling != STATE_FILLING) {
2399 /* End of buffering, let's calculate the watermark and unboost */
2400 set_filebuf_watermark();
2401 cancel_cpu_boost();
2404 if (!pcmbuf_queue_scan(&ev))
2405 queue_wait_w_tmo(&audio_queue, &ev, HZ/2);
2407 switch (ev.id) {
2409 case Q_AUDIO_FILL_BUFFER:
2410 LOGFQUEUE("audio < Q_AUDIO_FILL_BUFFER %d", (int)ev.data);
2411 audio_fill_file_buffer((bool)ev.data, 0);
2412 break;
2414 case Q_AUDIO_FINISH_LOAD:
2415 LOGFQUEUE("audio < Q_AUDIO_FINISH_LOAD");
2416 audio_finish_load_track();
2417 break;
2419 case Q_AUDIO_PLAY:
2420 LOGFQUEUE("audio < Q_AUDIO_PLAY");
2421 if (playing && ev.data <= 0)
2422 audio_new_playlist();
2423 else
2425 audio_stop_playback();
2426 audio_play_start((size_t)ev.data);
2428 break;
2430 case Q_AUDIO_STOP:
2431 LOGFQUEUE("audio < Q_AUDIO_STOP");
2432 if (playing)
2433 audio_stop_playback();
2434 if (ev.data != 0)
2435 queue_clear(&audio_queue);
2436 break;
2438 case Q_AUDIO_PAUSE:
2439 LOGFQUEUE("audio < Q_AUDIO_PAUSE");
2440 if (!(bool) ev.data && skipped_during_pause && !pcmbuf_is_crossfade_active())
2441 pcmbuf_play_stop(); /* Flush old track on resume after skip */
2442 skipped_during_pause = false;
2443 if (!playing)
2444 break;
2445 pcmbuf_pause((bool)ev.data);
2446 paused = (bool)ev.data;
2447 break;
2449 case Q_AUDIO_SKIP:
2450 LOGFQUEUE("audio < Q_AUDIO_SKIP");
2451 audio_initiate_track_change((long)ev.data);
2452 break;
2454 case Q_AUDIO_PRE_FF_REWIND:
2455 LOGFQUEUE("audio < Q_AUDIO_PRE_FF_REWIND");
2456 if (!playing)
2457 break;
2458 pcmbuf_pause(true);
2459 break;
2461 case Q_AUDIO_FF_REWIND:
2462 LOGFQUEUE("audio < Q_AUDIO_FF_REWIND");
2463 if (!playing)
2464 break;
2465 if (automatic_skip)
2467 /* An automatic track skip is in progress. Finalize it,
2468 then go back to the previous track */
2469 audio_finalise_track_change();
2470 ci.new_track = -1;
2472 ci.seek_time = (long)ev.data+1;
2473 break;
2475 case Q_AUDIO_CHECK_NEW_TRACK:
2476 LOGFQUEUE("audio < Q_AUDIO_CHECK_NEW_TRACK");
2477 queue_reply(&audio_queue, audio_check_new_track());
2478 break;
2480 case Q_AUDIO_DIR_SKIP:
2481 LOGFQUEUE("audio < Q_AUDIO_DIR_SKIP");
2482 audio_initiate_dir_change(ev.data);
2483 break;
2485 case Q_AUDIO_FLUSH:
2486 LOGFQUEUE("audio < Q_AUDIO_FLUSH");
2487 audio_invalidate_tracks();
2488 break;
2490 case Q_AUDIO_TRACK_CHANGED:
2491 /* PCM track change done */
2492 LOGFQUEUE("audio < Q_AUDIO_TRACK_CHANGED");
2493 audio_finalise_track_change();
2494 break;
2496 #ifndef SIMULATOR
2497 case SYS_USB_CONNECTED:
2498 LOGFQUEUE("audio < SYS_USB_CONNECTED");
2499 if (playing)
2500 audio_stop_playback();
2501 #ifdef PLAYBACK_VOICE
2502 voice_stop();
2503 #endif
2504 usb_acknowledge(SYS_USB_CONNECTED_ACK);
2505 usb_wait_for_disconnect(&audio_queue);
2507 /* Mark all entries null. */
2508 audio_clear_track_entries();
2510 /* release tracks to make sure all handles are closed */
2511 audio_release_tracks();
2512 break;
2513 #endif
2515 case SYS_TIMEOUT:
2516 LOGFQUEUE_SYS_TIMEOUT("audio < SYS_TIMEOUT");
2517 break;
2519 default:
2520 LOGFQUEUE("audio < default");
2521 break;
2522 } /* end switch */
2523 } /* end while */
2526 /* Initialize the audio system - called from init() in main.c.
2527 * Last function because of all the references to internal symbols
2529 void audio_init(void)
2531 unsigned int audio_thread_id;
2533 /* Can never do this twice */
2534 if (audio_is_initialized)
2536 logf("audio: already initialized");
2537 return;
2540 logf("audio: initializing");
2542 /* Initialize queues before giving control elsewhere in case it likes
2543 to send messages. Thread creation will be delayed however so nothing
2544 starts running until ready if something yields such as talk_init. */
2545 queue_init(&audio_queue, true);
2546 queue_init(&codec_queue, false);
2547 queue_init(&pcmbuf_queue, false);
2549 pcm_init();
2551 /* Initialize codec api. */
2552 ci.read_filebuf = codec_filebuf_callback;
2553 ci.pcmbuf_insert = codec_pcmbuf_insert_callback;
2554 ci.codec_get_buffer = codec_get_buffer;
2555 ci.request_buffer = codec_request_buffer_callback;
2556 ci.advance_buffer = codec_advance_buffer_callback;
2557 ci.advance_buffer_loc = codec_advance_buffer_loc_callback;
2558 ci.request_next_track = codec_request_next_track_callback;
2559 ci.seek_buffer = codec_seek_buffer_callback;
2560 ci.seek_complete = codec_seek_complete_callback;
2561 ci.set_elapsed = codec_set_elapsed_callback;
2562 ci.set_offset = codec_set_offset_callback;
2563 ci.configure = codec_configure_callback;
2564 ci.discard_codec = codec_discard_codec_callback;
2565 ci.dsp = (struct dsp_config *)dsp_configure(NULL, DSP_MYDSP,
2566 CODEC_IDX_AUDIO);
2568 thistrack_id3 = &mp3entry_buf[0];
2569 othertrack_id3 = &mp3entry_buf[1];
2571 /* initialize the buffer */
2572 filebuf = audiobuf;
2574 /* audio_reset_buffer must to know the size of voice buffer so init
2575 talk first */
2576 talk_init();
2578 codec_thread_id = create_thread(
2579 codec_thread, codec_stack, sizeof(codec_stack),
2580 CREATE_THREAD_FROZEN,
2581 codec_thread_name IF_PRIO(, PRIORITY_PLAYBACK)
2582 IF_COP(, CPU));
2584 queue_enable_queue_send(&codec_queue, &codec_queue_sender_list,
2585 codec_thread_id);
2587 audio_thread_id = create_thread(audio_thread, audio_stack,
2588 sizeof(audio_stack), CREATE_THREAD_FROZEN,
2589 audio_thread_name IF_PRIO(, PRIORITY_USER_INTERFACE)
2590 IF_COP(, CPU));
2592 queue_enable_queue_send(&audio_queue, &audio_queue_sender_list,
2593 audio_thread_id);
2595 #ifdef PLAYBACK_VOICE
2596 voice_thread_init();
2597 #endif
2599 /* Set crossfade setting for next buffer init which should be about... */
2600 pcmbuf_crossfade_enable(global_settings.crossfade);
2602 /* initialize the buffering system */
2604 buffering_init();
2605 /* ...now! Set up the buffers */
2606 audio_reset_buffer();
2608 int i;
2609 for(i = 0; i < MAX_TRACK; i++)
2611 tracks[i].audio_hid = -1;
2612 tracks[i].id3_hid = -1;
2613 tracks[i].codec_hid = -1;
2614 #ifdef HAVE_ALBUMART
2615 tracks[i].aa_hid = -1;
2616 #endif
2619 add_event(BUFFER_EVENT_REBUFFER, false, buffering_handle_rebuffer_callback);
2620 add_event(BUFFER_EVENT_FINISHED, false, buffering_handle_finished_callback);
2622 /* Probably safe to say */
2623 audio_is_initialized = true;
2625 sound_settings_apply();
2626 #ifdef HAVE_DISK_STORAGE
2627 audio_set_buffer_margin(global_settings.buffer_margin);
2628 #endif
2630 /* it's safe to let the threads run now */
2631 #ifdef PLAYBACK_VOICE
2632 voice_thread_resume();
2633 #endif
2634 thread_thaw(codec_thread_id);
2635 thread_thaw(audio_thread_id);
2637 } /* audio_init */
2639 bool audio_is_thread_ready(void)
2641 return audio_thread_ready;