si4700/rda5802 tuners: prevent hang when changing radio region. Probably fixes bug...
[kugel-rb.git] / apps / playback.c
blobf3c5db309ec0316b3118a74741899e284da97ae6
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 <string.h>
27 #include "playback.h"
28 #include "codec_thread.h"
29 #include "kernel.h"
30 #include "codecs.h"
31 #include "buffering.h"
32 #include "voice_thread.h"
33 #include "usb.h"
34 #include "ata.h"
35 #include "playlist.h"
36 #include "pcmbuf.h"
37 #include "buffer.h"
38 #include "cuesheet.h"
39 #ifdef HAVE_TAGCACHE
40 #include "tagcache.h"
41 #endif
42 #ifdef HAVE_LCD_BITMAP
43 #ifdef HAVE_ALBUMART
44 #include "albumart.h"
45 #endif
46 #endif
47 #include "sound.h"
48 #include "metadata.h"
49 #include "splash.h"
50 #include "talk.h"
51 #include "panic.h"
53 #ifdef HAVE_RECORDING
54 #include "pcm_record.h"
55 #endif
57 #define PLAYBACK_VOICE
59 /* amount of guess-space to allow for codecs that must hunt and peck
60 * for their correct seeek target, 32k seems a good size */
61 #define AUDIO_REBUFFER_GUESS_SIZE (1024*32)
63 /* Define LOGF_ENABLE to enable logf output in this file */
64 /*#define LOGF_ENABLE*/
65 #include "logf.h"
67 /* macros to enable logf for queues
68 logging on SYS_TIMEOUT can be disabled */
69 #ifdef SIMULATOR
70 /* Define this for logf output of all queuing except SYS_TIMEOUT */
71 #define PLAYBACK_LOGQUEUES
72 /* Define this to logf SYS_TIMEOUT messages */
73 /*#define PLAYBACK_LOGQUEUES_SYS_TIMEOUT*/
74 #endif
76 #ifdef PLAYBACK_LOGQUEUES
77 #define LOGFQUEUE logf
78 #else
79 #define LOGFQUEUE(...)
80 #endif
82 #ifdef PLAYBACK_LOGQUEUES_SYS_TIMEOUT
83 #define LOGFQUEUE_SYS_TIMEOUT logf
84 #else
85 #define LOGFQUEUE_SYS_TIMEOUT(...)
86 #endif
89 static enum filling_state {
90 STATE_IDLE, /* audio is stopped: nothing to do */
91 STATE_FILLING, /* adding tracks to the buffer */
92 STATE_FULL, /* can't add any more tracks */
93 STATE_END_OF_PLAYLIST, /* all remaining tracks have been added */
94 STATE_FINISHED, /* all remaining tracks are fully buffered */
95 } filling;
97 /* As defined in plugins/lib/xxx2wav.h */
98 #define GUARD_BUFSIZE (32*1024)
100 bool audio_is_initialized = false;
101 static bool audio_thread_ready SHAREDBSS_ATTR = false;
103 /* Variables are commented with the threads that use them: *
104 * A=audio, C=codec, V=voice. A suffix of - indicates that *
105 * the variable is read but not updated on that thread. */
106 /* TBD: Split out "audio" and "playback" (ie. calling) threads */
108 /* Main state control */
109 static volatile bool playing SHAREDBSS_ATTR = false;/* Is audio playing? (A) */
110 static volatile bool paused SHAREDBSS_ATTR = false; /* Is audio paused? (A/C-) */
111 extern volatile bool audio_codec_loaded; /* Codec loaded? (C/A-) */
113 /* Ring buffer where compressed audio and codecs are loaded */
114 static unsigned char *filebuf = NULL; /* Start of buffer (A/C-) */
115 static unsigned char *malloc_buf = NULL; /* Start of malloc buffer (A/C-) */
116 static size_t filebuflen = 0; /* Size of buffer (A/C-) */
117 /* FIXME: make buf_ridx (C/A-) */
119 /* Possible arrangements of the buffer */
120 enum audio_buffer_state
122 AUDIOBUF_STATE_TRASHED = -1, /* trashed; must be reset */
123 AUDIOBUF_STATE_INITIALIZED = 0, /* voice+audio OR audio-only */
124 AUDIOBUF_STATE_VOICED_ONLY = 1, /* voice-only */
126 static int buffer_state = AUDIOBUF_STATE_TRASHED; /* Buffer state */
128 /* These are used to store the current and next (or prev if the current is the last)
129 * mp3entry's in a round-robin system. This guarentees that the pointer returned
130 * by audio_current/next_track will be valid for the full duration of the
131 * currently playing track */
132 static struct mp3entry mp3entry_buf[2];
133 struct mp3entry *thistrack_id3, /* the currently playing track */
134 *othertrack_id3; /* prev track during track-change-transition, or end of playlist,
135 * next track otherwise */
136 static struct mp3entry unbuffered_id3; /* the id3 for the first unbuffered track */
138 /* for cuesheet support */
139 static struct cuesheet *curr_cue = NULL;
142 #define MAX_MULTIPLE_AA SKINNABLE_SCREENS_COUNT
144 #ifdef HAVE_ALBUMART
145 static struct albumart_slot {
146 struct dim dim; /* holds width, height of the albumart */
147 int used; /* counter, increments if something uses it */
148 } albumart_slots[MAX_MULTIPLE_AA];
150 #define FOREACH_ALBUMART(i) for(i = 0;i < MAX_MULTIPLE_AA; i++)
151 #endif
154 #define MAX_TRACK 128
155 #define MAX_TRACK_MASK (MAX_TRACK-1)
157 /* Track info structure about songs in the file buffer (A/C-) */
158 static struct track_info {
159 int audio_hid; /* The ID for the track's buffer handle */
160 int id3_hid; /* The ID for the track's metadata handle */
161 int codec_hid; /* The ID for the track's codec handle */
162 #ifdef HAVE_ALBUMART
163 int aa_hid[MAX_MULTIPLE_AA];/* The ID for the track's album art handle */
164 #endif
165 int cuesheet_hid; /* The ID for the track's parsed cueesheet handle */
167 size_t filesize; /* File total length */
169 bool taginfo_ready; /* Is metadata read */
171 } tracks[MAX_TRACK];
173 static volatile int track_ridx = 0; /* Track being decoded (A/C-) */
174 static int track_widx = 0; /* Track being buffered (A) */
175 #define CUR_TI (&tracks[track_ridx]) /* Playing track info pointer (A/C-) */
177 static struct track_info *prev_ti = NULL; /* Pointer to the previously played
178 track */
180 /* Information used only for filling the buffer */
181 /* Playlist steps from playing track to next track to be buffered (A) */
182 static int last_peek_offset = 0;
184 /* Scrobbler support */
185 static unsigned long prev_track_elapsed = 0; /* Previous track elapsed time (C/A-)*/
187 /* Track change controls */
188 bool automatic_skip = false; /* Who initiated in-progress skip? (C/A-) */
189 extern bool track_transition; /* Are we in a track transition? */
190 static bool dir_skip = false; /* Is a directory skip pending? (A) */
191 static bool new_playlist = false; /* Are we starting a new playlist? (A) */
192 static int wps_offset = 0; /* Pending track change offset, to keep WPS responsive (A) */
193 static bool skipped_during_pause = false; /* Do we need to clear the PCM buffer when playback resumes (A) */
195 static bool start_play_g = false; /* Used by audio_load_track to notify
196 audio_finish_load_track about start_play */
198 /* True when a track load is in progress, i.e. audio_load_track() has returned
199 * but audio_finish_load_track() hasn't been called yet. Used to avoid allowing
200 * audio_load_track() to get called twice in a row, which would cause problems.
202 static bool track_load_started = false;
204 #ifdef HAVE_DISK_STORAGE
205 static size_t buffer_margin = 5; /* Buffer margin aka anti-skip buffer (A/C-) */
206 #endif
208 /* Event queues */
209 struct event_queue audio_queue SHAREDBSS_ATTR;
210 struct event_queue codec_queue SHAREDBSS_ATTR;
211 static struct event_queue pcmbuf_queue SHAREDBSS_ATTR;
213 extern struct codec_api ci;
214 extern unsigned int codec_thread_id;
216 /* Multiple threads */
217 /* Set the watermark to trigger buffer fill (A/C) */
218 static void set_filebuf_watermark(void);
220 /* Audio thread */
221 static struct queue_sender_list audio_queue_sender_list SHAREDBSS_ATTR;
222 static long audio_stack[(DEFAULT_STACK_SIZE + 0x1000)/sizeof(long)];
223 static const char audio_thread_name[] = "audio";
225 static void audio_thread(void);
226 static void audio_initiate_track_change(long direction);
227 static bool audio_have_tracks(void);
228 static void audio_reset_buffer(void);
229 static void audio_stop_playback(void);
232 /**************************************/
235 /** Pcmbuf callbacks */
237 /* Between the codec and PCM track change, we need to keep updating the
238 * "elapsed" value of the previous (to the codec, but current to the
239 * user/PCM/WPS) track, so that the progressbar reaches the end.
240 * During that transition, the WPS will display othertrack_id3. */
241 void audio_pcmbuf_position_callback(unsigned int time)
243 time += othertrack_id3->elapsed;
245 if (time >= othertrack_id3->length)
247 /* we just played the end of the track, so stop this callback */
248 track_transition = false;
249 othertrack_id3->elapsed = othertrack_id3->length;
251 else
252 othertrack_id3->elapsed = time;
255 /* Post message from pcmbuf that the end of the previous track
256 * has just been played. */
257 void audio_post_track_change(bool pcmbuf)
259 if (pcmbuf)
261 LOGFQUEUE("pcmbuf > pcmbuf Q_AUDIO_TRACK_CHANGED");
262 queue_post(&pcmbuf_queue, Q_AUDIO_TRACK_CHANGED, 0);
264 else
266 LOGFQUEUE("pcmbuf > audio Q_AUDIO_TRACK_CHANGED");
267 queue_post(&audio_queue, Q_AUDIO_TRACK_CHANGED, 0);
271 /* Scan the pcmbuf queue and return true if a message pulled */
272 static bool pcmbuf_queue_scan(struct queue_event *ev)
274 if (!queue_empty(&pcmbuf_queue))
276 /* Transfer message to audio queue */
277 pcm_play_lock();
278 /* Pull message - never, ever any blocking call! */
279 queue_wait_w_tmo(&pcmbuf_queue, ev, 0);
280 pcm_play_unlock();
281 return true;
284 return false;
288 /** Helper functions */
290 static struct mp3entry *bufgetid3(int handle_id)
292 if (handle_id < 0)
293 return NULL;
295 struct mp3entry *id3;
296 ssize_t ret = bufgetdata(handle_id, 0, (void *)&id3);
298 if (ret < 0 || ret != sizeof(struct mp3entry))
299 return NULL;
301 return id3;
304 static bool clear_track_info(struct track_info *track)
306 /* bufclose returns true if the handle is not found, or if it is closed
307 * successfully, so these checks are safe on non-existant handles */
308 if (!track)
309 return false;
311 if (track->codec_hid >= 0) {
312 if (bufclose(track->codec_hid))
313 track->codec_hid = -1;
314 else
315 return false;
318 if (track->id3_hid >= 0) {
319 if (bufclose(track->id3_hid))
320 track->id3_hid = -1;
321 else
322 return false;
325 if (track->audio_hid >= 0) {
326 if (bufclose(track->audio_hid))
327 track->audio_hid = -1;
328 else
329 return false;
332 #ifdef HAVE_ALBUMART
334 int i;
335 FOREACH_ALBUMART(i)
337 if (track->aa_hid[i] >= 0) {
338 if (bufclose(track->aa_hid[i]))
339 track->aa_hid[i] = -1;
340 else
341 return false;
345 #endif
347 if (track->cuesheet_hid >= 0) {
348 if (bufclose(track->cuesheet_hid))
349 track->cuesheet_hid = -1;
350 else
351 return false;
354 track->filesize = 0;
355 track->taginfo_ready = false;
357 return true;
360 /* --- External interfaces --- */
362 /* This sends a stop message and the audio thread will dump all it's
363 subsequenct messages */
364 void audio_hard_stop(void)
366 /* Stop playback */
367 LOGFQUEUE("audio >| audio Q_AUDIO_STOP: 1");
368 queue_send(&audio_queue, Q_AUDIO_STOP, 1);
369 #ifdef PLAYBACK_VOICE
370 voice_stop();
371 #endif
374 bool audio_restore_playback(int type)
376 switch (type)
378 case AUDIO_WANT_PLAYBACK:
379 if (buffer_state != AUDIOBUF_STATE_INITIALIZED)
380 audio_reset_buffer();
381 return true;
382 case AUDIO_WANT_VOICE:
383 if (buffer_state == AUDIOBUF_STATE_TRASHED)
384 audio_reset_buffer();
385 return true;
386 default:
387 return false;
391 unsigned char *audio_get_buffer(bool talk_buf, size_t *buffer_size)
393 unsigned char *buf, *end;
395 if (audio_is_initialized)
397 audio_hard_stop();
399 /* else buffer_state will be AUDIOBUF_STATE_TRASHED at this point */
401 /* Reset the buffering thread so that it doesn't try to use the data */
402 buffering_reset(filebuf, filebuflen);
404 if (buffer_size == NULL)
406 /* Special case for talk_init to use since it already knows it's
407 trashed */
408 buffer_state = AUDIOBUF_STATE_TRASHED;
409 return NULL;
412 if (talk_buf || buffer_state == AUDIOBUF_STATE_TRASHED
413 || !talk_voice_required())
415 logf("get buffer: talk, audio");
416 /* Ok to use everything from audiobuf to audiobufend - voice is loaded,
417 the talk buffer is not needed because voice isn't being used, or
418 could be AUDIOBUF_STATE_TRASHED already. If state is
419 AUDIOBUF_STATE_VOICED_ONLY, no problem as long as memory isn't written
420 without the caller knowing what's going on. Changing certain settings
421 may move it to a worse condition but the memory in use by something
422 else will remain undisturbed.
424 if (buffer_state != AUDIOBUF_STATE_TRASHED)
426 talk_buffer_steal();
427 buffer_state = AUDIOBUF_STATE_TRASHED;
430 buf = audiobuf;
431 end = audiobufend;
433 else
435 /* Safe to just return this if already AUDIOBUF_STATE_VOICED_ONLY or
436 still AUDIOBUF_STATE_INITIALIZED */
437 /* Skip talk buffer and move pcm buffer to end to maximize available
438 contiguous memory - no audio running means voice will not need the
439 swap space */
440 logf("get buffer: audio");
441 buf = audiobuf + talk_get_bufsize();
442 end = audiobufend - pcmbuf_init(audiobufend);
443 buffer_state = AUDIOBUF_STATE_VOICED_ONLY;
446 *buffer_size = end - buf;
448 return buf;
451 bool audio_buffer_state_trashed(void)
453 return buffer_state == AUDIOBUF_STATE_TRASHED;
456 #ifdef HAVE_RECORDING
457 unsigned char *audio_get_recording_buffer(size_t *buffer_size)
459 /* Stop audio, voice and obtain all available buffer space */
460 audio_hard_stop();
461 talk_buffer_steal();
463 unsigned char *end = audiobufend;
464 buffer_state = AUDIOBUF_STATE_TRASHED;
465 *buffer_size = end - audiobuf;
467 return (unsigned char *)audiobuf;
470 bool audio_load_encoder(int afmt)
472 #if (CONFIG_PLATFORM & PLATFORM_NATIVE)
473 const char *enc_fn = get_codec_filename(afmt | CODEC_TYPE_ENCODER);
474 if (!enc_fn)
475 return false;
477 audio_remove_encoder();
478 ci.enc_codec_loaded = 0; /* clear any previous error condition */
480 LOGFQUEUE("codec > Q_ENCODER_LOAD_DISK");
481 queue_post(&codec_queue, Q_ENCODER_LOAD_DISK, (intptr_t)enc_fn);
483 while (ci.enc_codec_loaded == 0)
484 yield();
486 logf("codec loaded: %d", ci.enc_codec_loaded);
488 return ci.enc_codec_loaded > 0;
489 #else
490 (void)afmt;
491 return true;
492 #endif
493 } /* audio_load_encoder */
495 void audio_remove_encoder(void)
497 #if (CONFIG_PLATFORM & PLATFORM_NATIVE)
498 /* force encoder codec unload (if currently loaded) */
499 if (ci.enc_codec_loaded <= 0)
500 return;
502 ci.stop_encoder = true;
503 while (ci.enc_codec_loaded > 0)
504 yield();
505 #endif
506 } /* audio_remove_encoder */
508 #endif /* HAVE_RECORDING */
511 struct mp3entry* audio_current_track(void)
513 const char *filename;
514 struct playlist_track_info trackinfo;
515 int cur_idx;
516 int offset = ci.new_track + wps_offset;
517 struct mp3entry *write_id3;
519 cur_idx = (track_ridx + offset) & MAX_TRACK_MASK;
521 if (cur_idx == track_ridx && *thistrack_id3->path)
523 /* The usual case */
524 if (tracks[cur_idx].cuesheet_hid >= 0 && !thistrack_id3->cuesheet)
526 bufread(tracks[cur_idx].cuesheet_hid, sizeof(struct cuesheet), curr_cue);
527 thistrack_id3->cuesheet = curr_cue;
529 return thistrack_id3;
531 else if (automatic_skip && offset == -1 && *othertrack_id3->path)
533 /* We're in a track transition. The codec has moved on to the next track,
534 but the audio being played is still the same (now previous) track.
535 othertrack_id3.elapsed is being updated in an ISR by
536 codec_pcmbuf_position_callback */
537 if (tracks[cur_idx].cuesheet_hid >= 0 && !thistrack_id3->cuesheet)
539 bufread(tracks[cur_idx].cuesheet_hid, sizeof(struct cuesheet), curr_cue);
540 othertrack_id3->cuesheet = curr_cue;
542 return othertrack_id3;
545 if (offset != 0)
547 /* Codec may be using thistrack_id3, so it must not be overwritten.
548 If this is a manual skip, othertrack_id3 will become
549 thistrack_id3 in audio_check_new_track().
550 FIXME: If this is an automatic skip, it probably means multiple
551 short tracks fit in the PCM buffer. Overwriting othertrack_id3
552 can lead to an incorrect value later.
553 Note that othertrack_id3 may also be used for next track.
555 write_id3 = othertrack_id3;
557 else
559 write_id3 = thistrack_id3;
562 if (tracks[cur_idx].id3_hid >= 0)
564 /* The current track's info has been buffered but not read yet, so get it */
565 if (bufread(tracks[cur_idx].id3_hid, sizeof(struct mp3entry), write_id3)
566 == sizeof(struct mp3entry))
567 return write_id3;
570 /* We didn't find the ID3 metadata, so we fill temp_id3 with the little info
571 we have and return that. */
573 memset(write_id3, 0, sizeof(struct mp3entry));
575 playlist_get_track_info(NULL, playlist_next(0)+wps_offset, &trackinfo);
576 filename = trackinfo.filename;
577 if (!filename)
578 filename = "No file!";
580 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
581 if (tagcache_fill_tags(write_id3, filename))
582 return write_id3;
583 #endif
585 strlcpy(write_id3->path, filename, sizeof(write_id3->path));
586 write_id3->title = strrchr(write_id3->path, '/');
587 if (!write_id3->title)
588 write_id3->title = &write_id3->path[0];
589 else
590 write_id3->title++;
592 return write_id3;
595 struct mp3entry* audio_next_track(void)
597 int next_idx;
598 int offset = ci.new_track + wps_offset;
600 if (!audio_have_tracks())
601 return NULL;
603 if (wps_offset == -1 && *thistrack_id3->path)
605 /* We're in a track transition. The next track for the WPS is the one
606 currently being decoded. */
607 return thistrack_id3;
610 next_idx = (track_ridx + offset + 1) & MAX_TRACK_MASK;
612 if (tracks[next_idx].id3_hid >= 0)
614 if (bufread(tracks[next_idx].id3_hid, sizeof(struct mp3entry), othertrack_id3)
615 == sizeof(struct mp3entry))
616 return othertrack_id3;
617 else
618 return NULL;
621 if (next_idx == track_widx)
623 /* The next track hasn't been buffered yet, so we return the static
624 version of its metadata. */
625 return &unbuffered_id3;
628 return NULL;
631 /* gets a pointer to the id3 data, Not thread safe!, DON'T yield()/sleep() */
632 bool audio_peek_track(struct mp3entry** id3, int offset)
634 int next_idx;
635 int new_offset = ci.new_track + wps_offset + offset;
637 if (!audio_have_tracks())
638 return false;
639 next_idx = (track_ridx + new_offset) & MAX_TRACK_MASK;
641 if (tracks[next_idx].id3_hid >= 0)
643 return bufgetdata(tracks[next_idx].id3_hid, 0, (void**)id3)
644 == sizeof(struct mp3entry);
646 return false;
649 #ifdef HAVE_ALBUMART
650 int playback_current_aa_hid(int slot)
652 if (slot < 0)
653 return -1;
654 int cur_idx;
655 int offset = ci.new_track + wps_offset;
657 cur_idx = track_ridx + offset;
658 cur_idx &= MAX_TRACK_MASK;
660 return tracks[cur_idx].aa_hid[slot];
663 int playback_claim_aa_slot(struct dim *dim)
665 int i;
666 /* first try to find a slot already having the size to reuse it
667 * since we don't want albumart of the same size buffered multiple times */
668 FOREACH_ALBUMART(i)
670 struct albumart_slot *slot = &albumart_slots[i];
671 if (slot->dim.width == dim->width
672 && slot->dim.height == dim->height)
674 slot->used++;
675 return i;
678 /* size is new, find a free slot */
679 FOREACH_ALBUMART(i)
681 if (!albumart_slots[i].used)
683 albumart_slots[i].used++;
684 albumart_slots[i].dim = *dim;
685 return i;
688 /* sorry, no free slot */
689 return -1;
692 void playback_release_aa_slot(int slot)
694 /* invalidate the albumart_slot */
695 struct albumart_slot *aa_slot = &albumart_slots[slot];
696 if (aa_slot->used > 0)
697 aa_slot->used--;
700 #endif
701 void audio_play(long offset)
703 logf("audio_play");
705 #ifdef PLAYBACK_VOICE
706 /* Truncate any existing voice output so we don't have spelling
707 * etc. over the first part of the played track */
708 talk_force_shutup();
709 #endif
711 /* Start playback */
712 LOGFQUEUE("audio >| audio Q_AUDIO_PLAY: %ld", offset);
713 /* Don't return until playback has actually started */
714 queue_send(&audio_queue, Q_AUDIO_PLAY, offset);
717 void audio_stop(void)
719 /* Stop playback */
720 LOGFQUEUE("audio >| audio Q_AUDIO_STOP");
721 /* Don't return until playback has actually stopped */
722 queue_send(&audio_queue, Q_AUDIO_STOP, 0);
725 void audio_pause(void)
727 LOGFQUEUE("audio >| audio Q_AUDIO_PAUSE");
728 /* Don't return until playback has actually paused */
729 queue_send(&audio_queue, Q_AUDIO_PAUSE, true);
732 void audio_resume(void)
734 LOGFQUEUE("audio >| audio Q_AUDIO_PAUSE resume");
735 /* Don't return until playback has actually resumed */
736 queue_send(&audio_queue, Q_AUDIO_PAUSE, false);
739 void audio_skip(int direction)
741 if (playlist_check(ci.new_track + wps_offset + direction))
743 if (global_settings.beep)
744 pcmbuf_beep(2000, 100, 2500*global_settings.beep);
746 LOGFQUEUE("audio > audio Q_AUDIO_SKIP %d", direction);
747 queue_post(&audio_queue, Q_AUDIO_SKIP, direction);
748 /* Update wps while our message travels inside deep playback queues. */
749 wps_offset += direction;
751 else
753 /* No more tracks. */
754 if (global_settings.beep)
755 pcmbuf_beep(1000, 100, 1500*global_settings.beep);
759 void audio_next(void)
761 audio_skip(1);
764 void audio_prev(void)
766 audio_skip(-1);
769 void audio_next_dir(void)
771 LOGFQUEUE("audio > audio Q_AUDIO_DIR_SKIP 1");
772 queue_post(&audio_queue, Q_AUDIO_DIR_SKIP, 1);
775 void audio_prev_dir(void)
777 LOGFQUEUE("audio > audio Q_AUDIO_DIR_SKIP -1");
778 queue_post(&audio_queue, Q_AUDIO_DIR_SKIP, -1);
781 void audio_pre_ff_rewind(void)
783 LOGFQUEUE("audio > audio Q_AUDIO_PRE_FF_REWIND");
784 queue_post(&audio_queue, Q_AUDIO_PRE_FF_REWIND, 0);
787 void audio_ff_rewind(long newpos)
789 LOGFQUEUE("audio > audio Q_AUDIO_FF_REWIND");
790 queue_post(&audio_queue, Q_AUDIO_FF_REWIND, newpos);
793 void audio_flush_and_reload_tracks(void)
795 LOGFQUEUE("audio > audio Q_AUDIO_FLUSH");
796 queue_post(&audio_queue, Q_AUDIO_FLUSH, 0);
799 void audio_error_clear(void)
801 #ifdef AUDIO_HAVE_RECORDING
802 pcm_rec_error_clear();
803 #endif
806 int audio_status(void)
808 int ret = 0;
810 if (playing)
811 ret |= AUDIO_STATUS_PLAY;
813 if (paused)
814 ret |= AUDIO_STATUS_PAUSE;
816 #ifdef HAVE_RECORDING
817 /* Do this here for constitency with mpeg.c version */
818 /* FIXME: pcm_rec_status() is deprecated */
819 ret |= pcm_rec_status();
820 #endif
822 return ret;
825 int audio_get_file_pos(void)
827 return 0;
830 #ifdef HAVE_DISK_STORAGE
831 void audio_set_buffer_margin(int setting)
833 static const unsigned short lookup[] = {5, 15, 30, 60, 120, 180, 300, 600};
834 buffer_margin = lookup[setting];
835 logf("buffer margin: %ld", (long)buffer_margin);
836 set_filebuf_watermark();
838 #endif
840 #ifdef HAVE_CROSSFADE
841 /* Take necessary steps to enable or disable the crossfade setting */
842 void audio_set_crossfade(int enable)
844 size_t offset;
845 bool was_playing;
846 size_t size;
848 /* Tell it the next setting to use */
849 pcmbuf_request_crossfade_enable(enable);
851 /* Return if size hasn't changed or this is too early to determine
852 which in the second case there's no way we could be playing
853 anything at all */
854 if (pcmbuf_is_same_size()) return;
856 offset = 0;
857 was_playing = playing;
859 /* Playback has to be stopped before changing the buffer size */
860 if (was_playing)
862 /* Store the track resume position */
863 offset = thistrack_id3->offset;
866 /* Blast it - audio buffer will have to be setup again next time
867 something plays */
868 audio_get_buffer(true, &size);
870 /* Restart playback if audio was running previously */
871 if (was_playing)
872 audio_play(offset);
874 #endif
876 /* --- Routines called from multiple threads --- */
878 static void set_filebuf_watermark(void)
880 if (!filebuf)
881 return; /* Audio buffers not yet set up */
883 #ifdef HAVE_DISK_STORAGE
884 int seconds;
885 int spinup = ata_spinup_time();
886 if (spinup)
887 seconds = (spinup / HZ) + 1;
888 else
889 seconds = 5;
891 seconds += buffer_margin;
892 #else
893 /* flash storage */
894 int seconds = 1;
895 #endif
897 /* bitrate of last track in buffer dictates watermark */
898 struct mp3entry* id3 = NULL;
899 if (tracks[track_widx].taginfo_ready)
900 id3 = bufgetid3(tracks[track_widx].id3_hid);
901 else
902 id3 = bufgetid3(tracks[track_widx-1].id3_hid);
903 if (!id3) {
904 logf("fwmark: No id3 for last track (r%d/w%d), aborting!", track_ridx, track_widx);
905 return;
907 size_t bytes = id3->bitrate * (1000/8) * seconds;
908 buf_set_watermark(bytes);
909 logf("fwmark: %d", bytes);
912 /* --- Buffering callbacks --- */
914 static void buffering_low_buffer_callback(void *data)
916 (void)data;
917 logf("low buffer callback");
919 if (filling == STATE_FULL || filling == STATE_END_OF_PLAYLIST) {
920 /* force a refill */
921 LOGFQUEUE("buffering > audio Q_AUDIO_FILL_BUFFER");
922 queue_post(&audio_queue, Q_AUDIO_FILL_BUFFER, 0);
926 static void buffering_handle_rebuffer_callback(void *data)
928 (void)data;
929 LOGFQUEUE("audio >| audio Q_AUDIO_FLUSH");
930 queue_post(&audio_queue, Q_AUDIO_FLUSH, 0);
933 static void buffering_handle_finished_callback(void *data)
935 logf("handle %d finished buffering", *(int*)data);
936 int hid = (*(int*)data);
938 if (hid == tracks[track_widx].id3_hid)
940 int offset = ci.new_track + wps_offset;
941 int next_idx = (track_ridx + offset + 1) & MAX_TRACK_MASK;
942 /* The metadata handle for the last loaded track has been buffered.
943 We can ask the audio thread to load the rest of the track's data. */
944 LOGFQUEUE("audio >| audio Q_AUDIO_FINISH_LOAD");
945 queue_post(&audio_queue, Q_AUDIO_FINISH_LOAD, 0);
946 if (tracks[next_idx].id3_hid == hid)
947 send_event(PLAYBACK_EVENT_NEXTTRACKID3_AVAILABLE, NULL);
949 else
951 /* This is most likely an audio handle, so we strip the useless
952 trailing tags that are left. */
953 strip_tags(hid);
955 if (hid == tracks[track_widx-1].audio_hid
956 && filling == STATE_END_OF_PLAYLIST)
958 /* This was the last track in the playlist.
959 We now have all the data we need. */
960 logf("last track finished buffering");
961 filling = STATE_FINISHED;
967 /* --- Audio thread --- */
969 static bool audio_have_tracks(void)
971 return (audio_track_count() != 0);
974 static int audio_free_track_count(void)
976 /* Used tracks + free tracks adds up to MAX_TRACK - 1 */
977 return MAX_TRACK - 1 - audio_track_count();
980 int audio_track_count(void)
982 /* Calculate difference from track_ridx to track_widx
983 * taking into account a possible wrap-around. */
984 return (MAX_TRACK + track_widx - track_ridx) & MAX_TRACK_MASK;
987 long audio_filebufused(void)
989 return (long) buf_used();
992 /* Update track info after successful a codec track change */
993 static void audio_update_trackinfo(void)
995 /* Load the curent track's metadata into curtrack_id3 */
996 if (CUR_TI->id3_hid >= 0)
997 copy_mp3entry(thistrack_id3, bufgetid3(CUR_TI->id3_hid));
999 /* Reset current position */
1000 thistrack_id3->elapsed = 0;
1001 thistrack_id3->offset = 0;
1003 /* Update the codec API */
1004 ci.filesize = CUR_TI->filesize;
1005 ci.id3 = thistrack_id3;
1006 ci.curpos = 0;
1007 ci.taginfo_ready = &CUR_TI->taginfo_ready;
1010 /* Clear tracks between write and read, non inclusive */
1011 static void audio_clear_track_entries(void)
1013 int cur_idx = track_widx;
1015 logf("Clearing tracks: r%d/w%d", track_ridx, track_widx);
1017 /* Loop over all tracks from write-to-read */
1018 while (1)
1020 cur_idx = (cur_idx + 1) & MAX_TRACK_MASK;
1022 if (cur_idx == track_ridx)
1023 break;
1025 clear_track_info(&tracks[cur_idx]);
1029 /* Clear all tracks */
1030 static bool audio_release_tracks(void)
1032 int i, cur_idx;
1034 logf("releasing all tracks");
1036 for(i = 0; i < MAX_TRACK; i++)
1038 cur_idx = (track_ridx + i) & MAX_TRACK_MASK;
1039 if (!clear_track_info(&tracks[cur_idx]))
1040 return false;
1043 return true;
1046 static bool audio_loadcodec(bool start_play)
1048 int prev_track;
1049 char codec_path[MAX_PATH]; /* Full path to codec */
1050 const struct mp3entry *id3, *prev_id3;
1052 if (tracks[track_widx].id3_hid < 0) {
1053 return false;
1056 id3 = bufgetid3(tracks[track_widx].id3_hid);
1057 if (!id3)
1058 return false;
1060 const char *codec_fn = get_codec_filename(id3->codectype);
1061 if (codec_fn == NULL)
1062 return false;
1064 tracks[track_widx].codec_hid = -1;
1066 if (start_play)
1068 /* Load the codec directly from disk and save some memory. */
1069 track_ridx = track_widx;
1070 ci.filesize = CUR_TI->filesize;
1071 ci.id3 = thistrack_id3;
1072 ci.taginfo_ready = &CUR_TI->taginfo_ready;
1073 ci.curpos = 0;
1074 LOGFQUEUE("codec > codec Q_CODEC_LOAD_DISK");
1075 queue_post(&codec_queue, Q_CODEC_LOAD_DISK, (intptr_t)codec_fn);
1076 return true;
1078 else
1080 /* If we already have another track than this one buffered */
1081 if (track_widx != track_ridx)
1083 prev_track = (track_widx - 1) & MAX_TRACK_MASK;
1085 id3 = bufgetid3(tracks[track_widx].id3_hid);
1086 prev_id3 = bufgetid3(tracks[prev_track].id3_hid);
1088 /* If the previous codec is the same as this one, there is no need
1089 * to put another copy of it on the file buffer */
1090 if (id3 && prev_id3 &&
1091 get_codec_base_type(id3->codectype) ==
1092 get_codec_base_type(prev_id3->codectype)
1093 && audio_codec_loaded)
1095 logf("Reusing prev. codec");
1096 return true;
1101 codec_get_full_path(codec_path, codec_fn);
1103 tracks[track_widx].codec_hid = bufopen(codec_path, 0, TYPE_CODEC, NULL);
1104 if (tracks[track_widx].codec_hid < 0)
1105 return false;
1107 logf("Loaded codec");
1109 return true;
1112 /* Load metadata for the next track (with bufopen). The rest of the track
1113 loading will be handled by audio_finish_load_track once the metadata has been
1114 actually loaded by the buffering thread. */
1115 static bool audio_load_track(size_t offset, bool start_play)
1117 char name_buf[MAX_PATH + 1];
1118 const char *trackname;
1119 int fd = -1;
1121 if (track_load_started) {
1122 /* There is already a track load in progress, so track_widx hasn't been
1123 incremented yet. Loading another track would overwrite the one that
1124 hasn't finished loading. */
1125 logf("audio_load_track(): a track load is already in progress");
1126 return false;
1129 start_play_g = start_play; /* will be read by audio_finish_load_track */
1131 /* Stop buffer filling if there is no free track entries.
1132 Don't fill up the last track entry (we wan't to store next track
1133 metadata there). */
1134 if (!audio_free_track_count())
1136 logf("No free tracks");
1137 return false;
1140 last_peek_offset++;
1141 tracks[track_widx].taginfo_ready = false;
1143 logf("Buffering track: r%d/w%d", track_ridx, track_widx);
1144 /* Get track name from current playlist read position. */
1145 while ((trackname = playlist_peek(last_peek_offset, name_buf,
1146 sizeof(name_buf))) != NULL)
1148 /* Handle broken playlists. */
1149 fd = open(trackname, O_RDONLY);
1150 if (fd < 0)
1152 logf("Open failed");
1153 /* Skip invalid entry from playlist. */
1154 playlist_skip_entry(NULL, last_peek_offset);
1156 else
1157 break;
1160 if (!trackname)
1162 logf("End-of-playlist");
1163 memset(&unbuffered_id3, 0, sizeof(struct mp3entry));
1164 filling = STATE_END_OF_PLAYLIST;
1166 if (thistrack_id3->length == 0 && thistrack_id3->filesize == 0)
1168 /* Stop playback if no valid track was found. */
1169 audio_stop_playback();
1172 return false;
1175 tracks[track_widx].filesize = filesize(fd);
1177 if (offset > tracks[track_widx].filesize)
1178 offset = 0;
1180 /* Set default values */
1181 if (start_play)
1183 buf_set_watermark(filebuflen/2);
1184 dsp_configure(ci.dsp, DSP_RESET, 0);
1185 playlist_update_resume_info(audio_current_track());
1188 /* Get track metadata if we don't already have it. */
1189 if (tracks[track_widx].id3_hid < 0)
1191 tracks[track_widx].id3_hid = bufopen(trackname, 0, TYPE_ID3, NULL);
1193 if (tracks[track_widx].id3_hid < 0)
1195 /* Buffer is full. */
1196 get_metadata(&unbuffered_id3, fd, trackname);
1197 last_peek_offset--;
1198 close(fd);
1199 logf("buffer is full for now (get metadata)");
1200 filling = STATE_FULL;
1201 return false;
1204 if (track_widx == track_ridx)
1206 /* TODO: Superfluos buffering call? */
1207 buf_request_buffer_handle(tracks[track_widx].id3_hid);
1208 struct mp3entry *id3 = bufgetid3(tracks[track_widx].id3_hid);
1209 if (id3)
1211 copy_mp3entry(thistrack_id3, id3);
1212 thistrack_id3->offset = offset;
1214 else
1215 memset(thistrack_id3, 0, sizeof(struct mp3entry));
1218 if (start_play)
1220 playlist_update_resume_info(audio_current_track());
1224 close(fd);
1225 track_load_started = true; /* Remember that we've started loading a track */
1226 return true;
1229 /* Second part of the track loading: We now have the metadata available, so we
1230 can load the codec, the album art and finally the audio data.
1231 This is called on the audio thread after the buffering thread calls the
1232 buffering_handle_finished_callback callback. */
1233 static void audio_finish_load_track(void)
1235 size_t file_offset = 0;
1236 size_t offset = 0;
1237 bool start_play = start_play_g;
1239 track_load_started = false;
1241 if (tracks[track_widx].id3_hid < 0) {
1242 logf("No metadata");
1243 return;
1246 struct mp3entry *track_id3;
1248 if (track_widx == track_ridx)
1249 track_id3 = thistrack_id3;
1250 else
1251 track_id3 = bufgetid3(tracks[track_widx].id3_hid);
1253 if (track_id3->length == 0 && track_id3->filesize == 0)
1255 logf("audio_finish_load_track: invalid metadata");
1257 /* Invalid metadata */
1258 bufclose(tracks[track_widx].id3_hid);
1259 tracks[track_widx].id3_hid = -1;
1261 /* Skip invalid entry from playlist. */
1262 playlist_skip_entry(NULL, last_peek_offset--);
1264 /* load next track */
1265 LOGFQUEUE("audio > audio Q_AUDIO_FILL_BUFFER %d", (int)start_play);
1266 queue_post(&audio_queue, Q_AUDIO_FILL_BUFFER, start_play);
1268 return;
1270 /* Try to load a cuesheet for the track */
1271 if (curr_cue)
1273 char cuepath[MAX_PATH];
1274 if (look_for_cuesheet_file(track_id3->path, cuepath))
1276 void *temp;
1277 tracks[track_widx].cuesheet_hid =
1278 bufalloc(NULL, sizeof(struct cuesheet), TYPE_CUESHEET);
1279 if (tracks[track_widx].cuesheet_hid >= 0)
1281 bufgetdata(tracks[track_widx].cuesheet_hid,
1282 sizeof(struct cuesheet), &temp);
1283 struct cuesheet *cuesheet = (struct cuesheet*)temp;
1284 if (!parse_cuesheet(cuepath, cuesheet))
1286 bufclose(tracks[track_widx].cuesheet_hid);
1287 track_id3->cuesheet = NULL;
1292 #ifdef HAVE_ALBUMART
1294 int i;
1295 char aa_path[MAX_PATH];
1296 FOREACH_ALBUMART(i)
1298 /* albumart_slots may change during a yield of bufopen,
1299 * but that's no problem */
1300 if (tracks[track_widx].aa_hid[i] >= 0 || !albumart_slots[i].used)
1301 continue;
1302 /* find_albumart will error out if the wps doesn't have AA */
1303 if (find_albumart(track_id3, aa_path, sizeof(aa_path),
1304 &(albumart_slots[i].dim)))
1306 int aa_hid = bufopen(aa_path, 0, TYPE_BITMAP,
1307 &(albumart_slots[i].dim));
1309 if(aa_hid == ERR_BUFFER_FULL)
1311 filling = STATE_FULL;
1312 logf("buffer is full for now (get album art)");
1313 return; /* No space for track's album art, not an error */
1315 else if (aa_hid < 0)
1317 /* another error, ignore AlbumArt */
1318 logf("Album art loading failed");
1320 tracks[track_widx].aa_hid[i] = aa_hid;
1325 #endif
1327 /* Load the codec. */
1328 if (!audio_loadcodec(start_play))
1330 if (tracks[track_widx].codec_hid == ERR_BUFFER_FULL)
1332 /* No space for codec on buffer, not an error */
1333 filling = STATE_FULL;
1334 return;
1337 /* This is an error condition, either no codec was found, or reading
1338 * the codec file failed part way through, either way, skip the track */
1339 /* FIXME: We should not use splashf from audio thread! */
1340 splashf(HZ*2, "No codec for: %s", track_id3->path);
1341 /* Skip invalid entry from playlist. */
1342 playlist_skip_entry(NULL, last_peek_offset);
1343 return;
1346 track_id3->elapsed = 0;
1347 offset = track_id3->offset;
1348 size_t resume_rewind = (global_settings.resume_rewind *
1349 track_id3->bitrate * 1000) / 8;
1351 if (offset < resume_rewind)
1353 offset = 0;
1355 else
1357 offset -= resume_rewind;
1360 enum data_type type = TYPE_PACKET_AUDIO;
1362 switch (track_id3->codectype) {
1363 case AFMT_MPA_L1:
1364 case AFMT_MPA_L2:
1365 case AFMT_MPA_L3:
1366 if (offset > 0) {
1367 file_offset = offset;
1369 break;
1371 case AFMT_WAVPACK:
1372 if (offset > 0) {
1373 file_offset = offset;
1374 track_id3->elapsed = track_id3->length / 2;
1376 break;
1378 case AFMT_NSF:
1379 case AFMT_SPC:
1380 case AFMT_SID:
1381 logf("Loading atomic %d",track_id3->codectype);
1382 type = TYPE_ATOMIC_AUDIO;
1383 break;
1385 default:
1386 /* no special treatment needed */
1387 break;
1390 track_id3->offset = offset;
1392 logf("load track: %s", track_id3->path);
1394 if (file_offset > AUDIO_REBUFFER_GUESS_SIZE)
1395 file_offset -= AUDIO_REBUFFER_GUESS_SIZE;
1396 else if (track_id3->first_frame_offset)
1397 file_offset = track_id3->first_frame_offset;
1398 else
1399 file_offset = 0;
1401 tracks[track_widx].audio_hid = bufopen(track_id3->path, file_offset, type,
1402 NULL);
1404 /* No space left, not an error */
1405 if (tracks[track_widx].audio_hid == ERR_BUFFER_FULL)
1407 filling = STATE_FULL;
1408 logf("buffer is full for now (load audio)");
1409 return;
1411 else if (tracks[track_widx].audio_hid < 0)
1413 /* another error, do not continue either */
1414 logf("Could not add audio data handle");
1415 return;
1418 /* All required data is now available for the codec. */
1419 tracks[track_widx].taginfo_ready = true;
1421 if (start_play)
1423 ci.curpos=file_offset;
1424 buf_request_buffer_handle(tracks[track_widx].audio_hid);
1427 track_widx = (track_widx + 1) & MAX_TRACK_MASK;
1429 send_event(PLAYBACK_EVENT_TRACK_BUFFER, track_id3);
1431 /* load next track */
1432 LOGFQUEUE("audio > audio Q_AUDIO_FILL_BUFFER");
1433 queue_post(&audio_queue, Q_AUDIO_FILL_BUFFER, 0);
1435 return;
1438 static void audio_fill_file_buffer(bool start_play, size_t offset)
1440 trigger_cpu_boost();
1442 /* No need to rebuffer if there are track skips pending,
1443 * however don't cancel buffering on skipping while filling. */
1444 if (ci.new_track != 0 && filling != STATE_FILLING)
1445 return;
1446 filling = STATE_FILLING;
1448 /* Must reset the buffer before use if trashed or voice only - voice
1449 file size shouldn't have changed so we can go straight from
1450 AUDIOBUF_STATE_VOICED_ONLY to AUDIOBUF_STATE_INITIALIZED */
1451 if (buffer_state != AUDIOBUF_STATE_INITIALIZED)
1452 audio_reset_buffer();
1454 logf("Starting buffer fill");
1456 if (!start_play)
1457 audio_clear_track_entries();
1459 /* Save the current resume position once. */
1460 playlist_update_resume_info(audio_current_track());
1462 audio_load_track(offset, start_play);
1465 static void audio_rebuffer(void)
1467 logf("Forcing rebuffer");
1469 clear_track_info(CUR_TI);
1471 /* Reset track pointers */
1472 track_widx = track_ridx;
1473 audio_clear_track_entries();
1475 /* Reset a possibly interrupted track load */
1476 track_load_started = false;
1478 /* Fill the buffer */
1479 last_peek_offset = -1;
1480 ci.curpos = 0;
1482 if (!CUR_TI->taginfo_ready)
1483 memset(thistrack_id3, 0, sizeof(struct mp3entry));
1485 audio_fill_file_buffer(false, 0);
1488 /* Called on request from the codec to get a new track. This is the codec part
1489 of the track transition. */
1490 static int audio_check_new_track(void)
1492 int track_count = audio_track_count();
1493 int old_track_ridx = track_ridx;
1494 int i, idx;
1495 bool forward;
1496 struct mp3entry *temp = thistrack_id3;
1498 /* Now it's good time to send track finish events. */
1499 send_event(PLAYBACK_EVENT_TRACK_FINISH, thistrack_id3);
1500 /* swap the mp3entry pointers */
1501 thistrack_id3 = othertrack_id3;
1502 othertrack_id3 = temp;
1503 ci.id3 = thistrack_id3;
1504 memset(thistrack_id3, 0, sizeof(struct mp3entry));
1506 if (dir_skip)
1508 dir_skip = false;
1509 /* regardless of the return value we need to rebuffer.
1510 if it fails the old playlist will resume, else the
1511 next dir will start playing */
1512 playlist_next_dir(ci.new_track);
1513 ci.new_track = 0;
1514 audio_rebuffer();
1515 goto skip_done;
1518 if (new_playlist)
1519 ci.new_track = 0;
1521 /* If the playlist isn't that big */
1522 if (automatic_skip)
1524 while (!playlist_check(ci.new_track))
1526 if (ci.new_track >= 0)
1528 LOGFQUEUE("audio >|= codec Q_CODEC_REQUEST_FAILED");
1529 return Q_CODEC_REQUEST_FAILED;
1531 ci.new_track++;
1535 /* Update the playlist */
1536 last_peek_offset -= ci.new_track;
1538 if (playlist_next(ci.new_track) < 0)
1540 LOGFQUEUE("audio >|= codec Q_CODEC_REQUEST_FAILED");
1541 return Q_CODEC_REQUEST_FAILED;
1544 if (new_playlist)
1546 ci.new_track = 1;
1547 new_playlist = false;
1550 /* Save a pointer to the old track to allow later clearing */
1551 prev_ti = CUR_TI;
1553 for (i = 0; i < ci.new_track; i++)
1555 idx = (track_ridx + i) & MAX_TRACK_MASK;
1556 struct mp3entry *id3 = bufgetid3(tracks[idx].id3_hid);
1557 ssize_t offset = buf_handle_offset(tracks[idx].audio_hid);
1558 if (!id3 || offset < 0 || (unsigned)offset > id3->first_frame_offset)
1560 /* We don't have all the audio data for that track, so clear it,
1561 but keep the metadata. */
1562 if (tracks[idx].audio_hid >= 0 && bufclose(tracks[idx].audio_hid))
1564 tracks[idx].audio_hid = -1;
1565 tracks[idx].filesize = 0;
1570 /* Move to the new track */
1571 track_ridx = (track_ridx + ci.new_track) & MAX_TRACK_MASK;
1572 buf_set_base_handle(CUR_TI->audio_hid);
1575 if (automatic_skip)
1577 wps_offset = -ci.new_track;
1580 /* If it is not safe to even skip this many track entries */
1581 if (ci.new_track >= track_count || ci.new_track <= track_count - MAX_TRACK)
1583 ci.new_track = 0;
1584 audio_rebuffer();
1585 goto skip_done;
1588 forward = ci.new_track > 0;
1589 ci.new_track = 0;
1591 /* If the target track is clearly not in memory */
1592 if (CUR_TI->filesize == 0 || !CUR_TI->taginfo_ready)
1594 audio_rebuffer();
1595 goto skip_done;
1598 /* When skipping backwards, it is possible that we've found a track that's
1599 * buffered, but which is around the track-wrap and therefore not the track
1600 * we are looking for */
1601 if (!forward)
1603 int cur_idx = track_ridx;
1604 bool taginfo_ready = true;
1605 /* We've wrapped the buffer backwards if new > old */
1606 bool wrap = track_ridx > old_track_ridx;
1608 while (1)
1610 cur_idx = (cur_idx + 1) & MAX_TRACK_MASK;
1612 /* if we've advanced past the wrap when cur_idx is zeroed */
1613 if (!cur_idx)
1614 wrap = false;
1616 /* if we aren't still on the wrap and we've caught the old track */
1617 if (!(wrap || cur_idx < old_track_ridx))
1618 break;
1620 /* If we hit a track in between without valid tag info, bail */
1621 if (!tracks[cur_idx].taginfo_ready)
1623 taginfo_ready = false;
1624 break;
1627 if (!taginfo_ready)
1629 audio_rebuffer();
1633 skip_done:
1634 audio_update_trackinfo();
1635 LOGFQUEUE("audio >|= codec Q_CODEC_REQUEST_COMPLETE");
1636 return Q_CODEC_REQUEST_COMPLETE;
1639 unsigned long audio_prev_elapsed(void)
1641 return prev_track_elapsed;
1644 void audio_set_prev_elapsed(unsigned long setting)
1646 prev_track_elapsed = setting;
1649 static void audio_stop_codec_flush(void)
1651 ci.stop_codec = true;
1652 pcmbuf_pause(true);
1654 while (audio_codec_loaded)
1655 yield();
1657 /* If the audio codec is not loaded any more, and the audio is still
1658 * playing, it is now and _only_ now safe to call this function from the
1659 * audio thread */
1660 if (pcm_is_playing())
1662 pcmbuf_play_stop();
1663 pcm_play_lock();
1664 queue_clear(&pcmbuf_queue);
1665 pcm_play_unlock();
1667 pcmbuf_pause(paused);
1670 static void audio_stop_playback(void)
1672 if (playing)
1674 /* If we were playing, save resume information */
1675 struct mp3entry *id3 = NULL;
1677 if (!ci.stop_codec)
1679 /* Set this early, the outside code yields and may allow the codec
1680 to try to wait for a reply on a buffer wait */
1681 ci.stop_codec = true;
1682 id3 = audio_current_track();
1685 /* Save the current playing spot, or NULL if the playlist has ended */
1686 playlist_update_resume_info(id3);
1688 /* TODO: Create auto bookmark too? */
1690 prev_track_elapsed = othertrack_id3->elapsed;
1692 remove_event(BUFFER_EVENT_BUFFER_LOW, buffering_low_buffer_callback);
1695 audio_stop_codec_flush();
1696 paused = false;
1697 playing = false;
1698 track_load_started = false;
1700 filling = STATE_IDLE;
1702 /* Mark all entries null. */
1703 audio_clear_track_entries();
1705 /* Close all tracks */
1706 audio_release_tracks();
1709 static void audio_play_start(size_t offset)
1711 int i;
1713 send_event(PLAYBACK_EVENT_START_PLAYBACK, NULL);
1714 #if INPUT_SRC_CAPS != 0
1715 audio_set_input_source(AUDIO_SRC_PLAYBACK, SRCF_PLAYBACK);
1716 audio_set_output_source(AUDIO_SRC_PLAYBACK);
1717 #endif
1719 /* Wait for any previously playing audio to flush - TODO: Not necessary? */
1720 paused = false;
1721 audio_stop_codec_flush();
1723 playing = true;
1724 track_load_started = false;
1726 ci.new_track = 0;
1727 ci.seek_time = 0;
1728 wps_offset = 0;
1730 sound_set_volume(global_settings.volume);
1731 track_widx = track_ridx = 0;
1732 buf_set_base_handle(-1);
1734 /* Clear all track entries. */
1735 for (i = 0; i < MAX_TRACK; i++) {
1736 clear_track_info(&tracks[i]);
1739 last_peek_offset = -1;
1741 /* Officially playing */
1742 queue_reply(&audio_queue, 1);
1744 audio_fill_file_buffer(true, offset);
1746 add_event(BUFFER_EVENT_BUFFER_LOW, false, buffering_low_buffer_callback);
1748 LOGFQUEUE("audio > audio Q_AUDIO_TRACK_CHANGED");
1749 queue_post(&audio_queue, Q_AUDIO_TRACK_CHANGED, 0);
1753 /* Invalidates all but currently playing track. */
1754 static void audio_invalidate_tracks(void)
1756 if (audio_have_tracks())
1758 last_peek_offset = 0;
1759 track_widx = track_ridx;
1761 /* Mark all other entries null (also buffered wrong metadata). */
1762 audio_clear_track_entries();
1764 track_widx = (track_widx + 1) & MAX_TRACK_MASK;
1766 audio_fill_file_buffer(false, 0);
1767 send_event(PLAYBACK_EVENT_TRACK_CHANGE, thistrack_id3);
1771 static void audio_new_playlist(void)
1773 /* Prepare to start a new fill from the beginning of the playlist */
1774 last_peek_offset = -1;
1775 if (audio_have_tracks())
1777 if (paused)
1778 skipped_during_pause = true;
1779 track_widx = track_ridx;
1780 audio_clear_track_entries();
1782 track_widx = (track_widx + 1) & MAX_TRACK_MASK;
1784 /* Mark the current track as invalid to prevent skipping back to it */
1785 CUR_TI->taginfo_ready = false;
1788 /* Signal the codec to initiate a track change forward */
1789 new_playlist = true;
1790 ci.new_track = 1;
1792 /* Officially playing */
1793 queue_reply(&audio_queue, 1);
1795 audio_fill_file_buffer(false, 0);
1798 /* Called on manual track skip */
1799 static void audio_initiate_track_change(long direction)
1801 logf("audio_initiate_track_change(%ld)", direction);
1803 ci.new_track += direction;
1804 wps_offset -= direction;
1805 if (paused)
1806 skipped_during_pause = true;
1809 /* Called on manual dir skip */
1810 static void audio_initiate_dir_change(long direction)
1812 dir_skip = true;
1813 ci.new_track = direction;
1814 if (paused)
1815 skipped_during_pause = true;
1818 /* Called when PCM track change is complete */
1819 static void audio_finalise_track_change(void)
1821 logf("audio_finalise_track_change");
1823 if (automatic_skip)
1825 wps_offset = 0;
1826 automatic_skip = false;
1828 /* Invalidate prevtrack_id3 */
1829 memset(othertrack_id3, 0, sizeof(struct mp3entry));
1831 if (prev_ti && prev_ti->audio_hid < 0)
1833 /* No audio left so we clear all the track info. */
1834 clear_track_info(prev_ti);
1837 send_event(PLAYBACK_EVENT_TRACK_CHANGE, thistrack_id3);
1838 playlist_update_resume_info(audio_current_track());
1842 * Layout audio buffer as follows - iram buffer depends on target:
1843 * [|SWAP:iram][|TALK]|FILE|GUARD|PCM|[SWAP:dram[|iram]|]
1845 static void audio_reset_buffer(void)
1847 /* see audio_get_recording_buffer if this is modified */
1848 logf("audio_reset_buffer");
1850 /* If the setup of anything allocated before the file buffer is
1851 changed, do check the adjustments after the buffer_alloc call
1852 as it will likely be affected and need sliding over */
1854 /* Initially set up file buffer as all space available */
1855 malloc_buf = audiobuf + talk_get_bufsize();
1857 /* Align the malloc buf to line size.
1858 * Especially important to cf targets that do line reads/writes.
1859 * Also for targets which need aligned DMA storage buffers */
1860 malloc_buf = (unsigned char *)(((uintptr_t)malloc_buf + (CACHEALIGN_SIZE - 1)) & ~(CACHEALIGN_SIZE - 1));
1861 filebuf = malloc_buf; /* filebuf line align implied */
1862 filebuflen = (audiobufend - filebuf) & ~(CACHEALIGN_SIZE - 1);
1864 /* Subtract whatever the pcm buffer says it used plus the guard buffer */
1865 const size_t pcmbuf_size = pcmbuf_init(filebuf + filebuflen) +GUARD_BUFSIZE;
1866 if(pcmbuf_size > filebuflen)
1867 panicf("%s(): EOM (%zu > %zu)", __func__, pcmbuf_size, filebuflen);
1869 filebuflen -= pcmbuf_size;
1871 /* Make sure filebuflen is a longword multiple after adjustment - filebuf
1872 will already be line aligned */
1873 filebuflen &= ~3;
1875 buffering_reset(filebuf, filebuflen);
1877 /* Clear any references to the file buffer */
1878 buffer_state = AUDIOBUF_STATE_INITIALIZED;
1880 #if defined(ROCKBOX_HAS_LOGF) && defined(LOGF_ENABLE)
1881 /* Make sure everything adds up - yes, some info is a bit redundant but
1882 aids viewing and the sumation of certain variables should add up to
1883 the location of others. */
1885 size_t pcmbufsize;
1886 const unsigned char *pcmbuf = pcmbuf_get_meminfo(&pcmbufsize);
1887 logf("mabuf: %08X", (unsigned)malloc_buf);
1888 logf("fbuf: %08X", (unsigned)filebuf);
1889 logf("fbufe: %08X", (unsigned)(filebuf + filebuflen));
1890 logf("gbuf: %08X", (unsigned)(filebuf + filebuflen));
1891 logf("gbufe: %08X", (unsigned)(filebuf + filebuflen + GUARD_BUFSIZE));
1892 logf("pcmb: %08X", (unsigned)pcmbuf);
1893 logf("pcmbe: %08X", (unsigned)(pcmbuf + pcmbufsize));
1895 #endif
1898 static void audio_thread(void)
1900 struct queue_event ev;
1902 pcm_postinit();
1904 audio_thread_ready = true;
1906 while (1)
1908 if (filling != STATE_FILLING && filling != STATE_IDLE) {
1909 /* End of buffering, let's calculate the watermark and unboost */
1910 set_filebuf_watermark();
1911 cancel_cpu_boost();
1914 if (!pcmbuf_queue_scan(&ev))
1915 queue_wait_w_tmo(&audio_queue, &ev, HZ/2);
1917 switch (ev.id) {
1919 case Q_AUDIO_FILL_BUFFER:
1920 LOGFQUEUE("audio < Q_AUDIO_FILL_BUFFER %d", (int)ev.data);
1921 audio_fill_file_buffer((bool)ev.data, 0);
1922 break;
1924 case Q_AUDIO_FINISH_LOAD:
1925 LOGFQUEUE("audio < Q_AUDIO_FINISH_LOAD");
1926 audio_finish_load_track();
1927 buf_set_base_handle(CUR_TI->audio_hid);
1928 break;
1930 case Q_AUDIO_PLAY:
1931 LOGFQUEUE("audio < Q_AUDIO_PLAY");
1932 if (playing && ev.data <= 0)
1933 audio_new_playlist();
1934 else
1936 audio_stop_playback();
1937 audio_play_start((size_t)ev.data);
1939 break;
1941 case Q_AUDIO_STOP:
1942 LOGFQUEUE("audio < Q_AUDIO_STOP");
1943 if (playing)
1944 audio_stop_playback();
1945 if (ev.data != 0)
1946 queue_clear(&audio_queue);
1947 break;
1949 case Q_AUDIO_PAUSE:
1950 LOGFQUEUE("audio < Q_AUDIO_PAUSE");
1951 if (!(bool) ev.data && skipped_during_pause
1952 #ifdef HAVE_CROSSFADE
1953 && !pcmbuf_is_crossfade_active()
1954 #endif
1956 pcmbuf_play_stop(); /* Flush old track on resume after skip */
1957 skipped_during_pause = false;
1958 if (!playing)
1959 break;
1960 pcmbuf_pause((bool)ev.data);
1961 paused = (bool)ev.data;
1962 break;
1964 case Q_AUDIO_SKIP:
1965 LOGFQUEUE("audio < Q_AUDIO_SKIP");
1966 audio_initiate_track_change((long)ev.data);
1967 break;
1969 case Q_AUDIO_PRE_FF_REWIND:
1970 LOGFQUEUE("audio < Q_AUDIO_PRE_FF_REWIND");
1971 if (!playing)
1972 break;
1973 pcmbuf_pause(true);
1974 break;
1976 case Q_AUDIO_FF_REWIND:
1977 LOGFQUEUE("audio < Q_AUDIO_FF_REWIND");
1978 if (!playing)
1979 break;
1980 if (automatic_skip)
1982 /* An automatic track skip is in progress. Finalize it,
1983 then go back to the previous track */
1984 audio_finalise_track_change();
1985 ci.new_track = -1;
1987 ci.seek_time = (long)ev.data+1;
1988 break;
1990 case Q_AUDIO_CHECK_NEW_TRACK:
1991 LOGFQUEUE("audio < Q_AUDIO_CHECK_NEW_TRACK");
1992 queue_reply(&audio_queue, audio_check_new_track());
1993 break;
1995 case Q_AUDIO_DIR_SKIP:
1996 LOGFQUEUE("audio < Q_AUDIO_DIR_SKIP");
1997 audio_initiate_dir_change(ev.data);
1998 break;
2000 case Q_AUDIO_FLUSH:
2001 LOGFQUEUE("audio < Q_AUDIO_FLUSH");
2002 audio_invalidate_tracks();
2003 break;
2005 case Q_AUDIO_TRACK_CHANGED:
2006 /* PCM track change done */
2007 LOGFQUEUE("audio < Q_AUDIO_TRACK_CHANGED");
2008 audio_finalise_track_change();
2009 break;
2010 #if (CONFIG_PLATFORM & PLATFORM_NATIVE)
2011 case SYS_USB_CONNECTED:
2012 LOGFQUEUE("audio < SYS_USB_CONNECTED");
2013 if (playing)
2014 audio_stop_playback();
2015 #ifdef PLAYBACK_VOICE
2016 voice_stop();
2017 #endif
2018 usb_acknowledge(SYS_USB_CONNECTED_ACK);
2019 usb_wait_for_disconnect(&audio_queue);
2021 /* Mark all entries null. */
2022 audio_clear_track_entries();
2024 /* release tracks to make sure all handles are closed */
2025 audio_release_tracks();
2026 break;
2027 #endif
2029 case SYS_TIMEOUT:
2030 LOGFQUEUE_SYS_TIMEOUT("audio < SYS_TIMEOUT");
2031 break;
2033 default:
2034 /* LOGFQUEUE("audio < default : %08lX", ev.id); */
2035 break;
2036 } /* end switch */
2037 } /* end while */
2040 /* Initialize the audio system - called from init() in main.c.
2041 * Last function because of all the references to internal symbols
2043 void audio_init(void)
2045 unsigned int audio_thread_id;
2047 /* Can never do this twice */
2048 if (audio_is_initialized)
2050 logf("audio: already initialized");
2051 return;
2054 logf("audio: initializing");
2056 /* Initialize queues before giving control elsewhere in case it likes
2057 to send messages. Thread creation will be delayed however so nothing
2058 starts running until ready if something yields such as talk_init. */
2059 queue_init(&audio_queue, true);
2060 queue_init(&codec_queue, false);
2061 queue_init(&pcmbuf_queue, false);
2063 pcm_init();
2065 codec_init_codec_api();
2067 thistrack_id3 = &mp3entry_buf[0];
2068 othertrack_id3 = &mp3entry_buf[1];
2070 /* cuesheet support */
2071 if (global_settings.cuesheet)
2072 curr_cue = (struct cuesheet*)buffer_alloc(sizeof(struct cuesheet));
2074 /* initialize the buffer */
2075 filebuf = audiobuf;
2077 /* audio_reset_buffer must to know the size of voice buffer so init
2078 talk first */
2079 talk_init();
2081 make_codec_thread();
2083 audio_thread_id = create_thread(audio_thread, audio_stack,
2084 sizeof(audio_stack), CREATE_THREAD_FROZEN,
2085 audio_thread_name IF_PRIO(, PRIORITY_USER_INTERFACE)
2086 IF_COP(, CPU));
2088 queue_enable_queue_send(&audio_queue, &audio_queue_sender_list,
2089 audio_thread_id);
2091 #ifdef PLAYBACK_VOICE
2092 voice_thread_init();
2093 #endif
2095 #ifdef HAVE_CROSSFADE
2096 /* Set crossfade setting for next buffer init which should be about... */
2097 pcmbuf_request_crossfade_enable(global_settings.crossfade);
2098 #endif
2100 /* initialize the buffering system */
2102 buffering_init();
2103 /* ...now! Set up the buffers */
2104 audio_reset_buffer();
2106 int i;
2107 for(i = 0; i < MAX_TRACK; i++)
2109 tracks[i].audio_hid = -1;
2110 tracks[i].id3_hid = -1;
2111 tracks[i].codec_hid = -1;
2112 tracks[i].cuesheet_hid = -1;
2114 #ifdef HAVE_ALBUMART
2115 FOREACH_ALBUMART(i)
2117 int j;
2118 for (j = 0; j < MAX_TRACK; j++)
2120 tracks[j].aa_hid[i] = -1;
2123 #endif
2125 add_event(BUFFER_EVENT_REBUFFER, false, buffering_handle_rebuffer_callback);
2126 add_event(BUFFER_EVENT_FINISHED, false, buffering_handle_finished_callback);
2128 /* Probably safe to say */
2129 audio_is_initialized = true;
2131 sound_settings_apply();
2132 #ifdef HAVE_DISK_STORAGE
2133 audio_set_buffer_margin(global_settings.buffer_margin);
2134 #endif
2136 /* it's safe to let the threads run now */
2137 #ifdef PLAYBACK_VOICE
2138 voice_thread_resume();
2139 #endif
2140 thread_thaw(codec_thread_id);
2141 thread_thaw(audio_thread_id);
2143 } /* audio_init */
2145 bool audio_is_thread_ready(void)
2147 return audio_thread_ready;
2150 size_t audio_get_filebuflen(void)
2152 return filebuflen;
2155 int get_audio_hid()
2157 return CUR_TI->audio_hid;
2160 int *get_codec_hid()
2162 return &tracks[track_ridx].codec_hid;