FS9795 - some playback cleanup.
[kugel-rb.git] / apps / playback.c
blob3709b407fabc287b674f764e2ffb1ae897dd13d9
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 /* FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME
2047 * 1) why are we doing this?
2048 * 2) thistrack_id3 has already been cleared anyway */
2049 /* Update the main buffer copy of the track metadata with the one
2050 the codec has been using (for the unbuffer callbacks) */
2051 if (CUR_TI->id3_hid >= 0)
2052 copy_mp3entry(bufgetid3(CUR_TI->id3_hid), thistrack_id3);
2053 /* FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME */
2056 /* Save a pointer to the old track to allow later clearing */
2057 prev_ti = CUR_TI;
2059 for (i = 0; i < ci.new_track; i++)
2061 idx = (track_ridx + i) & MAX_TRACK_MASK;
2062 struct mp3entry *id3 = bufgetid3(tracks[idx].id3_hid);
2063 ssize_t offset = buf_handle_offset(tracks[idx].audio_hid);
2064 if (!id3 || offset < 0 || (unsigned)offset > id3->first_frame_offset)
2066 /* We don't have all the audio data for that track, so clear it,
2067 but keep the metadata. */
2068 if (tracks[idx].audio_hid >= 0 && bufclose(tracks[idx].audio_hid))
2070 tracks[idx].audio_hid = -1;
2071 tracks[idx].filesize = 0;
2076 /* Move to the new track */
2077 track_ridx = (track_ridx + ci.new_track) & MAX_TRACK_MASK;
2079 buf_set_base_handle(CUR_TI->audio_hid);
2081 if (automatic_skip)
2083 wps_offset = -ci.new_track;
2086 /* If it is not safe to even skip this many track entries */
2087 if (ci.new_track >= track_count || ci.new_track <= track_count - MAX_TRACK)
2089 ci.new_track = 0;
2090 audio_rebuffer();
2091 goto skip_done;
2094 forward = ci.new_track > 0;
2095 ci.new_track = 0;
2097 /* If the target track is clearly not in memory */
2098 if (CUR_TI->filesize == 0 || !CUR_TI->taginfo_ready)
2100 audio_rebuffer();
2101 goto skip_done;
2104 /* When skipping backwards, it is possible that we've found a track that's
2105 * buffered, but which is around the track-wrap and therefore not the track
2106 * we are looking for */
2107 if (!forward)
2109 int cur_idx = track_ridx;
2110 bool taginfo_ready = true;
2111 /* We've wrapped the buffer backwards if new > old */
2112 bool wrap = track_ridx > old_track_ridx;
2114 while (1)
2116 cur_idx = (cur_idx + 1) & MAX_TRACK_MASK;
2118 /* if we've advanced past the wrap when cur_idx is zeroed */
2119 if (!cur_idx)
2120 wrap = false;
2122 /* if we aren't still on the wrap and we've caught the old track */
2123 if (!(wrap || cur_idx < old_track_ridx))
2124 break;
2126 /* If we hit a track in between without valid tag info, bail */
2127 if (!tracks[cur_idx].taginfo_ready)
2129 taginfo_ready = false;
2130 break;
2133 if (!taginfo_ready)
2135 audio_rebuffer();
2139 skip_done:
2140 audio_update_trackinfo();
2141 LOGFQUEUE("audio >|= codec Q_CODEC_REQUEST_COMPLETE");
2142 return Q_CODEC_REQUEST_COMPLETE;
2145 unsigned long audio_prev_elapsed(void)
2147 return prev_track_elapsed;
2150 static void audio_stop_codec_flush(void)
2152 ci.stop_codec = true;
2153 pcmbuf_pause(true);
2155 while (audio_codec_loaded)
2156 yield();
2158 /* If the audio codec is not loaded any more, and the audio is still
2159 * playing, it is now and _only_ now safe to call this function from the
2160 * audio thread */
2161 if (pcm_is_playing())
2163 pcmbuf_play_stop();
2164 pcmbuf_queue_clear();
2166 pcmbuf_pause(paused);
2169 static void audio_stop_playback(void)
2171 /* If we were playing, save resume information */
2172 if (playing)
2174 struct mp3entry *id3 = NULL;
2176 if (!ci.stop_codec)
2178 /* Set this early, the outside code yields and may allow the codec
2179 to try to wait for a reply on a buffer wait */
2180 ci.stop_codec = true;
2181 id3 = audio_current_track();
2184 /* Save the current playing spot, or NULL if the playlist has ended */
2185 playlist_update_resume_info(id3);
2187 /* TODO: Create auto bookmark too? */
2189 prev_track_elapsed = othertrack_id3->elapsed;
2191 remove_event(BUFFER_EVENT_BUFFER_LOW, buffering_low_buffer_callback);
2194 audio_stop_codec_flush();
2195 paused = false;
2196 playing = false;
2197 track_load_started = false;
2199 filling = STATE_IDLE;
2201 /* Mark all entries null. */
2202 audio_clear_track_entries();
2204 /* Close all tracks */
2205 audio_release_tracks();
2208 static void audio_play_start(size_t offset)
2210 int i;
2212 #if INPUT_SRC_CAPS != 0
2213 audio_set_input_source(AUDIO_SRC_PLAYBACK, SRCF_PLAYBACK);
2214 audio_set_output_source(AUDIO_SRC_PLAYBACK);
2215 #endif
2217 /* Wait for any previously playing audio to flush - TODO: Not necessary? */
2218 paused = false;
2219 audio_stop_codec_flush();
2221 playing = true;
2222 track_load_started = false;
2224 ci.new_track = 0;
2225 ci.seek_time = 0;
2226 wps_offset = 0;
2228 sound_set_volume(global_settings.volume);
2229 track_widx = track_ridx = 0;
2231 /* Clear all track entries. */
2232 for (i = 0; i < MAX_TRACK; i++) {
2233 clear_track_info(&tracks[i]);
2236 last_peek_offset = -1;
2238 /* Officially playing */
2239 queue_reply(&audio_queue, 1);
2241 audio_fill_file_buffer(true, offset);
2243 add_event(BUFFER_EVENT_BUFFER_LOW, false, buffering_low_buffer_callback);
2245 LOGFQUEUE("audio > audio Q_AUDIO_TRACK_CHANGED");
2246 queue_post(&audio_queue, Q_AUDIO_TRACK_CHANGED, 0);
2250 /* Invalidates all but currently playing track. */
2251 static void audio_invalidate_tracks(void)
2253 if (audio_have_tracks())
2255 last_peek_offset = 0;
2256 track_widx = track_ridx;
2258 /* Mark all other entries null (also buffered wrong metadata). */
2259 audio_clear_track_entries();
2261 track_widx = (track_widx + 1) & MAX_TRACK_MASK;
2263 audio_fill_file_buffer(false, 0);
2267 static void audio_new_playlist(void)
2269 /* Prepare to start a new fill from the beginning of the playlist */
2270 last_peek_offset = -1;
2271 if (audio_have_tracks())
2273 if (paused)
2274 skipped_during_pause = true;
2275 track_widx = track_ridx;
2276 audio_clear_track_entries();
2278 track_widx = (track_widx + 1) & MAX_TRACK_MASK;
2280 /* Mark the current track as invalid to prevent skipping back to it */
2281 CUR_TI->taginfo_ready = false;
2284 /* Signal the codec to initiate a track change forward */
2285 new_playlist = true;
2286 ci.new_track = 1;
2288 /* Officially playing */
2289 queue_reply(&audio_queue, 1);
2291 audio_fill_file_buffer(false, 0);
2294 /* Called on manual track skip */
2295 static void audio_initiate_track_change(long direction)
2297 logf("audio_initiate_track_change(%ld)", direction);
2299 ci.new_track += direction;
2300 wps_offset -= direction;
2301 if (paused)
2302 skipped_during_pause = true;
2305 /* Called on manual dir skip */
2306 static void audio_initiate_dir_change(long direction)
2308 dir_skip = true;
2309 ci.new_track = direction;
2310 if (paused)
2311 skipped_during_pause = true;
2314 /* Called when PCM track change is complete */
2315 static void audio_finalise_track_change(void)
2317 logf("audio_finalise_track_change");
2319 if (automatic_skip)
2321 wps_offset = 0;
2322 automatic_skip = false;
2324 /* Invalidate prevtrack_id3 */
2325 memset(othertrack_id3, 0, sizeof(struct mp3entry));
2327 if (prev_ti && prev_ti->audio_hid < 0)
2329 /* No audio left so we clear all the track info. */
2330 clear_track_info(prev_ti);
2333 send_event(PLAYBACK_EVENT_TRACK_CHANGE, thistrack_id3);
2334 playlist_update_resume_info(audio_current_track());
2338 * Layout audio buffer as follows - iram buffer depends on target:
2339 * [|SWAP:iram][|TALK]|FILE|GUARD|PCM|[SWAP:dram[|iram]|]
2341 static void audio_reset_buffer(void)
2343 /* see audio_get_recording_buffer if this is modified */
2344 logf("audio_reset_buffer");
2346 /* If the setup of anything allocated before the file buffer is
2347 changed, do check the adjustments after the buffer_alloc call
2348 as it will likely be affected and need sliding over */
2350 /* Initially set up file buffer as all space available */
2351 malloc_buf = audiobuf + talk_get_bufsize();
2352 /* Align the malloc buf to line size. Especially important to cf
2353 targets that do line reads/writes. */
2354 malloc_buf = (unsigned char *)(((uintptr_t)malloc_buf + 15) & ~15);
2355 filebuf = malloc_buf; /* filebuf line align implied */
2356 filebuflen = audiobufend - filebuf;
2358 filebuflen &= ~15;
2360 /* Subtract whatever the pcm buffer says it used plus the guard buffer */
2361 const size_t pcmbuf_size = pcmbuf_init(filebuf + filebuflen) +GUARD_BUFSIZE;
2363 #ifdef DEBUG
2364 if(pcmbuf_size > filebuflen)
2365 panicf("Not enough memory for pcmbuf_init() : %d > %d",
2366 (int)pcmbuf_size, (int)filebuflen);
2367 #endif
2369 filebuflen -= pcmbuf_size;
2371 /* Make sure filebuflen is a longword multiple after adjustment - filebuf
2372 will already be line aligned */
2373 filebuflen &= ~3;
2375 buffering_reset(filebuf, filebuflen);
2377 /* Clear any references to the file buffer */
2378 buffer_state = AUDIOBUF_STATE_INITIALIZED;
2380 #if defined(ROCKBOX_HAS_LOGF) && defined(LOGF_ENABLE)
2381 /* Make sure everything adds up - yes, some info is a bit redundant but
2382 aids viewing and the sumation of certain variables should add up to
2383 the location of others. */
2385 size_t pcmbufsize;
2386 const unsigned char *pcmbuf = pcmbuf_get_meminfo(&pcmbufsize);
2387 logf("mabuf: %08X", (unsigned)malloc_buf);
2388 logf("fbuf: %08X", (unsigned)filebuf);
2389 logf("fbufe: %08X", (unsigned)(filebuf + filebuflen));
2390 logf("gbuf: %08X", (unsigned)(filebuf + filebuflen));
2391 logf("gbufe: %08X", (unsigned)(filebuf + filebuflen + GUARD_BUFSIZE));
2392 logf("pcmb: %08X", (unsigned)pcmbuf);
2393 logf("pcmbe: %08X", (unsigned)(pcmbuf + pcmbufsize));
2395 #endif
2398 static void audio_thread(void)
2400 struct queue_event ev;
2402 pcm_postinit();
2404 audio_thread_ready = true;
2406 while (1)
2408 if (filling != STATE_FILLING) {
2409 /* End of buffering, let's calculate the watermark and unboost */
2410 set_filebuf_watermark();
2411 cancel_cpu_boost();
2414 if (!pcmbuf_queue_scan(&ev))
2415 queue_wait_w_tmo(&audio_queue, &ev, HZ/2);
2417 switch (ev.id) {
2419 case Q_AUDIO_FILL_BUFFER:
2420 LOGFQUEUE("audio < Q_AUDIO_FILL_BUFFER %d", (int)ev.data);
2421 audio_fill_file_buffer((bool)ev.data, 0);
2422 break;
2424 case Q_AUDIO_FINISH_LOAD:
2425 LOGFQUEUE("audio < Q_AUDIO_FINISH_LOAD");
2426 audio_finish_load_track();
2427 break;
2429 case Q_AUDIO_PLAY:
2430 LOGFQUEUE("audio < Q_AUDIO_PLAY");
2431 if (playing && ev.data <= 0)
2432 audio_new_playlist();
2433 else
2435 audio_stop_playback();
2436 audio_play_start((size_t)ev.data);
2438 break;
2440 case Q_AUDIO_STOP:
2441 LOGFQUEUE("audio < Q_AUDIO_STOP");
2442 if (playing)
2443 audio_stop_playback();
2444 if (ev.data != 0)
2445 queue_clear(&audio_queue);
2446 break;
2448 case Q_AUDIO_PAUSE:
2449 LOGFQUEUE("audio < Q_AUDIO_PAUSE");
2450 if (!(bool) ev.data && skipped_during_pause && !pcmbuf_is_crossfade_active())
2451 pcmbuf_play_stop(); /* Flush old track on resume after skip */
2452 skipped_during_pause = false;
2453 if (!playing)
2454 break;
2455 pcmbuf_pause((bool)ev.data);
2456 paused = (bool)ev.data;
2457 break;
2459 case Q_AUDIO_SKIP:
2460 LOGFQUEUE("audio < Q_AUDIO_SKIP");
2461 audio_initiate_track_change((long)ev.data);
2462 break;
2464 case Q_AUDIO_PRE_FF_REWIND:
2465 LOGFQUEUE("audio < Q_AUDIO_PRE_FF_REWIND");
2466 if (!playing)
2467 break;
2468 pcmbuf_pause(true);
2469 break;
2471 case Q_AUDIO_FF_REWIND:
2472 LOGFQUEUE("audio < Q_AUDIO_FF_REWIND");
2473 if (!playing)
2474 break;
2475 if (automatic_skip)
2477 /* An automatic track skip is in progress. Finalize it,
2478 then go back to the previous track */
2479 audio_finalise_track_change();
2480 ci.new_track = -1;
2482 ci.seek_time = (long)ev.data+1;
2483 break;
2485 case Q_AUDIO_CHECK_NEW_TRACK:
2486 LOGFQUEUE("audio < Q_AUDIO_CHECK_NEW_TRACK");
2487 queue_reply(&audio_queue, audio_check_new_track());
2488 break;
2490 case Q_AUDIO_DIR_SKIP:
2491 LOGFQUEUE("audio < Q_AUDIO_DIR_SKIP");
2492 audio_initiate_dir_change(ev.data);
2493 break;
2495 case Q_AUDIO_FLUSH:
2496 LOGFQUEUE("audio < Q_AUDIO_FLUSH");
2497 audio_invalidate_tracks();
2498 break;
2500 case Q_AUDIO_TRACK_CHANGED:
2501 /* PCM track change done */
2502 LOGFQUEUE("audio < Q_AUDIO_TRACK_CHANGED");
2503 audio_finalise_track_change();
2504 break;
2506 #ifndef SIMULATOR
2507 case SYS_USB_CONNECTED:
2508 LOGFQUEUE("audio < SYS_USB_CONNECTED");
2509 if (playing)
2510 audio_stop_playback();
2511 #ifdef PLAYBACK_VOICE
2512 voice_stop();
2513 #endif
2514 usb_acknowledge(SYS_USB_CONNECTED_ACK);
2515 usb_wait_for_disconnect(&audio_queue);
2517 /* Mark all entries null. */
2518 audio_clear_track_entries();
2520 /* release tracks to make sure all handles are closed */
2521 audio_release_tracks();
2522 break;
2523 #endif
2525 case SYS_TIMEOUT:
2526 LOGFQUEUE_SYS_TIMEOUT("audio < SYS_TIMEOUT");
2527 break;
2529 default:
2530 LOGFQUEUE("audio < default");
2531 break;
2532 } /* end switch */
2533 } /* end while */
2536 /* Initialize the audio system - called from init() in main.c.
2537 * Last function because of all the references to internal symbols
2539 void audio_init(void)
2541 unsigned int audio_thread_id;
2543 /* Can never do this twice */
2544 if (audio_is_initialized)
2546 logf("audio: already initialized");
2547 return;
2550 logf("audio: initializing");
2552 /* Initialize queues before giving control elsewhere in case it likes
2553 to send messages. Thread creation will be delayed however so nothing
2554 starts running until ready if something yields such as talk_init. */
2555 queue_init(&audio_queue, true);
2556 queue_init(&codec_queue, false);
2557 queue_init(&pcmbuf_queue, false);
2559 pcm_init();
2561 /* Initialize codec api. */
2562 ci.read_filebuf = codec_filebuf_callback;
2563 ci.pcmbuf_insert = codec_pcmbuf_insert_callback;
2564 ci.codec_get_buffer = codec_get_buffer;
2565 ci.request_buffer = codec_request_buffer_callback;
2566 ci.advance_buffer = codec_advance_buffer_callback;
2567 ci.advance_buffer_loc = codec_advance_buffer_loc_callback;
2568 ci.request_next_track = codec_request_next_track_callback;
2569 ci.seek_buffer = codec_seek_buffer_callback;
2570 ci.seek_complete = codec_seek_complete_callback;
2571 ci.set_elapsed = codec_set_elapsed_callback;
2572 ci.set_offset = codec_set_offset_callback;
2573 ci.configure = codec_configure_callback;
2574 ci.discard_codec = codec_discard_codec_callback;
2575 ci.dsp = (struct dsp_config *)dsp_configure(NULL, DSP_MYDSP,
2576 CODEC_IDX_AUDIO);
2578 thistrack_id3 = &mp3entry_buf[0];
2579 othertrack_id3 = &mp3entry_buf[1];
2581 /* initialize the buffer */
2582 filebuf = audiobuf;
2584 /* audio_reset_buffer must to know the size of voice buffer so init
2585 talk first */
2586 talk_init();
2588 codec_thread_id = create_thread(
2589 codec_thread, codec_stack, sizeof(codec_stack),
2590 CREATE_THREAD_FROZEN,
2591 codec_thread_name IF_PRIO(, PRIORITY_PLAYBACK)
2592 IF_COP(, CPU));
2594 queue_enable_queue_send(&codec_queue, &codec_queue_sender_list,
2595 codec_thread_id);
2597 audio_thread_id = create_thread(audio_thread, audio_stack,
2598 sizeof(audio_stack), CREATE_THREAD_FROZEN,
2599 audio_thread_name IF_PRIO(, PRIORITY_USER_INTERFACE)
2600 IF_COP(, CPU));
2602 queue_enable_queue_send(&audio_queue, &audio_queue_sender_list,
2603 audio_thread_id);
2605 #ifdef PLAYBACK_VOICE
2606 voice_thread_init();
2607 #endif
2609 /* Set crossfade setting for next buffer init which should be about... */
2610 pcmbuf_crossfade_enable(global_settings.crossfade);
2612 /* initialize the buffering system */
2614 buffering_init();
2615 /* ...now! Set up the buffers */
2616 audio_reset_buffer();
2618 int i;
2619 for(i = 0; i < MAX_TRACK; i++)
2621 tracks[i].audio_hid = -1;
2622 tracks[i].id3_hid = -1;
2623 tracks[i].codec_hid = -1;
2624 #ifdef HAVE_ALBUMART
2625 tracks[i].aa_hid = -1;
2626 #endif
2629 add_event(BUFFER_EVENT_REBUFFER, false, buffering_handle_rebuffer_callback);
2630 add_event(BUFFER_EVENT_FINISHED, false, buffering_handle_finished_callback);
2632 /* Probably safe to say */
2633 audio_is_initialized = true;
2635 sound_settings_apply();
2636 #ifdef HAVE_DISK_STORAGE
2637 audio_set_buffer_margin(global_settings.buffer_margin);
2638 #endif
2640 /* it's safe to let the threads run now */
2641 #ifdef PLAYBACK_VOICE
2642 voice_thread_resume();
2643 #endif
2644 thread_thaw(codec_thread_id);
2645 thread_thaw(audio_thread_id);
2647 } /* audio_init */
2649 bool audio_is_thread_ready(void)
2651 return audio_thread_ready;