Remove the HAVE_RADIO_REGION from the platform config since it's already defined...
[kugel-rb/myfork.git] / apps / playback.c
blob10908821e9485b3d4ce89525fe493e10bd106aec
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 = 5; /* 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 struct playlist_track_info trackinfo;
561 int cur_idx;
562 int offset = ci.new_track + wps_offset;
563 struct mp3entry *write_id3;
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;
581 if (offset != 0)
583 /* Codec may be using thistrack_id3, so it must not be overwritten.
584 If this is a manual skip, othertrack_id3 will become
585 thistrack_id3 in audio_check_new_track().
586 FIXME: If this is an automatic skip, it probably means multiple
587 short tracks fit in the PCM buffer. Overwriting othertrack_id3
588 can lead to an incorrect value later.
589 Note that othertrack_id3 may also be used for next track.
591 write_id3 = othertrack_id3;
593 else
595 write_id3 = thistrack_id3;
598 if (tracks[cur_idx].id3_hid >= 0)
600 /* The current track's info has been buffered but not read yet, so get it */
601 if (bufread(tracks[cur_idx].id3_hid, sizeof(struct mp3entry), write_id3)
602 == sizeof(struct mp3entry))
603 return write_id3;
606 /* We didn't find the ID3 metadata, so we fill temp_id3 with the little info
607 we have and return that. */
609 memset(write_id3, 0, sizeof(struct mp3entry));
611 playlist_get_track_info(NULL, playlist_next(0)+wps_offset, &trackinfo);
612 filename = trackinfo.filename;
613 if (!filename)
614 filename = "No file!";
616 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
617 if (tagcache_fill_tags(write_id3, filename))
618 return write_id3;
619 #endif
621 strncpy(write_id3->path, filename, sizeof(write_id3->path)-1);
622 write_id3->title = strrchr(write_id3->path, '/');
623 if (!write_id3->title)
624 write_id3->title = &write_id3->path[0];
625 else
626 write_id3->title++;
628 return write_id3;
631 struct mp3entry* audio_next_track(void)
633 int next_idx;
634 int offset = ci.new_track + wps_offset;
636 if (!audio_have_tracks())
637 return NULL;
639 if (wps_offset == -1 && *thistrack_id3->path)
641 /* We're in a track transition. The next track for the WPS is the one
642 currently being decoded. */
643 return thistrack_id3;
646 next_idx = (track_ridx + offset + 1) & MAX_TRACK_MASK;
648 if (tracks[next_idx].id3_hid >= 0)
650 if (bufread(tracks[next_idx].id3_hid, sizeof(struct mp3entry), othertrack_id3)
651 == sizeof(struct mp3entry))
652 return othertrack_id3;
653 else
654 return NULL;
657 if (next_idx == track_widx)
659 /* The next track hasn't been buffered yet, so we return the static
660 version of its metadata. */
661 return &unbuffered_id3;
664 return NULL;
667 void audio_play(long offset)
669 logf("audio_play");
671 #ifdef PLAYBACK_VOICE
672 /* Truncate any existing voice output so we don't have spelling
673 * etc. over the first part of the played track */
674 talk_force_shutup();
675 #endif
677 /* Start playback */
678 LOGFQUEUE("audio >| audio Q_AUDIO_PLAY: %ld", offset);
679 /* Don't return until playback has actually started */
680 queue_send(&audio_queue, Q_AUDIO_PLAY, offset);
683 void audio_stop(void)
685 /* Stop playback */
686 LOGFQUEUE("audio >| audio Q_AUDIO_STOP");
687 /* Don't return until playback has actually stopped */
688 queue_send(&audio_queue, Q_AUDIO_STOP, 0);
691 void audio_pause(void)
693 LOGFQUEUE("audio >| audio Q_AUDIO_PAUSE");
694 /* Don't return until playback has actually paused */
695 queue_send(&audio_queue, Q_AUDIO_PAUSE, true);
698 void audio_resume(void)
700 LOGFQUEUE("audio >| audio Q_AUDIO_PAUSE resume");
701 /* Don't return until playback has actually resumed */
702 queue_send(&audio_queue, Q_AUDIO_PAUSE, false);
705 void audio_skip(int direction)
707 if (playlist_check(ci.new_track + wps_offset + direction))
709 if (global_settings.beep)
710 pcmbuf_beep(2000, 100, 2500*global_settings.beep);
712 LOGFQUEUE("audio > audio Q_AUDIO_SKIP %d", direction);
713 queue_post(&audio_queue, Q_AUDIO_SKIP, direction);
714 /* Update wps while our message travels inside deep playback queues. */
715 wps_offset += direction;
717 else
719 /* No more tracks. */
720 if (global_settings.beep)
721 pcmbuf_beep(1000, 100, 1500*global_settings.beep);
725 void audio_next(void)
727 audio_skip(1);
730 void audio_prev(void)
732 audio_skip(-1);
735 void audio_next_dir(void)
737 LOGFQUEUE("audio > audio Q_AUDIO_DIR_SKIP 1");
738 queue_post(&audio_queue, Q_AUDIO_DIR_SKIP, 1);
741 void audio_prev_dir(void)
743 LOGFQUEUE("audio > audio Q_AUDIO_DIR_SKIP -1");
744 queue_post(&audio_queue, Q_AUDIO_DIR_SKIP, -1);
747 void audio_pre_ff_rewind(void)
749 LOGFQUEUE("audio > audio Q_AUDIO_PRE_FF_REWIND");
750 queue_post(&audio_queue, Q_AUDIO_PRE_FF_REWIND, 0);
753 void audio_ff_rewind(long newpos)
755 LOGFQUEUE("audio > audio Q_AUDIO_FF_REWIND");
756 queue_post(&audio_queue, Q_AUDIO_FF_REWIND, newpos);
759 void audio_flush_and_reload_tracks(void)
761 LOGFQUEUE("audio > audio Q_AUDIO_FLUSH");
762 queue_post(&audio_queue, Q_AUDIO_FLUSH, 0);
765 void audio_error_clear(void)
767 #ifdef AUDIO_HAVE_RECORDING
768 pcm_rec_error_clear();
769 #endif
772 int audio_status(void)
774 int ret = 0;
776 if (playing)
777 ret |= AUDIO_STATUS_PLAY;
779 if (paused)
780 ret |= AUDIO_STATUS_PAUSE;
782 #ifdef HAVE_RECORDING
783 /* Do this here for constitency with mpeg.c version */
784 ret |= pcm_rec_status();
785 #endif
787 return ret;
790 int audio_get_file_pos(void)
792 return 0;
795 #ifdef HAVE_DISK_STORAGE
796 void audio_set_buffer_margin(int setting)
798 static const unsigned short lookup[] = {5, 15, 30, 60, 120, 180, 300, 600};
799 buffer_margin = lookup[setting];
800 logf("buffer margin: %ld", (long)buffer_margin);
801 set_filebuf_watermark();
803 #endif
805 /* Take necessary steps to enable or disable the crossfade setting */
806 void audio_set_crossfade(int enable)
808 size_t offset;
809 bool was_playing;
810 size_t size;
812 /* Tell it the next setting to use */
813 pcmbuf_crossfade_enable(enable);
815 /* Return if size hasn't changed or this is too early to determine
816 which in the second case there's no way we could be playing
817 anything at all */
818 if (pcmbuf_is_same_size())
820 /* This function is a copout and just syncs some variables -
821 to be removed at a later date */
822 pcmbuf_crossfade_enable_finished();
823 return;
826 offset = 0;
827 was_playing = playing;
829 /* Playback has to be stopped before changing the buffer size */
830 if (was_playing)
832 /* Store the track resume position */
833 offset = thistrack_id3->offset;
836 /* Blast it - audio buffer will have to be setup again next time
837 something plays */
838 audio_get_buffer(true, &size);
840 /* Restart playback if audio was running previously */
841 if (was_playing)
842 audio_play(offset);
845 /* --- Routines called from multiple threads --- */
847 static void set_filebuf_watermark(void)
849 if (!filebuf)
850 return; /* Audio buffers not yet set up */
852 #ifdef HAVE_DISK_STORAGE
853 int seconds;
854 int spinup = ata_spinup_time();
855 if (spinup)
856 seconds = (spinup / HZ) + 1;
857 else
858 seconds = 5;
860 seconds += buffer_margin;
861 #else
862 /* flash storage */
863 int seconds = 1;
864 #endif
866 /* bitrate of last track in buffer dictates watermark */
867 struct mp3entry* id3 = NULL;
868 if (tracks[track_widx].taginfo_ready)
869 id3 = bufgetid3(tracks[track_widx].id3_hid);
870 else
871 id3 = bufgetid3(tracks[track_widx-1].id3_hid);
872 if (!id3) {
873 logf("fwmark: No id3 for last track (r%d/w%d), aborting!", track_ridx, track_widx);
874 return;
876 size_t bytes = id3->bitrate * (1000/8) * seconds;
877 buf_set_watermark(bytes);
878 logf("fwmark: %d", bytes);
881 const char *get_codec_filename(int cod_spec)
883 const char *fname;
885 #ifdef HAVE_RECORDING
886 /* Can choose decoder or encoder if one available */
887 int type = cod_spec & CODEC_TYPE_MASK;
888 int afmt = cod_spec & CODEC_AFMT_MASK;
890 if ((unsigned)afmt >= AFMT_NUM_CODECS)
891 type = AFMT_UNKNOWN | (type & CODEC_TYPE_MASK);
893 fname = (type == CODEC_TYPE_ENCODER) ?
894 audio_formats[afmt].codec_enc_root_fn :
895 audio_formats[afmt].codec_root_fn;
897 logf("%s: %d - %s",
898 (type == CODEC_TYPE_ENCODER) ? "Encoder" : "Decoder",
899 afmt, fname ? fname : "<unknown>");
900 #else /* !HAVE_RECORDING */
901 /* Always decoder */
902 if ((unsigned)cod_spec >= AFMT_NUM_CODECS)
903 cod_spec = AFMT_UNKNOWN;
904 fname = audio_formats[cod_spec].codec_root_fn;
905 logf("Codec: %d - %s", cod_spec, fname ? fname : "<unknown>");
906 #endif /* HAVE_RECORDING */
908 return fname;
909 } /* get_codec_filename */
911 /* --- Codec thread --- */
912 static bool codec_pcmbuf_insert_callback(
913 const void *ch1, const void *ch2, int count)
915 const char *src[2] = { ch1, ch2 };
917 while (count > 0)
919 int out_count = dsp_output_count(ci.dsp, count);
920 int inp_count;
921 char *dest;
923 /* Prevent audio from a previous track from playing */
924 if (ci.new_track || ci.stop_codec)
925 return true;
927 while ((dest = pcmbuf_request_buffer(&out_count)) == NULL)
929 cancel_cpu_boost();
930 sleep(1);
931 if (ci.seek_time || ci.new_track || ci.stop_codec)
932 return true;
935 /* Get the real input_size for output_size bytes, guarding
936 * against resampling buffer overflows. */
937 inp_count = dsp_input_count(ci.dsp, out_count);
939 if (inp_count <= 0)
940 return true;
942 /* Input size has grown, no error, just don't write more than length */
943 if (inp_count > count)
944 inp_count = count;
946 out_count = dsp_process(ci.dsp, dest, src, inp_count);
948 if (out_count <= 0)
949 return true;
951 pcmbuf_write_complete(out_count);
953 count -= inp_count;
956 return true;
957 } /* codec_pcmbuf_insert_callback */
959 static void* codec_get_buffer(size_t *size)
961 if (codec_size >= CODEC_SIZE)
962 return NULL;
963 *size = CODEC_SIZE - codec_size;
964 return &codecbuf[codec_size];
967 /* Between the codec and PCM track change, we need to keep updating the
968 "elapsed" value of the previous (to the codec, but current to the
969 user/PCM/WPS) track, so that the progressbar reaches the end.
970 During that transition, the WPS will display prevtrack_id3. */
971 static void codec_pcmbuf_position_callback(size_t size) ICODE_ATTR;
972 static void codec_pcmbuf_position_callback(size_t size)
974 /* This is called from an ISR, so be quick */
975 unsigned int time = size * 1000 / 4 / NATIVE_FREQUENCY +
976 othertrack_id3->elapsed;
978 if (time >= othertrack_id3->length)
980 pcmbuf_set_position_callback(NULL);
981 othertrack_id3->elapsed = othertrack_id3->length;
983 else
984 othertrack_id3->elapsed = time;
987 static void codec_set_elapsed_callback(unsigned int value)
989 unsigned int latency;
990 if (ci.seek_time)
991 return;
993 #ifdef AB_REPEAT_ENABLE
994 ab_position_report(value);
995 #endif
997 latency = pcmbuf_get_latency();
998 if (value < latency)
999 thistrack_id3->elapsed = 0;
1000 else if (value - latency > thistrack_id3->elapsed ||
1001 value - latency < thistrack_id3->elapsed - 2)
1003 thistrack_id3->elapsed = value - latency;
1007 static void codec_set_offset_callback(size_t value)
1009 unsigned int latency;
1011 if (ci.seek_time)
1012 return;
1014 latency = pcmbuf_get_latency() * thistrack_id3->bitrate / 8;
1015 if (value < latency)
1016 thistrack_id3->offset = 0;
1017 else
1018 thistrack_id3->offset = value - latency;
1021 static void codec_advance_buffer_counters(size_t amount)
1023 bufadvance(CUR_TI->audio_hid, amount);
1024 ci.curpos += amount;
1027 /* copy up-to size bytes into ptr and return the actual size copied */
1028 static size_t codec_filebuf_callback(void *ptr, size_t size)
1030 ssize_t copy_n;
1032 if (ci.stop_codec || !playing)
1033 return 0;
1035 copy_n = bufread(CUR_TI->audio_hid, size, ptr);
1037 /* Nothing requested OR nothing left */
1038 if (copy_n == 0)
1039 return 0;
1041 /* Update read and other position pointers */
1042 codec_advance_buffer_counters(copy_n);
1044 /* Return the actual amount of data copied to the buffer */
1045 return copy_n;
1046 } /* codec_filebuf_callback */
1048 static void* codec_request_buffer_callback(size_t *realsize, size_t reqsize)
1050 size_t copy_n = reqsize;
1051 ssize_t ret;
1052 void *ptr;
1054 if (!playing)
1056 *realsize = 0;
1057 return NULL;
1060 ret = bufgetdata(CUR_TI->audio_hid, reqsize, &ptr);
1061 if (ret >= 0)
1062 copy_n = MIN((size_t)ret, reqsize);
1064 if (copy_n == 0)
1066 *realsize = 0;
1067 return NULL;
1070 *realsize = copy_n;
1072 return ptr;
1073 } /* codec_request_buffer_callback */
1075 static int get_codec_base_type(int type)
1077 switch (type) {
1078 case AFMT_MPA_L1:
1079 case AFMT_MPA_L2:
1080 case AFMT_MPA_L3:
1081 return AFMT_MPA_L3;
1084 return type;
1087 static void codec_advance_buffer_callback(size_t amount)
1089 codec_advance_buffer_counters(amount);
1090 codec_set_offset_callback(ci.curpos);
1093 static void codec_advance_buffer_loc_callback(void *ptr)
1095 size_t amount = buf_get_offset(CUR_TI->audio_hid, ptr);
1096 codec_advance_buffer_callback(amount);
1099 static void codec_seek_complete_callback(void)
1101 logf("seek_complete");
1102 if (pcm_is_paused())
1104 /* If this is not a seamless seek, clear the buffer */
1105 pcmbuf_play_stop();
1106 dsp_configure(ci.dsp, DSP_FLUSH, 0);
1108 /* If playback was not 'deliberately' paused, unpause now */
1109 if (!paused)
1110 pcmbuf_pause(false);
1112 ci.seek_time = 0;
1115 static bool codec_seek_buffer_callback(size_t newpos)
1117 logf("codec_seek_buffer_callback");
1119 int ret = bufseek(CUR_TI->audio_hid, newpos);
1120 if (ret == 0) {
1121 ci.curpos = newpos;
1122 return true;
1124 else {
1125 return false;
1129 static void codec_configure_callback(int setting, intptr_t value)
1131 switch (setting) {
1132 default:
1133 if (!dsp_configure(ci.dsp, setting, value))
1134 { logf("Illegal key:%d", setting); }
1138 static void codec_track_changed(void)
1140 LOGFQUEUE("codec > audio Q_AUDIO_TRACK_CHANGED");
1141 queue_post(&audio_queue, Q_AUDIO_TRACK_CHANGED, 0);
1144 static void codec_pcmbuf_track_changed_callback(void)
1146 pcmbuf_set_position_callback(NULL);
1147 pcmbuf_callback_queue_post(Q_AUDIO_TRACK_CHANGED, 0);
1150 static void codec_discard_codec_callback(void)
1152 if (CUR_TI->codec_hid >= 0)
1154 bufclose(CUR_TI->codec_hid);
1155 CUR_TI->codec_hid = -1;
1159 static inline void codec_gapless_track_change(void)
1161 /* callback keeps the progress bar moving while the pcmbuf empties */
1162 pcmbuf_set_position_callback(codec_pcmbuf_position_callback);
1163 /* set the pcmbuf callback for when the track really changes */
1164 pcmbuf_set_event_handler(codec_pcmbuf_track_changed_callback);
1167 static inline void codec_crossfade_track_change(void)
1169 /* Initiate automatic crossfade mode */
1170 pcmbuf_crossfade_init(false);
1171 /* Notify the wps that the track change starts now */
1172 codec_track_changed();
1175 static void codec_track_skip_done(bool was_manual)
1177 /* Manual track change (always crossfade or flush audio). */
1178 if (was_manual)
1180 pcmbuf_crossfade_init(true);
1181 LOGFQUEUE("codec > audio Q_AUDIO_TRACK_CHANGED");
1182 queue_post(&audio_queue, Q_AUDIO_TRACK_CHANGED, 0);
1184 /* Automatic track change w/crossfade, if not in "Track Skip Only" mode. */
1185 else if (pcmbuf_is_crossfade_enabled() && !pcmbuf_is_crossfade_active()
1186 && global_settings.crossfade != CROSSFADE_ENABLE_TRACKSKIP)
1188 if (global_settings.crossfade == CROSSFADE_ENABLE_SHUFFLE_AND_TRACKSKIP)
1190 if (global_settings.playlist_shuffle)
1191 /* shuffle mode is on, so crossfade: */
1192 codec_crossfade_track_change();
1193 else
1194 /* shuffle mode is off, so do a gapless track change */
1195 codec_gapless_track_change();
1197 else
1198 /* normal crossfade: */
1199 codec_crossfade_track_change();
1201 else
1202 /* normal gapless playback. */
1203 codec_gapless_track_change();
1206 static bool codec_load_next_track(void)
1208 intptr_t result = Q_CODEC_REQUEST_FAILED;
1210 prev_track_elapsed = thistrack_id3->elapsed;
1212 #ifdef AB_REPEAT_ENABLE
1213 ab_end_of_track_report();
1214 #endif
1216 logf("Request new track");
1218 if (ci.new_track == 0)
1220 ci.new_track++;
1221 automatic_skip = true;
1224 if (!ci.stop_codec)
1226 trigger_cpu_boost();
1227 LOGFQUEUE("codec >| audio Q_AUDIO_CHECK_NEW_TRACK");
1228 result = queue_send(&audio_queue, Q_AUDIO_CHECK_NEW_TRACK, 0);
1231 switch (result)
1233 case Q_CODEC_REQUEST_COMPLETE:
1234 LOGFQUEUE("codec |< Q_CODEC_REQUEST_COMPLETE");
1235 codec_track_skip_done(!automatic_skip);
1236 return true;
1238 case Q_CODEC_REQUEST_FAILED:
1239 LOGFQUEUE("codec |< Q_CODEC_REQUEST_FAILED");
1240 ci.new_track = 0;
1241 ci.stop_codec = true;
1242 codec_requested_stop = true;
1243 return false;
1245 default:
1246 LOGFQUEUE("codec |< default");
1247 ci.stop_codec = true;
1248 codec_requested_stop = true;
1249 return false;
1253 static bool codec_request_next_track_callback(void)
1255 int prev_codectype;
1257 if (ci.stop_codec || !playing)
1258 return false;
1260 prev_codectype = get_codec_base_type(thistrack_id3->codectype);
1261 if (!codec_load_next_track())
1262 return false;
1264 /* Seek to the beginning of the new track because if the struct
1265 mp3entry was buffered, "elapsed" might not be zero (if the track has
1266 been played already but not unbuffered) */
1267 codec_seek_buffer_callback(thistrack_id3->first_frame_offset);
1268 /* Check if the next codec is the same file. */
1269 if (prev_codectype == get_codec_base_type(thistrack_id3->codectype))
1271 logf("New track loaded");
1272 codec_discard_codec_callback();
1273 return true;
1275 else
1277 logf("New codec:%d/%d", thistrack_id3->codectype, prev_codectype);
1278 return false;
1282 static void codec_thread(void)
1284 struct queue_event ev;
1285 int status;
1287 while (1) {
1288 status = 0;
1290 if (!pcmbuf_is_crossfade_active()) {
1291 cancel_cpu_boost();
1294 queue_wait(&codec_queue, &ev);
1295 codec_requested_stop = false;
1297 switch (ev.id) {
1298 case Q_CODEC_LOAD_DISK:
1299 LOGFQUEUE("codec < Q_CODEC_LOAD_DISK");
1300 queue_reply(&codec_queue, 1);
1301 audio_codec_loaded = true;
1302 ci.stop_codec = false;
1303 status = codec_load_file((const char *)ev.data, &ci);
1304 LOGFQUEUE("codec_load_file %s %d\n", (const char *)ev.data, status);
1305 break;
1307 case Q_CODEC_LOAD:
1308 LOGFQUEUE("codec < Q_CODEC_LOAD");
1309 if (CUR_TI->codec_hid < 0) {
1310 logf("Codec slot is empty!");
1311 /* Wait for the pcm buffer to go empty */
1312 while (pcm_is_playing())
1313 yield();
1314 /* This must be set to prevent an infinite loop */
1315 ci.stop_codec = true;
1316 LOGFQUEUE("codec > codec Q_AUDIO_PLAY");
1317 queue_post(&codec_queue, Q_AUDIO_PLAY, 0);
1318 break;
1321 audio_codec_loaded = true;
1322 ci.stop_codec = false;
1323 status = codec_load_buf(CUR_TI->codec_hid, &ci);
1324 LOGFQUEUE("codec_load_buf %d\n", status);
1325 break;
1327 case Q_CODEC_DO_CALLBACK:
1328 LOGFQUEUE("codec < Q_CODEC_DO_CALLBACK");
1329 queue_reply(&codec_queue, 1);
1330 if ((void*)ev.data != NULL)
1332 cpucache_invalidate();
1333 ((void (*)(void))ev.data)();
1334 cpucache_flush();
1336 break;
1338 #ifdef AUDIO_HAVE_RECORDING
1339 case Q_ENCODER_LOAD_DISK:
1340 LOGFQUEUE("codec < Q_ENCODER_LOAD_DISK");
1341 audio_codec_loaded = false; /* Not audio codec! */
1342 logf("loading encoder");
1343 ci.stop_encoder = false;
1344 status = codec_load_file((const char *)ev.data, &ci);
1345 logf("encoder stopped");
1346 break;
1347 #endif /* AUDIO_HAVE_RECORDING */
1349 default:
1350 LOGFQUEUE("codec < default");
1353 if (audio_codec_loaded)
1355 if (ci.stop_codec)
1357 status = CODEC_OK;
1358 if (!playing)
1359 pcmbuf_play_stop();
1362 audio_codec_loaded = false;
1365 switch (ev.id) {
1366 case Q_CODEC_LOAD_DISK:
1367 case Q_CODEC_LOAD:
1368 LOGFQUEUE("codec < Q_CODEC_LOAD");
1369 if (playing)
1371 if (ci.new_track || status != CODEC_OK)
1373 if (!ci.new_track)
1375 logf("Codec failure, %d %d", ci.new_track, status);
1376 splash(HZ*2, "Codec failure");
1379 if (!codec_load_next_track())
1381 LOGFQUEUE("codec > audio Q_AUDIO_STOP");
1382 /* End of playlist */
1383 queue_post(&audio_queue, Q_AUDIO_STOP, 0);
1384 break;
1387 else
1389 logf("Codec finished");
1390 if (ci.stop_codec)
1392 /* Wait for the audio to stop playing before
1393 * triggering the WPS exit */
1394 while(pcm_is_playing())
1396 /* There has been one too many struct pointer swaps by now
1397 * so even though it says othertrack_id3, its the correct one! */
1398 othertrack_id3->elapsed =
1399 othertrack_id3->length - pcmbuf_get_latency();
1400 sleep(1);
1403 if (codec_requested_stop)
1405 LOGFQUEUE("codec > audio Q_AUDIO_STOP");
1406 queue_post(&audio_queue, Q_AUDIO_STOP, 0);
1408 break;
1412 if (CUR_TI->codec_hid >= 0)
1414 LOGFQUEUE("codec > codec Q_CODEC_LOAD");
1415 queue_post(&codec_queue, Q_CODEC_LOAD, 0);
1417 else
1419 const char *codec_fn =
1420 get_codec_filename(thistrack_id3->codectype);
1421 if (codec_fn)
1423 LOGFQUEUE("codec > codec Q_CODEC_LOAD_DISK");
1424 queue_post(&codec_queue, Q_CODEC_LOAD_DISK,
1425 (intptr_t)codec_fn);
1429 break;
1431 #ifdef AUDIO_HAVE_RECORDING
1432 case Q_ENCODER_LOAD_DISK:
1433 LOGFQUEUE("codec < Q_ENCODER_LOAD_DISK");
1435 if (status == CODEC_OK)
1436 break;
1438 logf("Encoder failure");
1439 splash(HZ*2, "Encoder failure");
1441 if (ci.enc_codec_loaded < 0)
1442 break;
1444 logf("Encoder failed to load");
1445 ci.enc_codec_loaded = -1;
1446 break;
1447 #endif /* AUDIO_HAVE_RECORDING */
1449 default:
1450 LOGFQUEUE("codec < default");
1452 } /* end switch */
1456 /* Borrow the codec thread and return the ID */
1457 void codec_thread_do_callback(void (*fn)(void), unsigned int *id)
1459 /* Set id before telling thread to call something; it may be
1460 * needed before this function returns. */
1461 if (id != NULL)
1462 *id = codec_thread_id;
1464 /* Codec thread will signal just before entering callback */
1465 LOGFQUEUE("codec >| Q_CODEC_DO_CALLBACK");
1466 queue_send(&codec_queue, Q_CODEC_DO_CALLBACK, (intptr_t)fn);
1469 /* --- Buffering callbacks --- */
1471 static void buffering_low_buffer_callback(void *data)
1473 (void)data;
1474 logf("low buffer callback");
1476 if (filling == STATE_FULL || filling == STATE_END_OF_PLAYLIST) {
1477 /* force a refill */
1478 LOGFQUEUE("buffering > audio Q_AUDIO_FILL_BUFFER");
1479 queue_post(&audio_queue, Q_AUDIO_FILL_BUFFER, 0);
1483 static void buffering_handle_rebuffer_callback(void *data)
1485 (void)data;
1486 LOGFQUEUE("audio >| audio Q_AUDIO_FLUSH");
1487 queue_post(&audio_queue, Q_AUDIO_FLUSH, 0);
1490 static void buffering_handle_finished_callback(int *data)
1492 logf("handle %d finished buffering", *data);
1494 if (*data == tracks[track_widx].id3_hid)
1496 int offset = ci.new_track + wps_offset;
1497 int next_idx = (track_ridx + offset + 1) & MAX_TRACK_MASK;
1498 /* The metadata handle for the last loaded track has been buffered.
1499 We can ask the audio thread to load the rest of the track's data. */
1500 LOGFQUEUE("audio >| audio Q_AUDIO_FINISH_LOAD");
1501 queue_post(&audio_queue, Q_AUDIO_FINISH_LOAD, 0);
1502 if (tracks[next_idx].id3_hid == *data)
1503 send_event(PLAYBACK_EVENT_NEXTTRACKID3_AVAILABLE, NULL);
1505 else
1507 /* This is most likely an audio handle, so we strip the useless
1508 trailing tags that are left. */
1509 strip_tags(*data);
1511 if (*data == tracks[track_widx-1].audio_hid
1512 && filling == STATE_END_OF_PLAYLIST)
1514 /* This was the last track in the playlist.
1515 We now have all the data we need. */
1516 logf("last track finished buffering");
1517 filling = STATE_FINISHED;
1523 /* --- Audio thread --- */
1525 static bool audio_have_tracks(void)
1527 return (audio_track_count() != 0);
1530 static int audio_free_track_count(void)
1532 /* Used tracks + free tracks adds up to MAX_TRACK - 1 */
1533 return MAX_TRACK - 1 - audio_track_count();
1536 int audio_track_count(void)
1538 /* Calculate difference from track_ridx to track_widx
1539 * taking into account a possible wrap-around. */
1540 return (MAX_TRACK + track_widx - track_ridx) & MAX_TRACK_MASK;
1543 long audio_filebufused(void)
1545 return (long) buf_used();
1548 /* Update track info after successful a codec track change */
1549 static void audio_update_trackinfo(void)
1551 /* Load the curent track's metadata into curtrack_id3 */
1552 if (CUR_TI->id3_hid >= 0)
1553 copy_mp3entry(thistrack_id3, bufgetid3(CUR_TI->id3_hid));
1555 /* Reset current position */
1556 thistrack_id3->elapsed = 0;
1557 thistrack_id3->offset = 0;
1559 /* Update the codec API */
1560 ci.filesize = CUR_TI->filesize;
1561 ci.id3 = thistrack_id3;
1562 ci.curpos = 0;
1563 ci.taginfo_ready = &CUR_TI->taginfo_ready;
1566 /* Clear tracks between write and read, non inclusive */
1567 static void audio_clear_track_entries(void)
1569 int cur_idx = track_widx;
1571 logf("Clearing tracks:%d/%d", track_ridx, track_widx);
1573 /* Loop over all tracks from write-to-read */
1574 while (1)
1576 cur_idx = (cur_idx + 1) & MAX_TRACK_MASK;
1578 if (cur_idx == track_ridx)
1579 break;
1581 clear_track_info(&tracks[cur_idx]);
1585 /* Clear all tracks */
1586 static bool audio_release_tracks(void)
1588 int i, cur_idx;
1590 logf("releasing all tracks");
1592 for(i = 0; i < MAX_TRACK; i++)
1594 cur_idx = (track_ridx + i) & MAX_TRACK_MASK;
1595 if (!clear_track_info(&tracks[cur_idx]))
1596 return false;
1599 return true;
1602 static bool audio_loadcodec(bool start_play)
1604 int prev_track;
1605 char codec_path[MAX_PATH]; /* Full path to codec */
1606 const struct mp3entry *id3, *prev_id3;
1608 if (tracks[track_widx].id3_hid < 0) {
1609 return false;
1612 id3 = bufgetid3(tracks[track_widx].id3_hid);
1613 if (!id3)
1614 return false;
1616 const char *codec_fn = get_codec_filename(id3->codectype);
1617 if (codec_fn == NULL)
1618 return false;
1620 tracks[track_widx].codec_hid = -1;
1622 if (start_play)
1624 /* Load the codec directly from disk and save some memory. */
1625 track_ridx = track_widx;
1626 ci.filesize = CUR_TI->filesize;
1627 ci.id3 = thistrack_id3;
1628 ci.taginfo_ready = &CUR_TI->taginfo_ready;
1629 ci.curpos = 0;
1630 LOGFQUEUE("codec > codec Q_CODEC_LOAD_DISK");
1631 queue_post(&codec_queue, Q_CODEC_LOAD_DISK, (intptr_t)codec_fn);
1632 return true;
1634 else
1636 /* If we already have another track than this one buffered */
1637 if (track_widx != track_ridx)
1639 prev_track = (track_widx - 1) & MAX_TRACK_MASK;
1641 id3 = bufgetid3(tracks[track_widx].id3_hid);
1642 prev_id3 = bufgetid3(tracks[prev_track].id3_hid);
1644 /* If the previous codec is the same as this one, there is no need
1645 * to put another copy of it on the file buffer */
1646 if (id3 && prev_id3 &&
1647 get_codec_base_type(id3->codectype) ==
1648 get_codec_base_type(prev_id3->codectype)
1649 && audio_codec_loaded)
1651 logf("Reusing prev. codec");
1652 return true;
1657 codec_get_full_path(codec_path, codec_fn);
1659 tracks[track_widx].codec_hid = bufopen(codec_path, 0, TYPE_CODEC);
1660 if (tracks[track_widx].codec_hid < 0)
1661 return false;
1663 logf("Loaded codec");
1665 return true;
1668 /* Load metadata for the next track (with bufopen). The rest of the track
1669 loading will be handled by audio_finish_load_track once the metadata has been
1670 actually loaded by the buffering thread. */
1671 static bool audio_load_track(size_t offset, bool start_play)
1673 const char *trackname;
1674 int fd = -1;
1676 if (track_load_started) {
1677 /* There is already a track load in progress, so track_widx hasn't been
1678 incremented yet. Loading another track would overwrite the one that
1679 hasn't finished loading. */
1680 logf("audio_load_track(): a track load is already in progress");
1681 return false;
1684 start_play_g = start_play; /* will be read by audio_finish_load_track */
1686 /* Stop buffer filling if there is no free track entries.
1687 Don't fill up the last track entry (we wan't to store next track
1688 metadata there). */
1689 if (!audio_free_track_count())
1691 logf("No free tracks");
1692 return false;
1695 last_peek_offset++;
1696 tracks[track_widx].taginfo_ready = false;
1698 logf("Buffering track:%d/%d", track_widx, track_ridx);
1699 /* Get track name from current playlist read position. */
1700 while ((trackname = playlist_peek(last_peek_offset)) != NULL)
1702 /* Handle broken playlists. */
1703 fd = open(trackname, O_RDONLY);
1704 if (fd < 0)
1706 logf("Open failed");
1707 /* Skip invalid entry from playlist. */
1708 playlist_skip_entry(NULL, last_peek_offset);
1710 else
1711 break;
1714 if (!trackname)
1716 logf("End-of-playlist");
1717 memset(&unbuffered_id3, 0, sizeof(struct mp3entry));
1718 filling = STATE_END_OF_PLAYLIST;
1720 if (thistrack_id3->length == 0 && thistrack_id3->filesize == 0)
1722 /* Stop playback if no valid track was found. */
1723 audio_stop_playback();
1726 return false;
1729 tracks[track_widx].filesize = filesize(fd);
1731 if (offset > tracks[track_widx].filesize)
1732 offset = 0;
1734 /* Set default values */
1735 if (start_play)
1737 buf_set_watermark(filebuflen/2);
1738 dsp_configure(ci.dsp, DSP_RESET, 0);
1739 playlist_update_resume_info(audio_current_track());
1742 /* Get track metadata if we don't already have it. */
1743 if (tracks[track_widx].id3_hid < 0)
1745 tracks[track_widx].id3_hid = bufopen(trackname, 0, TYPE_ID3);
1747 if (tracks[track_widx].id3_hid < 0)
1749 /* Buffer is full. */
1750 get_metadata(&unbuffered_id3, fd, trackname);
1751 last_peek_offset--;
1752 close(fd);
1753 logf("buffer is full for now");
1754 filling = STATE_FULL;
1755 return false;
1758 if (track_widx == track_ridx)
1760 /* TODO: Superfluos buffering call? */
1761 buf_request_buffer_handle(tracks[track_widx].id3_hid);
1762 struct mp3entry *id3 = bufgetid3(tracks[track_widx].id3_hid);
1763 if (id3)
1765 copy_mp3entry(thistrack_id3, id3);
1766 thistrack_id3->offset = offset;
1768 else
1769 memset(thistrack_id3, 0, sizeof(struct mp3entry));
1772 if (start_play)
1774 playlist_update_resume_info(audio_current_track());
1778 close(fd);
1779 track_load_started = true; /* Remember that we've started loading a track */
1780 return true;
1783 /* Second part of the track loading: We now have the metadata available, so we
1784 can load the codec, the album art and finally the audio data.
1785 This is called on the audio thread after the buffering thread calls the
1786 buffering_handle_finished_callback callback. */
1787 static void audio_finish_load_track(void)
1789 size_t file_offset = 0;
1790 size_t offset = 0;
1791 bool start_play = start_play_g;
1793 track_load_started = false;
1795 if (tracks[track_widx].id3_hid < 0) {
1796 logf("no metatdata");
1797 return;
1800 struct mp3entry *track_id3;
1802 if (track_widx == track_ridx)
1803 track_id3 = thistrack_id3;
1804 else
1805 track_id3 = bufgetid3(tracks[track_widx].id3_hid);
1807 if (track_id3->length == 0 && track_id3->filesize == 0)
1809 logf("audio_finish_load_track: invalid metadata");
1811 /* Invalid metadata */
1812 bufclose(tracks[track_widx].id3_hid);
1813 tracks[track_widx].id3_hid = -1;
1815 /* Skip invalid entry from playlist. */
1816 playlist_skip_entry(NULL, last_peek_offset--);
1818 /* load next track */
1819 LOGFQUEUE("audio > audio Q_AUDIO_FILL_BUFFER %d", (int)start_play);
1820 queue_post(&audio_queue, Q_AUDIO_FILL_BUFFER, start_play);
1822 return;
1825 #ifdef HAVE_ALBUMART
1826 if (tracks[track_widx].aa_hid < 0 && gui_sync_wps_uses_albumart())
1828 char aa_path[MAX_PATH];
1829 if (find_albumart(track_id3, aa_path, sizeof(aa_path)))
1831 tracks[track_widx].aa_hid = bufopen(aa_path, 0, TYPE_BITMAP);
1833 if(tracks[track_widx].aa_hid == ERR_BUFFER_FULL)
1835 filling = STATE_FULL;
1836 logf("buffer is full for now");
1837 return; /* No space for track's album art, not an error */
1839 else if (tracks[track_widx].aa_hid < 0)
1841 /* another error, ignore AlbumArt */
1842 logf("Album art loading failed");
1846 #endif
1848 /* Load the codec. */
1849 if (!audio_loadcodec(start_play))
1851 if (tracks[track_widx].codec_hid == ERR_BUFFER_FULL)
1853 /* No space for codec on buffer, not an error */
1854 filling = STATE_FULL;
1855 return;
1858 /* This is an error condition, either no codec was found, or reading
1859 * the codec file failed part way through, either way, skip the track */
1860 /* FIXME: We should not use splashf from audio thread! */
1861 splashf(HZ*2, "No codec for: %s", track_id3->path);
1862 /* Skip invalid entry from playlist. */
1863 playlist_skip_entry(NULL, last_peek_offset);
1864 return;
1867 track_id3->elapsed = 0;
1868 offset = track_id3->offset;
1870 enum data_type type = TYPE_PACKET_AUDIO;
1872 switch (track_id3->codectype) {
1873 case AFMT_MPA_L1:
1874 case AFMT_MPA_L2:
1875 case AFMT_MPA_L3:
1876 if (offset > 0) {
1877 file_offset = offset;
1878 track_id3->offset = offset;
1880 break;
1882 case AFMT_WAVPACK:
1883 if (offset > 0) {
1884 file_offset = offset;
1885 track_id3->offset = offset;
1886 track_id3->elapsed = track_id3->length / 2;
1888 break;
1890 case AFMT_OGG_VORBIS:
1891 case AFMT_SPEEX:
1892 case AFMT_FLAC:
1893 case AFMT_PCM_WAV:
1894 case AFMT_A52:
1895 case AFMT_AAC:
1896 case AFMT_MPC:
1897 case AFMT_APE:
1898 case AFMT_WMA:
1899 if (offset > 0)
1900 track_id3->offset = offset;
1901 break;
1903 case AFMT_NSF:
1904 case AFMT_SPC:
1905 case AFMT_SID:
1906 logf("Loading atomic %d",track_id3->codectype);
1907 type = TYPE_ATOMIC_AUDIO;
1908 break;
1911 logf("alt:%s", track_id3->path);
1913 if (file_offset > AUDIO_REBUFFER_GUESS_SIZE)
1914 file_offset -= AUDIO_REBUFFER_GUESS_SIZE;
1915 else if (track_id3->first_frame_offset)
1916 file_offset = track_id3->first_frame_offset;
1917 else
1918 file_offset = 0;
1920 tracks[track_widx].audio_hid = bufopen(track_id3->path, file_offset, type);
1922 /* No space left, not an error */
1923 if (tracks[track_widx].audio_hid == ERR_BUFFER_FULL)
1925 filling = STATE_FULL;
1926 logf("buffer is full for now");
1927 return;
1929 else if (tracks[track_widx].audio_hid < 0)
1931 /* another error, do not continue either */
1932 logf("Could not add audio data handle");
1933 return;
1936 /* All required data is now available for the codec. */
1937 tracks[track_widx].taginfo_ready = true;
1939 if (start_play)
1941 ci.curpos=file_offset;
1942 buf_request_buffer_handle(tracks[track_widx].audio_hid);
1945 track_widx = (track_widx + 1) & MAX_TRACK_MASK;
1947 send_event(PLAYBACK_EVENT_TRACK_BUFFER, track_id3);
1949 /* load next track */
1950 LOGFQUEUE("audio > audio Q_AUDIO_FILL_BUFFER");
1951 queue_post(&audio_queue, Q_AUDIO_FILL_BUFFER, 0);
1953 return;
1956 static void audio_fill_file_buffer(bool start_play, size_t offset)
1958 filling = STATE_FILLING;
1959 trigger_cpu_boost();
1961 /* No need to rebuffer if there are track skips pending. */
1962 if (ci.new_track != 0)
1963 return;
1965 /* Must reset the buffer before use if trashed or voice only - voice
1966 file size shouldn't have changed so we can go straight from
1967 AUDIOBUF_STATE_VOICED_ONLY to AUDIOBUF_STATE_INITIALIZED */
1968 if (buffer_state != AUDIOBUF_STATE_INITIALIZED)
1969 audio_reset_buffer();
1971 logf("Starting buffer fill");
1973 if (!start_play)
1974 audio_clear_track_entries();
1976 /* Save the current resume position once. */
1977 playlist_update_resume_info(audio_current_track());
1979 audio_load_track(offset, start_play);
1982 static void audio_rebuffer(void)
1984 logf("Forcing rebuffer");
1986 clear_track_info(CUR_TI);
1988 /* Reset track pointers */
1989 track_widx = track_ridx;
1990 audio_clear_track_entries();
1992 /* Reset a possibly interrupted track load */
1993 track_load_started = false;
1995 /* Fill the buffer */
1996 last_peek_offset = -1;
1997 ci.curpos = 0;
1999 if (!CUR_TI->taginfo_ready)
2000 memset(thistrack_id3, 0, sizeof(struct mp3entry));
2002 audio_fill_file_buffer(false, 0);
2005 /* Called on request from the codec to get a new track. This is the codec part
2006 of the track transition. */
2007 static int audio_check_new_track(void)
2009 int track_count = audio_track_count();
2010 int old_track_ridx = track_ridx;
2011 int i, idx;
2012 bool forward;
2013 struct mp3entry *temp = thistrack_id3;
2015 /* Now it's good time to send track finish events. */
2016 send_event(PLAYBACK_EVENT_TRACK_FINISH, thistrack_id3);
2017 /* swap the mp3entry pointers */
2018 thistrack_id3 = othertrack_id3;
2019 othertrack_id3 = temp;
2020 ci.id3 = thistrack_id3;
2021 memset(thistrack_id3, 0, sizeof(struct mp3entry));
2023 if (dir_skip)
2025 dir_skip = false;
2026 /* regardless of the return value we need to rebuffer.
2027 if it fails the old playlist will resume, else the
2028 next dir will start playing */
2029 playlist_next_dir(ci.new_track);
2030 ci.new_track = 0;
2031 audio_rebuffer();
2032 goto skip_done;
2035 if (new_playlist)
2036 ci.new_track = 0;
2038 /* If the playlist isn't that big */
2039 if (automatic_skip)
2041 while (!playlist_check(ci.new_track))
2043 if (ci.new_track >= 0)
2045 LOGFQUEUE("audio >|= codec Q_CODEC_REQUEST_FAILED");
2046 return Q_CODEC_REQUEST_FAILED;
2048 ci.new_track++;
2052 /* Update the playlist */
2053 last_peek_offset -= ci.new_track;
2055 if (playlist_next(ci.new_track) < 0)
2057 LOGFQUEUE("audio >|= codec Q_CODEC_REQUEST_FAILED");
2058 return Q_CODEC_REQUEST_FAILED;
2061 if (new_playlist)
2063 ci.new_track = 1;
2064 new_playlist = false;
2067 /* Save a pointer to the old track to allow later clearing */
2068 prev_ti = CUR_TI;
2070 for (i = 0; i < ci.new_track; i++)
2072 idx = (track_ridx + i) & MAX_TRACK_MASK;
2073 struct mp3entry *id3 = bufgetid3(tracks[idx].id3_hid);
2074 ssize_t offset = buf_handle_offset(tracks[idx].audio_hid);
2075 if (!id3 || offset < 0 || (unsigned)offset > id3->first_frame_offset)
2077 /* We don't have all the audio data for that track, so clear it,
2078 but keep the metadata. */
2079 if (tracks[idx].audio_hid >= 0 && bufclose(tracks[idx].audio_hid))
2081 tracks[idx].audio_hid = -1;
2082 tracks[idx].filesize = 0;
2087 /* Move to the new track */
2088 track_ridx = (track_ridx + ci.new_track) & MAX_TRACK_MASK;
2090 buf_set_base_handle(CUR_TI->audio_hid);
2092 if (automatic_skip)
2094 wps_offset = -ci.new_track;
2097 /* If it is not safe to even skip this many track entries */
2098 if (ci.new_track >= track_count || ci.new_track <= track_count - MAX_TRACK)
2100 ci.new_track = 0;
2101 audio_rebuffer();
2102 goto skip_done;
2105 forward = ci.new_track > 0;
2106 ci.new_track = 0;
2108 /* If the target track is clearly not in memory */
2109 if (CUR_TI->filesize == 0 || !CUR_TI->taginfo_ready)
2111 audio_rebuffer();
2112 goto skip_done;
2115 /* When skipping backwards, it is possible that we've found a track that's
2116 * buffered, but which is around the track-wrap and therefore not the track
2117 * we are looking for */
2118 if (!forward)
2120 int cur_idx = track_ridx;
2121 bool taginfo_ready = true;
2122 /* We've wrapped the buffer backwards if new > old */
2123 bool wrap = track_ridx > old_track_ridx;
2125 while (1)
2127 cur_idx = (cur_idx + 1) & MAX_TRACK_MASK;
2129 /* if we've advanced past the wrap when cur_idx is zeroed */
2130 if (!cur_idx)
2131 wrap = false;
2133 /* if we aren't still on the wrap and we've caught the old track */
2134 if (!(wrap || cur_idx < old_track_ridx))
2135 break;
2137 /* If we hit a track in between without valid tag info, bail */
2138 if (!tracks[cur_idx].taginfo_ready)
2140 taginfo_ready = false;
2141 break;
2144 if (!taginfo_ready)
2146 audio_rebuffer();
2150 skip_done:
2151 audio_update_trackinfo();
2152 LOGFQUEUE("audio >|= codec Q_CODEC_REQUEST_COMPLETE");
2153 return Q_CODEC_REQUEST_COMPLETE;
2156 unsigned long audio_prev_elapsed(void)
2158 return prev_track_elapsed;
2161 static void audio_stop_codec_flush(void)
2163 ci.stop_codec = true;
2164 pcmbuf_pause(true);
2166 while (audio_codec_loaded)
2167 yield();
2169 /* If the audio codec is not loaded any more, and the audio is still
2170 * playing, it is now and _only_ now safe to call this function from the
2171 * audio thread */
2172 if (pcm_is_playing())
2174 pcmbuf_play_stop();
2175 pcmbuf_queue_clear();
2177 pcmbuf_pause(paused);
2180 static void audio_stop_playback(void)
2182 /* If we were playing, save resume information */
2183 if (playing)
2185 struct mp3entry *id3 = NULL;
2187 if (!ci.stop_codec)
2189 /* Set this early, the outside code yields and may allow the codec
2190 to try to wait for a reply on a buffer wait */
2191 ci.stop_codec = true;
2192 id3 = audio_current_track();
2195 /* Save the current playing spot, or NULL if the playlist has ended */
2196 playlist_update_resume_info(id3);
2198 /* TODO: Create auto bookmark too? */
2200 prev_track_elapsed = othertrack_id3->elapsed;
2202 remove_event(BUFFER_EVENT_BUFFER_LOW, buffering_low_buffer_callback);
2205 audio_stop_codec_flush();
2206 paused = false;
2207 playing = false;
2208 track_load_started = false;
2210 filling = STATE_IDLE;
2212 /* Mark all entries null. */
2213 audio_clear_track_entries();
2215 /* Close all tracks */
2216 audio_release_tracks();
2219 static void audio_play_start(size_t offset)
2221 int i;
2223 #if INPUT_SRC_CAPS != 0
2224 audio_set_input_source(AUDIO_SRC_PLAYBACK, SRCF_PLAYBACK);
2225 audio_set_output_source(AUDIO_SRC_PLAYBACK);
2226 #endif
2228 /* Wait for any previously playing audio to flush - TODO: Not necessary? */
2229 paused = false;
2230 audio_stop_codec_flush();
2232 playing = true;
2233 track_load_started = false;
2235 ci.new_track = 0;
2236 ci.seek_time = 0;
2237 wps_offset = 0;
2239 sound_set_volume(global_settings.volume);
2240 track_widx = track_ridx = 0;
2242 /* Clear all track entries. */
2243 for (i = 0; i < MAX_TRACK; i++) {
2244 clear_track_info(&tracks[i]);
2247 last_peek_offset = -1;
2249 /* Officially playing */
2250 queue_reply(&audio_queue, 1);
2252 audio_fill_file_buffer(true, offset);
2254 add_event(BUFFER_EVENT_BUFFER_LOW, false, buffering_low_buffer_callback);
2256 LOGFQUEUE("audio > audio Q_AUDIO_TRACK_CHANGED");
2257 queue_post(&audio_queue, Q_AUDIO_TRACK_CHANGED, 0);
2261 /* Invalidates all but currently playing track. */
2262 static void audio_invalidate_tracks(void)
2264 if (audio_have_tracks())
2266 last_peek_offset = 0;
2267 track_widx = track_ridx;
2269 /* Mark all other entries null (also buffered wrong metadata). */
2270 audio_clear_track_entries();
2272 track_widx = (track_widx + 1) & MAX_TRACK_MASK;
2274 audio_fill_file_buffer(false, 0);
2278 static void audio_new_playlist(void)
2280 /* Prepare to start a new fill from the beginning of the playlist */
2281 last_peek_offset = -1;
2282 if (audio_have_tracks())
2284 if (paused)
2285 skipped_during_pause = true;
2286 track_widx = track_ridx;
2287 audio_clear_track_entries();
2289 track_widx = (track_widx + 1) & MAX_TRACK_MASK;
2291 /* Mark the current track as invalid to prevent skipping back to it */
2292 CUR_TI->taginfo_ready = false;
2295 /* Signal the codec to initiate a track change forward */
2296 new_playlist = true;
2297 ci.new_track = 1;
2299 /* Officially playing */
2300 queue_reply(&audio_queue, 1);
2302 audio_fill_file_buffer(false, 0);
2305 /* Called on manual track skip */
2306 static void audio_initiate_track_change(long direction)
2308 logf("audio_initiate_track_change(%ld)", direction);
2310 ci.new_track += direction;
2311 wps_offset -= direction;
2312 if (paused)
2313 skipped_during_pause = true;
2316 /* Called on manual dir skip */
2317 static void audio_initiate_dir_change(long direction)
2319 dir_skip = true;
2320 ci.new_track = direction;
2321 if (paused)
2322 skipped_during_pause = true;
2325 /* Called when PCM track change is complete */
2326 static void audio_finalise_track_change(void)
2328 logf("audio_finalise_track_change");
2330 if (automatic_skip)
2332 wps_offset = 0;
2333 automatic_skip = false;
2335 /* Invalidate prevtrack_id3 */
2336 memset(othertrack_id3, 0, sizeof(struct mp3entry));
2338 if (prev_ti && prev_ti->audio_hid < 0)
2340 /* No audio left so we clear all the track info. */
2341 clear_track_info(prev_ti);
2344 send_event(PLAYBACK_EVENT_TRACK_CHANGE, thistrack_id3);
2345 playlist_update_resume_info(audio_current_track());
2349 * Layout audio buffer as follows - iram buffer depends on target:
2350 * [|SWAP:iram][|TALK]|FILE|GUARD|PCM|[SWAP:dram[|iram]|]
2352 static void audio_reset_buffer(void)
2354 /* see audio_get_recording_buffer if this is modified */
2355 logf("audio_reset_buffer");
2357 /* If the setup of anything allocated before the file buffer is
2358 changed, do check the adjustments after the buffer_alloc call
2359 as it will likely be affected and need sliding over */
2361 /* Initially set up file buffer as all space available */
2362 malloc_buf = audiobuf + talk_get_bufsize();
2363 /* Align the malloc buf to line size. Especially important to cf
2364 targets that do line reads/writes. */
2365 malloc_buf = (unsigned char *)(((uintptr_t)malloc_buf + 15) & ~15);
2366 filebuf = malloc_buf; /* filebuf line align implied */
2367 filebuflen = audiobufend - filebuf;
2369 filebuflen &= ~15;
2371 /* Subtract whatever the pcm buffer says it used plus the guard buffer */
2372 const size_t pcmbuf_size = pcmbuf_init(filebuf + filebuflen) +GUARD_BUFSIZE;
2374 #ifdef DEBUG
2375 if(pcmbuf_size > filebuflen)
2376 panicf("Not enough memory for pcmbuf_init() : %d > %d",
2377 (int)pcmbuf_size, (int)filebuflen);
2378 #endif
2380 filebuflen -= pcmbuf_size;
2382 /* Make sure filebuflen is a longword multiple after adjustment - filebuf
2383 will already be line aligned */
2384 filebuflen &= ~3;
2386 buffering_reset(filebuf, filebuflen);
2388 /* Clear any references to the file buffer */
2389 buffer_state = AUDIOBUF_STATE_INITIALIZED;
2391 #if defined(ROCKBOX_HAS_LOGF) && defined(LOGF_ENABLE)
2392 /* Make sure everything adds up - yes, some info is a bit redundant but
2393 aids viewing and the sumation of certain variables should add up to
2394 the location of others. */
2396 size_t pcmbufsize;
2397 const unsigned char *pcmbuf = pcmbuf_get_meminfo(&pcmbufsize);
2398 logf("mabuf: %08X", (unsigned)malloc_buf);
2399 logf("fbuf: %08X", (unsigned)filebuf);
2400 logf("fbufe: %08X", (unsigned)(filebuf + filebuflen));
2401 logf("gbuf: %08X", (unsigned)(filebuf + filebuflen));
2402 logf("gbufe: %08X", (unsigned)(filebuf + filebuflen + GUARD_BUFSIZE));
2403 logf("pcmb: %08X", (unsigned)pcmbuf);
2404 logf("pcmbe: %08X", (unsigned)(pcmbuf + pcmbufsize));
2406 #endif
2409 static void audio_thread(void)
2411 struct queue_event ev;
2413 pcm_postinit();
2415 audio_thread_ready = true;
2417 while (1)
2419 if (filling != STATE_FILLING) {
2420 /* End of buffering, let's calculate the watermark and unboost */
2421 set_filebuf_watermark();
2422 cancel_cpu_boost();
2425 if (!pcmbuf_queue_scan(&ev))
2426 queue_wait_w_tmo(&audio_queue, &ev, HZ/2);
2428 switch (ev.id) {
2430 case Q_AUDIO_FILL_BUFFER:
2431 LOGFQUEUE("audio < Q_AUDIO_FILL_BUFFER %d", (int)ev.data);
2432 audio_fill_file_buffer((bool)ev.data, 0);
2433 break;
2435 case Q_AUDIO_FINISH_LOAD:
2436 LOGFQUEUE("audio < Q_AUDIO_FINISH_LOAD");
2437 audio_finish_load_track();
2438 break;
2440 case Q_AUDIO_PLAY:
2441 LOGFQUEUE("audio < Q_AUDIO_PLAY");
2442 if (playing && ev.data <= 0)
2443 audio_new_playlist();
2444 else
2446 audio_stop_playback();
2447 audio_play_start((size_t)ev.data);
2449 break;
2451 case Q_AUDIO_STOP:
2452 LOGFQUEUE("audio < Q_AUDIO_STOP");
2453 if (playing)
2454 audio_stop_playback();
2455 if (ev.data != 0)
2456 queue_clear(&audio_queue);
2457 break;
2459 case Q_AUDIO_PAUSE:
2460 LOGFQUEUE("audio < Q_AUDIO_PAUSE");
2461 if (!(bool) ev.data && skipped_during_pause && !pcmbuf_is_crossfade_active())
2462 pcmbuf_play_stop(); /* Flush old track on resume after skip */
2463 skipped_during_pause = false;
2464 if (!playing)
2465 break;
2466 pcmbuf_pause((bool)ev.data);
2467 paused = (bool)ev.data;
2468 break;
2470 case Q_AUDIO_SKIP:
2471 LOGFQUEUE("audio < Q_AUDIO_SKIP");
2472 audio_initiate_track_change((long)ev.data);
2473 break;
2475 case Q_AUDIO_PRE_FF_REWIND:
2476 LOGFQUEUE("audio < Q_AUDIO_PRE_FF_REWIND");
2477 if (!playing)
2478 break;
2479 pcmbuf_pause(true);
2480 break;
2482 case Q_AUDIO_FF_REWIND:
2483 LOGFQUEUE("audio < Q_AUDIO_FF_REWIND");
2484 if (!playing)
2485 break;
2486 if (automatic_skip)
2488 /* An automatic track skip is in progress. Finalize it,
2489 then go back to the previous track */
2490 audio_finalise_track_change();
2491 ci.new_track = -1;
2493 ci.seek_time = (long)ev.data+1;
2494 break;
2496 case Q_AUDIO_CHECK_NEW_TRACK:
2497 LOGFQUEUE("audio < Q_AUDIO_CHECK_NEW_TRACK");
2498 queue_reply(&audio_queue, audio_check_new_track());
2499 break;
2501 case Q_AUDIO_DIR_SKIP:
2502 LOGFQUEUE("audio < Q_AUDIO_DIR_SKIP");
2503 audio_initiate_dir_change(ev.data);
2504 break;
2506 case Q_AUDIO_FLUSH:
2507 LOGFQUEUE("audio < Q_AUDIO_FLUSH");
2508 audio_invalidate_tracks();
2509 break;
2511 case Q_AUDIO_TRACK_CHANGED:
2512 /* PCM track change done */
2513 LOGFQUEUE("audio < Q_AUDIO_TRACK_CHANGED");
2514 audio_finalise_track_change();
2515 break;
2517 #ifndef SIMULATOR
2518 case SYS_USB_CONNECTED:
2519 LOGFQUEUE("audio < SYS_USB_CONNECTED");
2520 if (playing)
2521 audio_stop_playback();
2522 #ifdef PLAYBACK_VOICE
2523 voice_stop();
2524 #endif
2525 usb_acknowledge(SYS_USB_CONNECTED_ACK);
2526 usb_wait_for_disconnect(&audio_queue);
2528 /* Mark all entries null. */
2529 audio_clear_track_entries();
2531 /* release tracks to make sure all handles are closed */
2532 audio_release_tracks();
2533 break;
2534 #endif
2536 case SYS_TIMEOUT:
2537 LOGFQUEUE_SYS_TIMEOUT("audio < SYS_TIMEOUT");
2538 break;
2540 default:
2541 LOGFQUEUE("audio < default");
2542 break;
2543 } /* end switch */
2544 } /* end while */
2547 /* Initialize the audio system - called from init() in main.c.
2548 * Last function because of all the references to internal symbols
2550 void audio_init(void)
2552 unsigned int audio_thread_id;
2554 /* Can never do this twice */
2555 if (audio_is_initialized)
2557 logf("audio: already initialized");
2558 return;
2561 logf("audio: initializing");
2563 /* Initialize queues before giving control elsewhere in case it likes
2564 to send messages. Thread creation will be delayed however so nothing
2565 starts running until ready if something yields such as talk_init. */
2566 queue_init(&audio_queue, true);
2567 queue_init(&codec_queue, false);
2568 queue_init(&pcmbuf_queue, false);
2570 pcm_init();
2572 /* Initialize codec api. */
2573 ci.read_filebuf = codec_filebuf_callback;
2574 ci.pcmbuf_insert = codec_pcmbuf_insert_callback;
2575 ci.codec_get_buffer = codec_get_buffer;
2576 ci.request_buffer = codec_request_buffer_callback;
2577 ci.advance_buffer = codec_advance_buffer_callback;
2578 ci.advance_buffer_loc = codec_advance_buffer_loc_callback;
2579 ci.request_next_track = codec_request_next_track_callback;
2580 ci.seek_buffer = codec_seek_buffer_callback;
2581 ci.seek_complete = codec_seek_complete_callback;
2582 ci.set_elapsed = codec_set_elapsed_callback;
2583 ci.set_offset = codec_set_offset_callback;
2584 ci.configure = codec_configure_callback;
2585 ci.discard_codec = codec_discard_codec_callback;
2586 ci.dsp = (struct dsp_config *)dsp_configure(NULL, DSP_MYDSP,
2587 CODEC_IDX_AUDIO);
2589 thistrack_id3 = &mp3entry_buf[0];
2590 othertrack_id3 = &mp3entry_buf[1];
2592 /* initialize the buffer */
2593 filebuf = audiobuf;
2595 /* audio_reset_buffer must to know the size of voice buffer so init
2596 talk first */
2597 talk_init();
2599 codec_thread_id = create_thread(
2600 codec_thread, codec_stack, sizeof(codec_stack),
2601 CREATE_THREAD_FROZEN,
2602 codec_thread_name IF_PRIO(, PRIORITY_PLAYBACK)
2603 IF_COP(, CPU));
2605 queue_enable_queue_send(&codec_queue, &codec_queue_sender_list,
2606 codec_thread_id);
2608 audio_thread_id = create_thread(audio_thread, audio_stack,
2609 sizeof(audio_stack), CREATE_THREAD_FROZEN,
2610 audio_thread_name IF_PRIO(, PRIORITY_USER_INTERFACE)
2611 IF_COP(, CPU));
2613 queue_enable_queue_send(&audio_queue, &audio_queue_sender_list,
2614 audio_thread_id);
2616 #ifdef PLAYBACK_VOICE
2617 voice_thread_init();
2618 #endif
2620 /* Set crossfade setting for next buffer init which should be about... */
2621 pcmbuf_crossfade_enable(global_settings.crossfade);
2623 /* initialize the buffering system */
2625 buffering_init();
2626 /* ...now! Set up the buffers */
2627 audio_reset_buffer();
2629 int i;
2630 for(i = 0; i < MAX_TRACK; i++)
2632 tracks[i].audio_hid = -1;
2633 tracks[i].id3_hid = -1;
2634 tracks[i].codec_hid = -1;
2635 #ifdef HAVE_ALBUMART
2636 tracks[i].aa_hid = -1;
2637 #endif
2640 add_event(BUFFER_EVENT_REBUFFER, false, buffering_handle_rebuffer_callback);
2641 add_event(BUFFER_EVENT_FINISHED, false, buffering_handle_finished_callback);
2643 /* Probably safe to say */
2644 audio_is_initialized = true;
2646 sound_settings_apply();
2647 #ifdef HAVE_DISK_STORAGE
2648 audio_set_buffer_margin(global_settings.buffer_margin);
2649 #endif
2651 /* it's safe to let the threads run now */
2652 #ifdef PLAYBACK_VOICE
2653 voice_thread_resume();
2654 #endif
2655 thread_thaw(codec_thread_id);
2656 thread_thaw(audio_thread_id);
2658 } /* audio_init */
2660 bool audio_is_thread_ready(void)
2662 return audio_thread_ready;