Add missing cabbiev2 800x480 backdrop
[maemo-rb.git] / apps / playback.c
blob5d91693cad7e5e10516e11b263c64055ad08be16
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
146 static struct albumart_slot {
147 struct dim dim; /* holds width, height of the albumart */
148 int used; /* counter, increments if something uses it */
149 } albumart_slots[MAX_MULTIPLE_AA];
151 #define FOREACH_ALBUMART(i) for(i = 0;i < MAX_MULTIPLE_AA; i++)
152 #endif
155 #define MAX_TRACK 128
156 #define MAX_TRACK_MASK (MAX_TRACK-1)
158 /* Track info structure about songs in the file buffer (A/C-) */
159 static struct track_info {
160 int audio_hid; /* The ID for the track's buffer handle */
161 int id3_hid; /* The ID for the track's metadata handle */
162 int codec_hid; /* The ID for the track's codec handle */
163 #ifdef HAVE_ALBUMART
164 int aa_hid[MAX_MULTIPLE_AA];/* The ID for the track's album art handle */
165 #endif
166 int cuesheet_hid; /* The ID for the track's parsed cueesheet handle */
168 size_t filesize; /* File total length */
170 bool taginfo_ready; /* Is metadata read */
172 } tracks[MAX_TRACK];
174 static volatile int track_ridx = 0; /* Track being decoded (A/C-) */
175 static int track_widx = 0; /* Track being buffered (A) */
176 #define CUR_TI (&tracks[track_ridx]) /* Playing track info pointer (A/C-) */
178 static struct track_info *prev_ti = NULL; /* Pointer to the previously played
179 track */
181 /* Information used only for filling the buffer */
182 /* Playlist steps from playing track to next track to be buffered (A) */
183 static int last_peek_offset = 0;
185 /* Scrobbler support */
186 static unsigned long prev_track_elapsed = 0; /* Previous track elapsed time (C/A-)*/
188 /* Track change controls */
189 bool automatic_skip = false; /* Who initiated in-progress skip? (C/A-) */
190 extern bool track_transition; /* Are we in a track transition? */
191 static bool dir_skip = false; /* Is a directory skip pending? (A) */
192 static bool new_playlist = false; /* Are we starting a new playlist? (A) */
193 static int wps_offset = 0; /* Pending track change offset, to keep WPS responsive (A) */
194 static bool skipped_during_pause = false; /* Do we need to clear the PCM buffer when playback resumes (A) */
196 static bool start_play_g = false; /* Used by audio_load_track to notify
197 audio_finish_load_track about start_play */
199 /* True when a track load is in progress, i.e. audio_load_track() has returned
200 * but audio_finish_load_track() hasn't been called yet. Used to avoid allowing
201 * audio_load_track() to get called twice in a row, which would cause problems.
203 static bool track_load_started = false;
205 #ifdef HAVE_DISK_STORAGE
206 static size_t buffer_margin = 5; /* Buffer margin aka anti-skip buffer (A/C-) */
207 #endif
209 /* Event queues */
210 struct event_queue audio_queue SHAREDBSS_ATTR;
211 struct event_queue codec_queue SHAREDBSS_ATTR;
212 static struct event_queue pcmbuf_queue SHAREDBSS_ATTR;
214 extern struct codec_api ci;
215 extern unsigned int codec_thread_id;
217 /* Multiple threads */
218 /* Set the watermark to trigger buffer fill (A/C) */
219 static void set_filebuf_watermark(void);
221 /* Audio thread */
222 static struct queue_sender_list audio_queue_sender_list SHAREDBSS_ATTR;
223 static long audio_stack[(DEFAULT_STACK_SIZE + 0x1000)/sizeof(long)];
224 static const char audio_thread_name[] = "audio";
226 static void audio_thread(void);
227 static void audio_initiate_track_change(long direction);
228 static bool audio_have_tracks(void);
229 static void audio_reset_buffer(void);
230 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 != sizeof(struct mp3entry))
299 return NULL;
301 return id3;
304 static bool bufreadid3(int handle_id, struct mp3entry *id3out)
306 struct mp3entry *id3 = bufgetid3(handle_id);
308 if (id3)
310 copy_mp3entry(id3out, id3);
311 return true;
314 return false;
317 static bool clear_track_info(struct track_info *track)
319 /* bufclose returns true if the handle is not found, or if it is closed
320 * successfully, so these checks are safe on non-existant handles */
321 if (!track)
322 return false;
324 if (track->codec_hid >= 0) {
325 if (bufclose(track->codec_hid))
326 track->codec_hid = -1;
327 else
328 return false;
331 if (track->id3_hid >= 0) {
332 if (bufclose(track->id3_hid))
333 track->id3_hid = -1;
334 else
335 return false;
338 if (track->audio_hid >= 0) {
339 if (bufclose(track->audio_hid))
340 track->audio_hid = -1;
341 else
342 return false;
345 #ifdef HAVE_ALBUMART
347 int i;
348 FOREACH_ALBUMART(i)
350 if (track->aa_hid[i] >= 0) {
351 if (bufclose(track->aa_hid[i]))
352 track->aa_hid[i] = -1;
353 else
354 return false;
358 #endif
360 if (track->cuesheet_hid >= 0) {
361 if (bufclose(track->cuesheet_hid))
362 track->cuesheet_hid = -1;
363 else
364 return false;
367 track->filesize = 0;
368 track->taginfo_ready = false;
370 return true;
373 /* --- External interfaces --- */
375 /* This sends a stop message and the audio thread will dump all it's
376 subsequenct messages */
377 void audio_hard_stop(void)
379 /* Stop playback */
380 LOGFQUEUE("audio >| audio Q_AUDIO_STOP: 1");
381 queue_send(&audio_queue, Q_AUDIO_STOP, 1);
382 #ifdef PLAYBACK_VOICE
383 voice_stop();
384 #endif
387 bool audio_restore_playback(int type)
389 switch (type)
391 case AUDIO_WANT_PLAYBACK:
392 if (buffer_state != AUDIOBUF_STATE_INITIALIZED)
393 audio_reset_buffer();
394 return true;
395 case AUDIO_WANT_VOICE:
396 if (buffer_state == AUDIOBUF_STATE_TRASHED)
397 audio_reset_buffer();
398 return true;
399 default:
400 return false;
404 unsigned char *audio_get_buffer(bool talk_buf, size_t *buffer_size)
406 unsigned char *buf, *end;
408 if (audio_is_initialized)
410 audio_hard_stop();
412 /* else buffer_state will be AUDIOBUF_STATE_TRASHED at this point */
414 /* Reset the buffering thread so that it doesn't try to use the data */
415 buffering_reset(filebuf, filebuflen);
417 if (buffer_size == NULL)
419 /* Special case for talk_init to use since it already knows it's
420 trashed */
421 buffer_state = AUDIOBUF_STATE_TRASHED;
422 return NULL;
425 if (talk_buf || buffer_state == AUDIOBUF_STATE_TRASHED
426 || !talk_voice_required())
428 logf("get buffer: talk, audio");
429 /* Ok to use everything from audiobuf to audiobufend - voice is loaded,
430 the talk buffer is not needed because voice isn't being used, or
431 could be AUDIOBUF_STATE_TRASHED already. If state is
432 AUDIOBUF_STATE_VOICED_ONLY, no problem as long as memory isn't written
433 without the caller knowing what's going on. Changing certain settings
434 may move it to a worse condition but the memory in use by something
435 else will remain undisturbed.
437 if (buffer_state != AUDIOBUF_STATE_TRASHED)
439 talk_buffer_steal();
440 buffer_state = AUDIOBUF_STATE_TRASHED;
443 buf = audiobuf;
444 end = audiobufend;
446 else
448 /* Safe to just return this if already AUDIOBUF_STATE_VOICED_ONLY or
449 still AUDIOBUF_STATE_INITIALIZED */
450 /* Skip talk buffer and move pcm buffer to end to maximize available
451 contiguous memory - no audio running means voice will not need the
452 swap space */
453 logf("get buffer: audio");
454 buf = audiobuf + talk_get_bufsize();
455 end = audiobufend - pcmbuf_init(audiobufend);
456 buffer_state = AUDIOBUF_STATE_VOICED_ONLY;
459 *buffer_size = end - buf;
461 return buf;
464 bool audio_buffer_state_trashed(void)
466 return buffer_state == AUDIOBUF_STATE_TRASHED;
469 #ifdef HAVE_RECORDING
470 unsigned char *audio_get_recording_buffer(size_t *buffer_size)
472 /* Stop audio, voice and obtain all available buffer space */
473 audio_hard_stop();
474 talk_buffer_steal();
476 unsigned char *end = audiobufend;
477 buffer_state = AUDIOBUF_STATE_TRASHED;
478 *buffer_size = end - audiobuf;
480 return (unsigned char *)audiobuf;
483 bool audio_load_encoder(int afmt)
485 #if (CONFIG_PLATFORM & PLATFORM_NATIVE)
486 const char *enc_fn = get_codec_filename(afmt | CODEC_TYPE_ENCODER);
487 if (!enc_fn)
488 return false;
490 audio_remove_encoder();
491 ci.enc_codec_loaded = 0; /* clear any previous error condition */
493 LOGFQUEUE("codec > Q_ENCODER_LOAD_DISK");
494 queue_post(&codec_queue, Q_ENCODER_LOAD_DISK, (intptr_t)enc_fn);
496 while (ci.enc_codec_loaded == 0)
497 yield();
499 logf("codec loaded: %d", ci.enc_codec_loaded);
501 return ci.enc_codec_loaded > 0;
502 #else
503 (void)afmt;
504 return true;
505 #endif
506 } /* audio_load_encoder */
508 void audio_remove_encoder(void)
510 #if (CONFIG_PLATFORM & PLATFORM_NATIVE)
511 /* force encoder codec unload (if currently loaded) */
512 if (ci.enc_codec_loaded <= 0)
513 return;
515 ci.stop_encoder = true;
516 while (ci.enc_codec_loaded > 0)
517 yield();
518 #endif
519 } /* audio_remove_encoder */
521 #endif /* HAVE_RECORDING */
524 struct mp3entry* audio_current_track(void)
526 const char *filename;
527 struct playlist_track_info trackinfo;
528 int cur_idx;
529 int offset = ci.new_track + wps_offset;
530 struct mp3entry *write_id3;
532 cur_idx = (track_ridx + offset) & MAX_TRACK_MASK;
534 if (cur_idx == track_ridx && *thistrack_id3->path)
536 /* The usual case */
537 if (tracks[cur_idx].cuesheet_hid >= 0 && !thistrack_id3->cuesheet)
539 bufread(tracks[cur_idx].cuesheet_hid, sizeof(struct cuesheet), curr_cue);
540 thistrack_id3->cuesheet = curr_cue;
542 return thistrack_id3;
544 else if (automatic_skip && offset == -1 && *othertrack_id3->path)
546 /* We're in a track transition. The codec has moved on to the next track,
547 but the audio being played is still the same (now previous) track.
548 othertrack_id3.elapsed is being updated in an ISR by
549 codec_pcmbuf_position_callback */
550 if (tracks[cur_idx].cuesheet_hid >= 0 && !thistrack_id3->cuesheet)
552 bufread(tracks[cur_idx].cuesheet_hid, sizeof(struct cuesheet), curr_cue);
553 othertrack_id3->cuesheet = curr_cue;
555 return othertrack_id3;
558 if (offset != 0)
560 /* Codec may be using thistrack_id3, so it must not be overwritten.
561 If this is a manual skip, othertrack_id3 will become
562 thistrack_id3 in audio_check_new_track().
563 FIXME: If this is an automatic skip, it probably means multiple
564 short tracks fit in the PCM buffer. Overwriting othertrack_id3
565 can lead to an incorrect value later.
566 Note that othertrack_id3 may also be used for next track.
568 write_id3 = othertrack_id3;
570 else
572 write_id3 = thistrack_id3;
575 if (tracks[cur_idx].id3_hid >= 0)
577 /* The current track's info has been buffered but not read yet, so get it */
578 if (bufreadid3(tracks[cur_idx].id3_hid, write_id3))
579 return write_id3;
582 /* We didn't find the ID3 metadata, so we fill temp_id3 with the little info
583 we have and return that. */
585 memset(write_id3, 0, sizeof(struct mp3entry));
587 playlist_get_track_info(NULL, playlist_next(0)+wps_offset, &trackinfo);
588 filename = trackinfo.filename;
589 if (!filename)
590 filename = "No file!";
592 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
593 if (tagcache_fill_tags(write_id3, filename))
594 return write_id3;
595 #endif
597 strlcpy(write_id3->path, filename, sizeof(write_id3->path));
598 write_id3->title = strrchr(write_id3->path, '/');
599 if (!write_id3->title)
600 write_id3->title = &write_id3->path[0];
601 else
602 write_id3->title++;
604 return write_id3;
607 struct mp3entry* audio_next_track(void)
609 int next_idx;
610 int offset = ci.new_track + wps_offset;
612 if (!audio_have_tracks())
613 return NULL;
615 if (wps_offset == -1 && *thistrack_id3->path)
617 /* We're in a track transition. The next track for the WPS is the one
618 currently being decoded. */
619 return thistrack_id3;
622 next_idx = (track_ridx + offset + 1) & MAX_TRACK_MASK;
624 if (tracks[next_idx].id3_hid >= 0)
626 if (bufreadid3(tracks[next_idx].id3_hid, othertrack_id3))
627 return othertrack_id3;
628 else
629 return NULL;
632 if (next_idx == track_widx)
634 /* The next track hasn't been buffered yet, so we return the static
635 version of its metadata. */
636 return &unbuffered_id3;
639 return NULL;
642 /* gets a copy of the id3 data */
643 bool audio_peek_track(struct mp3entry* id3, int offset)
645 int next_idx;
646 int new_offset = ci.new_track + wps_offset + offset;
648 if (!audio_have_tracks())
649 return false;
650 next_idx = (track_ridx + new_offset) & MAX_TRACK_MASK;
652 if (tracks[next_idx].id3_hid >= 0)
653 return bufreadid3(tracks[next_idx].id3_hid, id3);
655 return false;
658 #ifdef HAVE_ALBUMART
660 int playback_current_aa_hid(int slot)
662 if (slot < 0)
663 return -1;
664 int cur_idx;
665 int offset = ci.new_track + wps_offset;
667 cur_idx = track_ridx + offset;
668 cur_idx &= MAX_TRACK_MASK;
669 return tracks[cur_idx].aa_hid[slot];
672 int playback_claim_aa_slot(struct dim *dim)
674 int i;
676 /* first try to find a slot already having the size to reuse it
677 * since we don't want albumart of the same size buffered multiple times */
678 FOREACH_ALBUMART(i)
680 struct albumart_slot *slot = &albumart_slots[i];
681 if (slot->dim.width == dim->width
682 && slot->dim.height == dim->height)
684 slot->used++;
685 return i;
688 /* size is new, find a free slot */
689 FOREACH_ALBUMART(i)
691 if (!albumart_slots[i].used)
693 albumart_slots[i].used++;
694 albumart_slots[i].dim = *dim;
695 return i;
698 /* sorry, no free slot */
699 return -1;
702 void playback_release_aa_slot(int slot)
704 /* invalidate the albumart_slot */
705 struct albumart_slot *aa_slot = &albumart_slots[slot];
707 if (aa_slot->used > 0)
708 aa_slot->used--;
711 #endif
712 void audio_play(long offset)
714 logf("audio_play");
716 #ifdef PLAYBACK_VOICE
717 /* Truncate any existing voice output so we don't have spelling
718 * etc. over the first part of the played track */
719 talk_force_shutup();
720 #endif
722 /* Start playback */
723 LOGFQUEUE("audio >| audio Q_AUDIO_PLAY: %ld", offset);
724 /* Don't return until playback has actually started */
725 queue_send(&audio_queue, Q_AUDIO_PLAY, offset);
728 void audio_stop(void)
730 /* Stop playback */
731 LOGFQUEUE("audio >| audio Q_AUDIO_STOP");
732 /* Don't return until playback has actually stopped */
733 queue_send(&audio_queue, Q_AUDIO_STOP, 0);
736 void audio_pause(void)
738 LOGFQUEUE("audio >| audio Q_AUDIO_PAUSE");
739 /* Don't return until playback has actually paused */
740 queue_send(&audio_queue, Q_AUDIO_PAUSE, true);
743 void audio_resume(void)
745 LOGFQUEUE("audio >| audio Q_AUDIO_PAUSE resume");
746 /* Don't return until playback has actually resumed */
747 queue_send(&audio_queue, Q_AUDIO_PAUSE, false);
750 void audio_skip(int direction)
752 if (playlist_check(ci.new_track + wps_offset + direction))
754 if (global_settings.beep)
755 pcmbuf_beep(2000, 100, 2500*global_settings.beep);
757 LOGFQUEUE("audio > audio Q_AUDIO_SKIP %d", direction);
758 queue_post(&audio_queue, Q_AUDIO_SKIP, direction);
759 /* Update wps while our message travels inside deep playback queues. */
760 wps_offset += direction;
762 else
764 /* No more tracks. */
765 if (global_settings.beep)
766 pcmbuf_beep(1000, 100, 1500*global_settings.beep);
770 void audio_next(void)
772 audio_skip(1);
775 void audio_prev(void)
777 audio_skip(-1);
780 void audio_next_dir(void)
782 LOGFQUEUE("audio > audio Q_AUDIO_DIR_SKIP 1");
783 queue_post(&audio_queue, Q_AUDIO_DIR_SKIP, 1);
786 void audio_prev_dir(void)
788 LOGFQUEUE("audio > audio Q_AUDIO_DIR_SKIP -1");
789 queue_post(&audio_queue, Q_AUDIO_DIR_SKIP, -1);
792 void audio_pre_ff_rewind(void)
794 LOGFQUEUE("audio > audio Q_AUDIO_PRE_FF_REWIND");
795 queue_post(&audio_queue, Q_AUDIO_PRE_FF_REWIND, 0);
798 void audio_ff_rewind(long newpos)
800 LOGFQUEUE("audio > audio Q_AUDIO_FF_REWIND");
801 queue_post(&audio_queue, Q_AUDIO_FF_REWIND, newpos);
804 void audio_flush_and_reload_tracks(void)
806 LOGFQUEUE("audio > audio Q_AUDIO_FLUSH");
807 queue_post(&audio_queue, Q_AUDIO_FLUSH, 0);
810 void audio_error_clear(void)
812 #ifdef AUDIO_HAVE_RECORDING
813 pcm_rec_error_clear();
814 #endif
817 int audio_status(void)
819 int ret = 0;
821 if (playing)
822 ret |= AUDIO_STATUS_PLAY;
824 if (paused)
825 ret |= AUDIO_STATUS_PAUSE;
827 #ifdef HAVE_RECORDING
828 /* Do this here for constitency with mpeg.c version */
829 /* FIXME: pcm_rec_status() is deprecated */
830 ret |= pcm_rec_status();
831 #endif
833 return ret;
836 int audio_get_file_pos(void)
838 return 0;
841 #ifdef HAVE_DISK_STORAGE
842 void audio_set_buffer_margin(int setting)
844 static const unsigned short lookup[] = {5, 15, 30, 60, 120, 180, 300, 600};
845 buffer_margin = lookup[setting];
846 logf("buffer margin: %ld", (long)buffer_margin);
847 set_filebuf_watermark();
849 #endif
851 #ifdef HAVE_CROSSFADE
852 /* Take necessary steps to enable or disable the crossfade setting */
853 void audio_set_crossfade(int enable)
855 size_t offset;
856 bool was_playing;
857 size_t size;
859 /* Tell it the next setting to use */
860 pcmbuf_request_crossfade_enable(enable);
862 /* Return if size hasn't changed or this is too early to determine
863 which in the second case there's no way we could be playing
864 anything at all */
865 if (pcmbuf_is_same_size()) return;
867 offset = 0;
868 was_playing = playing;
870 /* Playback has to be stopped before changing the buffer size */
871 if (was_playing)
873 /* Store the track resume position */
874 offset = thistrack_id3->offset;
877 /* Blast it - audio buffer will have to be setup again next time
878 something plays */
879 audio_get_buffer(true, &size);
881 /* Restart playback if audio was running previously */
882 if (was_playing)
883 audio_play(offset);
885 #endif
887 /* --- Routines called from multiple threads --- */
889 static void set_filebuf_watermark(void)
891 if (!filebuf)
892 return; /* Audio buffers not yet set up */
894 #ifdef HAVE_DISK_STORAGE
895 int seconds;
896 int spinup = ata_spinup_time();
897 if (spinup)
898 seconds = (spinup / HZ) + 1;
899 else
900 seconds = 5;
902 seconds += buffer_margin;
903 #else
904 /* flash storage */
905 int seconds = 1;
906 #endif
908 /* bitrate of last track in buffer dictates watermark */
909 struct mp3entry* id3 = NULL;
910 if (tracks[track_widx].taginfo_ready)
911 id3 = bufgetid3(tracks[track_widx].id3_hid);
912 else
913 id3 = bufgetid3(tracks[track_widx-1].id3_hid);
914 if (!id3) {
915 logf("fwmark: No id3 for last track (r%d/w%d), aborting!", track_ridx, track_widx);
916 return;
918 size_t bytes = id3->bitrate * (1000/8) * seconds;
919 buf_set_watermark(bytes);
920 logf("fwmark: %d", bytes);
923 /* --- Buffering callbacks --- */
925 static void buffering_low_buffer_callback(void *data)
927 (void)data;
928 logf("low buffer callback");
930 if (filling == STATE_FULL || filling == STATE_END_OF_PLAYLIST) {
931 /* force a refill */
932 LOGFQUEUE("buffering > audio Q_AUDIO_FILL_BUFFER");
933 queue_post(&audio_queue, Q_AUDIO_FILL_BUFFER, 0);
937 static void buffering_handle_rebuffer_callback(void *data)
939 (void)data;
940 LOGFQUEUE("audio >| audio Q_AUDIO_FLUSH");
941 queue_post(&audio_queue, Q_AUDIO_FLUSH, 0);
944 static void buffering_handle_finished_callback(void *data)
946 logf("handle %d finished buffering", *(int*)data);
947 int hid = (*(int*)data);
949 if (hid == tracks[track_widx].id3_hid)
951 int offset = ci.new_track + wps_offset;
952 int next_idx = (track_ridx + offset + 1) & MAX_TRACK_MASK;
953 /* The metadata handle for the last loaded track has been buffered.
954 We can ask the audio thread to load the rest of the track's data. */
955 LOGFQUEUE("audio >| audio Q_AUDIO_FINISH_LOAD");
956 queue_post(&audio_queue, Q_AUDIO_FINISH_LOAD, 0);
957 if (tracks[next_idx].id3_hid == hid)
958 send_event(PLAYBACK_EVENT_NEXTTRACKID3_AVAILABLE, NULL);
960 else
962 /* This is most likely an audio handle, so we strip the useless
963 trailing tags that are left. */
964 strip_tags(hid);
966 if (hid == tracks[track_widx-1].audio_hid
967 && filling == STATE_END_OF_PLAYLIST)
969 /* This was the last track in the playlist.
970 We now have all the data we need. */
971 logf("last track finished buffering");
972 filling = STATE_FINISHED;
978 /* --- Audio thread --- */
980 static bool audio_have_tracks(void)
982 return (audio_track_count() != 0);
985 static int audio_free_track_count(void)
987 /* Used tracks + free tracks adds up to MAX_TRACK - 1 */
988 return MAX_TRACK - 1 - audio_track_count();
991 int audio_track_count(void)
993 /* Calculate difference from track_ridx to track_widx
994 * taking into account a possible wrap-around. */
995 return (MAX_TRACK + track_widx - track_ridx) & MAX_TRACK_MASK;
998 long audio_filebufused(void)
1000 return (long) buf_used();
1003 /* Update track info after successful a codec track change */
1004 static void audio_update_trackinfo(void)
1006 bool resume = false;
1008 /* Load the curent track's metadata into curtrack_id3 */
1009 if (CUR_TI->id3_hid >= 0)
1010 bufreadid3(CUR_TI->id3_hid, thistrack_id3);
1012 /* Reset current position */
1013 thistrack_id3->elapsed = 0;
1015 #ifdef HAVE_TAGCACHE
1016 /* Ignoring resume position for automatic track change if so configured */
1017 resume = global_settings.autoresume_enable &&
1018 (!automatic_skip /* Resume all manually selected tracks */
1019 || global_settings.autoresume_automatic == AUTORESUME_NEXTTRACK_ALWAYS
1020 || (global_settings.autoresume_automatic != AUTORESUME_NEXTTRACK_NEVER
1021 /* Not never resume? */
1022 && autoresumable(thistrack_id3))); /* Pass Resume filter? */
1023 #endif
1025 if (!resume)
1027 thistrack_id3->offset = 0;
1030 logf("audio_update_trackinfo: Set offset for %s to %lX\n",
1031 thistrack_id3->title, thistrack_id3->offset);
1033 /* Update the codec API */
1034 ci.filesize = CUR_TI->filesize;
1035 ci.id3 = thistrack_id3;
1036 ci.curpos = 0;
1037 ci.taginfo_ready = &CUR_TI->taginfo_ready;
1040 /* Clear tracks between write and read, non inclusive */
1041 static void audio_clear_track_entries(void)
1043 int cur_idx = track_widx;
1045 logf("Clearing tracks: r%d/w%d", track_ridx, track_widx);
1047 /* Loop over all tracks from write-to-read */
1048 while (1)
1050 cur_idx = (cur_idx + 1) & MAX_TRACK_MASK;
1052 if (cur_idx == track_ridx)
1053 break;
1055 clear_track_info(&tracks[cur_idx]);
1059 /* Clear all tracks */
1060 static bool audio_release_tracks(void)
1062 int i, cur_idx;
1064 logf("releasing all tracks");
1066 for(i = 0; i < MAX_TRACK; i++)
1068 cur_idx = (track_ridx + i) & MAX_TRACK_MASK;
1069 if (!clear_track_info(&tracks[cur_idx]))
1070 return false;
1073 return true;
1076 static bool audio_loadcodec(bool start_play)
1078 int prev_track, hid;
1079 char codec_path[MAX_PATH]; /* Full path to codec */
1080 const struct mp3entry *id3, *prev_id3;
1082 if (tracks[track_widx].id3_hid < 0) {
1083 return false;
1086 id3 = bufgetid3(tracks[track_widx].id3_hid);
1087 if (!id3)
1088 return false;
1090 const char *codec_fn = get_codec_filename(id3->codectype);
1091 if (codec_fn == NULL)
1092 return false;
1094 tracks[track_widx].codec_hid = -1;
1096 if (start_play)
1098 /* Load the codec directly from disk and save some memory. */
1099 track_ridx = track_widx;
1100 ci.filesize = CUR_TI->filesize;
1101 ci.id3 = thistrack_id3;
1102 ci.taginfo_ready = &CUR_TI->taginfo_ready;
1103 ci.curpos = 0;
1104 LOGFQUEUE("codec > codec Q_CODEC_LOAD_DISK");
1105 queue_post(&codec_queue, Q_CODEC_LOAD_DISK, (intptr_t)codec_fn);
1106 return true;
1108 else
1110 /* If we already have another track than this one buffered */
1111 if (track_widx != track_ridx)
1113 prev_track = (track_widx - 1) & MAX_TRACK_MASK;
1115 id3 = bufgetid3(tracks[track_widx].id3_hid);
1116 prev_id3 = bufgetid3(tracks[prev_track].id3_hid);
1118 /* If the previous codec is the same as this one, there is no need
1119 * to put another copy of it on the file buffer */
1120 if (id3 && prev_id3 &&
1121 get_codec_base_type(id3->codectype) ==
1122 get_codec_base_type(prev_id3->codectype)
1123 && audio_codec_loaded)
1125 logf("Reusing prev. codec");
1126 return true;
1131 codec_get_full_path(codec_path, codec_fn);
1133 hid = tracks[track_widx].codec_hid = bufopen(codec_path, 0, TYPE_CODEC, NULL);
1135 /* not an error if codec load it supported, will load it from disk
1136 * application builds don't support it
1138 if (hid < 0 && hid != ERR_UNSUPPORTED_TYPE)
1139 return false;
1141 if (hid > 0)
1142 logf("Loaded codec");
1143 else
1144 logf("Buffering codec unsupported, load later from disk");
1146 return true;
1149 /* Load metadata for the next track (with bufopen). The rest of the track
1150 loading will be handled by audio_finish_load_track once the metadata has been
1151 actually loaded by the buffering thread. */
1152 static bool audio_load_track(size_t offset, bool start_play)
1154 char name_buf[MAX_PATH + 1];
1155 const char *trackname;
1156 int fd = -1;
1158 if (track_load_started) {
1159 /* There is already a track load in progress, so track_widx hasn't been
1160 incremented yet. Loading another track would overwrite the one that
1161 hasn't finished loading. */
1162 logf("audio_load_track(): a track load is already in progress");
1163 return false;
1166 start_play_g = start_play; /* will be read by audio_finish_load_track */
1168 /* Stop buffer filling if there is no free track entries.
1169 Don't fill up the last track entry (we wan't to store next track
1170 metadata there). */
1171 if (!audio_free_track_count())
1173 logf("No free tracks");
1174 return false;
1177 last_peek_offset++;
1178 tracks[track_widx].taginfo_ready = false;
1180 logf("Buffering track: r%d/w%d", track_ridx, track_widx);
1181 /* Get track name from current playlist read position. */
1182 while ((trackname = playlist_peek(last_peek_offset, name_buf,
1183 sizeof(name_buf))) != NULL)
1185 /* Handle broken playlists. */
1186 fd = open(trackname, O_RDONLY);
1187 if (fd < 0)
1189 logf("Open failed");
1190 /* Skip invalid entry from playlist. */
1191 playlist_skip_entry(NULL, last_peek_offset);
1193 else
1194 break;
1197 if (!trackname)
1199 logf("End-of-playlist");
1200 memset(&unbuffered_id3, 0, sizeof(struct mp3entry));
1201 filling = STATE_END_OF_PLAYLIST;
1203 if (thistrack_id3->length == 0 && thistrack_id3->filesize == 0)
1205 /* Stop playback if no valid track was found. */
1206 audio_stop_playback();
1209 return false;
1212 tracks[track_widx].filesize = filesize(fd);
1214 if (offset > tracks[track_widx].filesize)
1215 offset = 0;
1217 /* Set default values */
1218 if (start_play)
1220 buf_set_watermark(filebuflen/2);
1221 dsp_configure(ci.dsp, DSP_RESET, 0);
1222 playlist_update_resume_info(audio_current_track());
1225 /* Get track metadata if we don't already have it. */
1226 if (tracks[track_widx].id3_hid < 0)
1228 tracks[track_widx].id3_hid = bufopen(trackname, 0, TYPE_ID3, NULL);
1230 if (tracks[track_widx].id3_hid < 0)
1232 /* Buffer is full. */
1233 get_metadata(&unbuffered_id3, fd, trackname);
1234 last_peek_offset--;
1235 close(fd);
1236 logf("buffer is full for now (get metadata)");
1237 filling = STATE_FULL;
1238 return false;
1241 if (track_widx == track_ridx)
1243 /* TODO: Superfluos buffering call? */
1244 buf_request_buffer_handle(tracks[track_widx].id3_hid);
1245 if (bufreadid3(tracks[track_widx].id3_hid, thistrack_id3))
1247 thistrack_id3->offset = offset;
1248 logf("audio_load_track: set offset for %s to %lX\n",
1249 thistrack_id3->title,
1250 offset);
1252 else
1253 memset(thistrack_id3, 0, sizeof(struct mp3entry));
1256 if (start_play)
1258 playlist_update_resume_info(audio_current_track());
1262 close(fd);
1263 track_load_started = true; /* Remember that we've started loading a track */
1264 return true;
1267 #ifdef HAVE_ALBUMART
1268 /* Load any album art for the file */
1269 static void audio_load_albumart(struct mp3entry *track_id3)
1271 int i;
1273 FOREACH_ALBUMART(i)
1275 struct bufopen_bitmap_data user_data;
1276 int hid = ERR_HANDLE_NOT_FOUND;
1278 /* albumart_slots may change during a yield of bufopen,
1279 * but that's no problem */
1280 if (tracks[track_widx].aa_hid[i] >= 0 || !albumart_slots[i].used)
1281 continue;
1283 memset(&user_data, 0, sizeof(user_data));
1284 user_data.dim = &(albumart_slots[i].dim);
1286 /* we can only decode jpeg for embedded AA */
1287 if (track_id3->embed_albumart && track_id3->albumart.type == AA_TYPE_JPG)
1289 user_data.embedded_albumart = &(track_id3->albumart);
1290 hid = bufopen(track_id3->path, 0, TYPE_BITMAP, &user_data);
1293 if (hid < 0 && hid != ERR_BUFFER_FULL)
1295 /* no embedded AA or it couldn't be loaded, try other sources */
1296 char path[MAX_PATH];
1298 if (find_albumart(track_id3, path, sizeof(path),
1299 &(albumart_slots[i].dim)))
1301 user_data.embedded_albumart = NULL;
1302 hid = bufopen(path, 0, TYPE_BITMAP, &user_data);
1306 if (hid == ERR_BUFFER_FULL)
1308 filling = STATE_FULL;
1309 logf("buffer is full for now (get album art)");
1311 else if (hid < 0)
1313 logf("Album art loading failed");
1316 tracks[track_widx].aa_hid[i] = hid;
1319 #endif
1321 /* Second part of the track loading: We now have the metadata available, so we
1322 can load the codec, the album art and finally the audio data.
1323 This is called on the audio thread after the buffering thread calls the
1324 buffering_handle_finished_callback callback. */
1325 static void audio_finish_load_track(void)
1327 size_t file_offset = 0;
1328 size_t offset = 0;
1329 bool start_play = start_play_g;
1331 track_load_started = false;
1333 if (tracks[track_widx].id3_hid < 0) {
1334 logf("No metadata");
1335 return;
1338 struct mp3entry *track_id3;
1340 if (track_widx == track_ridx)
1341 track_id3 = thistrack_id3;
1342 else
1343 track_id3 = bufgetid3(tracks[track_widx].id3_hid);
1345 if (track_id3->length == 0 && track_id3->filesize == 0)
1347 logf("audio_finish_load_track: invalid metadata");
1349 /* Invalid metadata */
1350 bufclose(tracks[track_widx].id3_hid);
1351 tracks[track_widx].id3_hid = -1;
1353 /* Skip invalid entry from playlist. */
1354 playlist_skip_entry(NULL, last_peek_offset--);
1356 /* load next track */
1357 LOGFQUEUE("audio > audio Q_AUDIO_FILL_BUFFER %d", (int)start_play);
1358 queue_post(&audio_queue, Q_AUDIO_FILL_BUFFER, start_play);
1360 return;
1362 /* Try to load a cuesheet for the track */
1363 if (curr_cue)
1365 char cuepath[MAX_PATH];
1366 if (look_for_cuesheet_file(track_id3->path, cuepath))
1368 void *temp;
1369 tracks[track_widx].cuesheet_hid =
1370 bufalloc(NULL, sizeof(struct cuesheet), TYPE_CUESHEET);
1371 if (tracks[track_widx].cuesheet_hid >= 0)
1373 bufgetdata(tracks[track_widx].cuesheet_hid,
1374 sizeof(struct cuesheet), &temp);
1375 struct cuesheet *cuesheet = (struct cuesheet*)temp;
1376 if (!parse_cuesheet(cuepath, cuesheet))
1378 bufclose(tracks[track_widx].cuesheet_hid);
1379 track_id3->cuesheet = NULL;
1385 #ifdef HAVE_ALBUMART
1386 audio_load_albumart(track_id3);
1387 #endif
1389 /* Load the codec. */
1390 if (!audio_loadcodec(start_play))
1392 if (tracks[track_widx].codec_hid == ERR_BUFFER_FULL)
1394 /* No space for codec on buffer, not an error */
1395 filling = STATE_FULL;
1396 return;
1399 /* This is an error condition, either no codec was found, or reading
1400 * the codec file failed part way through, either way, skip the track */
1401 /* FIXME: We should not use splashf from audio thread! */
1402 splashf(HZ*2, "No codec for: %s", track_id3->path);
1403 /* Skip invalid entry from playlist. */
1404 playlist_skip_entry(NULL, last_peek_offset);
1405 return;
1408 track_id3->elapsed = 0;
1409 offset = track_id3->offset;
1410 size_t resume_rewind = (global_settings.resume_rewind *
1411 track_id3->bitrate * 1000) / 8;
1413 if (offset < resume_rewind)
1415 offset = 0;
1417 else
1419 offset -= resume_rewind;
1422 enum data_type type = TYPE_PACKET_AUDIO;
1424 switch (track_id3->codectype) {
1425 case AFMT_MPA_L1:
1426 case AFMT_MPA_L2:
1427 case AFMT_MPA_L3:
1428 if (offset > 0) {
1429 file_offset = offset;
1431 break;
1433 case AFMT_WAVPACK:
1434 if (offset > 0) {
1435 file_offset = offset;
1436 track_id3->elapsed = track_id3->length / 2;
1438 break;
1440 case AFMT_NSF:
1441 case AFMT_SPC:
1442 case AFMT_SID:
1443 logf("Loading atomic %d",track_id3->codectype);
1444 type = TYPE_ATOMIC_AUDIO;
1445 break;
1447 default:
1448 /* no special treatment needed */
1449 break;
1452 track_id3->offset = offset;
1454 logf("load track: %s", track_id3->path);
1456 if (file_offset > AUDIO_REBUFFER_GUESS_SIZE)
1457 file_offset -= AUDIO_REBUFFER_GUESS_SIZE;
1458 else if (track_id3->first_frame_offset)
1459 file_offset = track_id3->first_frame_offset;
1460 else
1461 file_offset = 0;
1463 tracks[track_widx].audio_hid = bufopen(track_id3->path, file_offset, type,
1464 NULL);
1466 /* No space left, not an error */
1467 if (tracks[track_widx].audio_hid == ERR_BUFFER_FULL)
1469 filling = STATE_FULL;
1470 logf("buffer is full for now (load audio)");
1471 return;
1473 else if (tracks[track_widx].audio_hid < 0)
1475 /* another error, do not continue either */
1476 logf("Could not add audio data handle");
1477 return;
1480 /* All required data is now available for the codec -- unless the
1481 autoresume feature is in effect. In the latter case, the codec
1482 must wait until after PLAYBACK_EVENT_TRACK_BUFFER, which may
1483 generate a resume position. */
1484 #ifdef HAVE_TAGCACHE
1485 if (! global_settings.autoresume_enable)
1486 #endif
1487 tracks[track_widx].taginfo_ready = true;
1489 if (start_play)
1491 ci.curpos=file_offset;
1492 buf_request_buffer_handle(tracks[track_widx].audio_hid);
1495 send_event(PLAYBACK_EVENT_TRACK_BUFFER, track_id3);
1497 #ifdef HAVE_TAGCACHE
1498 /* In case the autoresume feature has been enabled, finally all
1499 required data is available for the codec. */
1500 if (global_settings.autoresume_enable)
1501 tracks[track_widx].taginfo_ready = true;
1502 #endif
1504 track_widx = (track_widx + 1) & MAX_TRACK_MASK;
1506 /* load next track */
1507 LOGFQUEUE("audio > audio Q_AUDIO_FILL_BUFFER");
1508 queue_post(&audio_queue, Q_AUDIO_FILL_BUFFER, 0);
1510 return;
1513 static void audio_fill_file_buffer(bool start_play, size_t offset)
1515 trigger_cpu_boost();
1517 /* No need to rebuffer if there are track skips pending,
1518 * however don't cancel buffering on skipping while filling. */
1519 if (ci.new_track != 0 && filling != STATE_FILLING)
1520 return;
1521 filling = STATE_FILLING;
1523 /* Must reset the buffer before use if trashed or voice only - voice
1524 file size shouldn't have changed so we can go straight from
1525 AUDIOBUF_STATE_VOICED_ONLY to AUDIOBUF_STATE_INITIALIZED */
1526 if (buffer_state != AUDIOBUF_STATE_INITIALIZED)
1527 audio_reset_buffer();
1529 logf("Starting buffer fill");
1531 if (!start_play)
1532 audio_clear_track_entries();
1534 /* Save the current resume position once. */
1535 playlist_update_resume_info(audio_current_track());
1537 audio_load_track(offset, start_play);
1540 static void audio_rebuffer(void)
1542 logf("Forcing rebuffer");
1544 clear_track_info(CUR_TI);
1546 /* Reset track pointers */
1547 track_widx = track_ridx;
1548 audio_clear_track_entries();
1550 /* Reset a possibly interrupted track load */
1551 track_load_started = false;
1553 /* Fill the buffer */
1554 last_peek_offset = -1;
1555 ci.curpos = 0;
1557 if (!CUR_TI->taginfo_ready)
1558 memset(thistrack_id3, 0, sizeof(struct mp3entry));
1560 audio_fill_file_buffer(false, 0);
1563 /* Called on request from the codec to get a new track. This is the codec part
1564 of the track transition. */
1565 static int audio_check_new_track(void)
1567 int track_count = audio_track_count();
1568 int old_track_ridx = track_ridx;
1569 int i, idx;
1570 bool forward;
1571 struct mp3entry *temp = thistrack_id3;
1573 /* Now it's good time to send track finish events. */
1574 send_event(PLAYBACK_EVENT_TRACK_FINISH, thistrack_id3);
1575 /* swap the mp3entry pointers */
1576 thistrack_id3 = othertrack_id3;
1577 othertrack_id3 = temp;
1578 ci.id3 = thistrack_id3;
1579 memset(thistrack_id3, 0, sizeof(struct mp3entry));
1581 if (dir_skip)
1583 dir_skip = false;
1584 /* regardless of the return value we need to rebuffer.
1585 if it fails the old playlist will resume, else the
1586 next dir will start playing */
1587 playlist_next_dir(ci.new_track);
1588 ci.new_track = 0;
1589 audio_rebuffer();
1590 goto skip_done;
1593 if (new_playlist)
1594 ci.new_track = 0;
1596 /* If the playlist isn't that big */
1597 if (automatic_skip)
1599 while (!playlist_check(ci.new_track))
1601 if (ci.new_track >= 0)
1603 LOGFQUEUE("audio >|= codec Q_CODEC_REQUEST_FAILED");
1604 return Q_CODEC_REQUEST_FAILED;
1606 ci.new_track++;
1610 /* Update the playlist */
1611 last_peek_offset -= ci.new_track;
1613 if (playlist_next(ci.new_track) < 0)
1615 LOGFQUEUE("audio >|= codec Q_CODEC_REQUEST_FAILED");
1616 return Q_CODEC_REQUEST_FAILED;
1619 if (new_playlist)
1621 ci.new_track = 1;
1622 new_playlist = false;
1625 /* Save a pointer to the old track to allow later clearing */
1626 prev_ti = CUR_TI;
1628 for (i = 0; i < ci.new_track; i++)
1630 idx = (track_ridx + i) & MAX_TRACK_MASK;
1631 struct mp3entry *id3 = bufgetid3(tracks[idx].id3_hid);
1632 ssize_t offset = buf_handle_offset(tracks[idx].audio_hid);
1633 if (!id3 || offset < 0 || (unsigned)offset > id3->first_frame_offset)
1635 /* We don't have all the audio data for that track, so clear it,
1636 but keep the metadata. */
1637 if (tracks[idx].audio_hid >= 0 && bufclose(tracks[idx].audio_hid))
1639 tracks[idx].audio_hid = -1;
1640 tracks[idx].filesize = 0;
1645 /* Move to the new track */
1646 track_ridx = (track_ridx + ci.new_track) & MAX_TRACK_MASK;
1647 buf_set_base_handle(CUR_TI->audio_hid);
1650 if (automatic_skip)
1652 wps_offset = -ci.new_track;
1655 /* If it is not safe to even skip this many track entries */
1656 if (ci.new_track >= track_count || ci.new_track <= track_count - MAX_TRACK)
1658 ci.new_track = 0;
1659 audio_rebuffer();
1660 goto skip_done;
1663 forward = ci.new_track > 0;
1664 ci.new_track = 0;
1666 /* If the target track is clearly not in memory */
1667 if (CUR_TI->filesize == 0 || !CUR_TI->taginfo_ready)
1669 audio_rebuffer();
1670 goto skip_done;
1673 /* When skipping backwards, it is possible that we've found a track that's
1674 * buffered, but which is around the track-wrap and therefore not the track
1675 * we are looking for */
1676 if (!forward)
1678 int cur_idx = track_ridx;
1679 bool taginfo_ready = true;
1680 /* We've wrapped the buffer backwards if new > old */
1681 bool wrap = track_ridx > old_track_ridx;
1683 while (1)
1685 cur_idx = (cur_idx + 1) & MAX_TRACK_MASK;
1687 /* if we've advanced past the wrap when cur_idx is zeroed */
1688 if (!cur_idx)
1689 wrap = false;
1691 /* if we aren't still on the wrap and we've caught the old track */
1692 if (!(wrap || cur_idx < old_track_ridx))
1693 break;
1695 /* If we hit a track in between without valid tag info, bail */
1696 if (!tracks[cur_idx].taginfo_ready)
1698 taginfo_ready = false;
1699 break;
1702 if (!taginfo_ready)
1704 audio_rebuffer();
1708 skip_done:
1709 audio_update_trackinfo();
1710 LOGFQUEUE("audio >|= codec Q_CODEC_REQUEST_COMPLETE");
1711 return Q_CODEC_REQUEST_COMPLETE;
1714 unsigned long audio_prev_elapsed(void)
1716 return prev_track_elapsed;
1719 void audio_set_prev_elapsed(unsigned long setting)
1721 prev_track_elapsed = setting;
1724 static void audio_stop_codec_flush(void)
1726 ci.stop_codec = true;
1727 pcmbuf_pause(true);
1729 while (audio_codec_loaded)
1730 yield();
1732 /* If the audio codec is not loaded any more, and the audio is still
1733 * playing, it is now and _only_ now safe to call this function from the
1734 * audio thread */
1735 if (pcm_is_playing())
1737 pcmbuf_play_stop();
1738 pcm_play_lock();
1739 queue_clear(&pcmbuf_queue);
1740 pcm_play_unlock();
1742 pcmbuf_pause(paused);
1745 static void audio_stop_playback(void)
1747 if (playing)
1749 /* If we were playing, save resume information */
1750 struct mp3entry *id3 = NULL;
1752 if (!ci.stop_codec)
1754 /* Set this early, the outside code yields and may allow the codec
1755 to try to wait for a reply on a buffer wait */
1756 ci.stop_codec = true;
1757 id3 = audio_current_track();
1760 /* Save the current playing spot, or NULL if the playlist has ended */
1761 playlist_update_resume_info(id3);
1763 /* Now it's good time to send track finish events. Do this
1764 only if this hasn't been done already as part of a track
1765 switch. */
1766 if (id3 == thistrack_id3)
1767 send_event(PLAYBACK_EVENT_TRACK_FINISH, thistrack_id3);
1769 /* TODO: Create auto bookmark too? */
1771 prev_track_elapsed = othertrack_id3->elapsed;
1773 remove_event(BUFFER_EVENT_BUFFER_LOW, buffering_low_buffer_callback);
1776 audio_stop_codec_flush();
1777 paused = false;
1778 playing = false;
1779 track_load_started = false;
1781 filling = STATE_IDLE;
1783 /* Mark all entries null. */
1784 audio_clear_track_entries();
1786 /* Close all tracks */
1787 audio_release_tracks();
1790 static void audio_play_start(size_t offset)
1792 int i;
1794 send_event(PLAYBACK_EVENT_START_PLAYBACK, NULL);
1795 #if INPUT_SRC_CAPS != 0
1796 audio_set_input_source(AUDIO_SRC_PLAYBACK, SRCF_PLAYBACK);
1797 audio_set_output_source(AUDIO_SRC_PLAYBACK);
1798 #endif
1800 /* Wait for any previously playing audio to flush - TODO: Not necessary? */
1801 paused = false;
1802 audio_stop_codec_flush();
1804 playing = true;
1805 track_load_started = false;
1807 ci.new_track = 0;
1808 ci.seek_time = 0;
1809 wps_offset = 0;
1811 sound_set_volume(global_settings.volume);
1812 track_widx = track_ridx = 0;
1813 buf_set_base_handle(-1);
1815 /* Clear all track entries. */
1816 for (i = 0; i < MAX_TRACK; i++) {
1817 clear_track_info(&tracks[i]);
1820 last_peek_offset = -1;
1822 /* Officially playing */
1823 queue_reply(&audio_queue, 1);
1825 audio_fill_file_buffer(true, offset);
1827 add_event(BUFFER_EVENT_BUFFER_LOW, false, buffering_low_buffer_callback);
1829 LOGFQUEUE("audio > audio Q_AUDIO_TRACK_CHANGED");
1830 queue_post(&audio_queue, Q_AUDIO_TRACK_CHANGED, 0);
1834 /* Invalidates all but currently playing track. */
1835 static void audio_invalidate_tracks(void)
1837 if (audio_have_tracks())
1839 last_peek_offset = 0;
1840 track_widx = track_ridx;
1842 /* Mark all other entries null (also buffered wrong metadata). */
1843 audio_clear_track_entries();
1845 track_widx = (track_widx + 1) & MAX_TRACK_MASK;
1847 audio_fill_file_buffer(false, 0);
1848 send_event(PLAYBACK_EVENT_TRACK_CHANGE, thistrack_id3);
1852 static void audio_new_playlist(void)
1854 /* Prepare to start a new fill from the beginning of the playlist */
1855 last_peek_offset = -1;
1856 if (audio_have_tracks())
1858 if (paused)
1859 skipped_during_pause = true;
1860 track_widx = track_ridx;
1861 audio_clear_track_entries();
1863 track_widx = (track_widx + 1) & MAX_TRACK_MASK;
1865 /* Mark the current track as invalid to prevent skipping back to it */
1866 CUR_TI->taginfo_ready = false;
1869 /* Signal the codec to initiate a track change forward */
1870 new_playlist = true;
1871 ci.new_track = 1;
1873 /* Officially playing */
1874 queue_reply(&audio_queue, 1);
1876 audio_fill_file_buffer(false, 0);
1879 /* Called on manual track skip */
1880 static void audio_initiate_track_change(long direction)
1882 logf("audio_initiate_track_change(%ld)", direction);
1884 ci.new_track += direction;
1885 wps_offset -= direction;
1886 if (paused)
1887 skipped_during_pause = true;
1890 /* Called on manual dir skip */
1891 static void audio_initiate_dir_change(long direction)
1893 dir_skip = true;
1894 ci.new_track = direction;
1895 if (paused)
1896 skipped_during_pause = true;
1899 /* Called when PCM track change is complete */
1900 static void audio_finalise_track_change(void)
1902 logf("audio_finalise_track_change");
1904 if (automatic_skip)
1906 wps_offset = 0;
1907 automatic_skip = false;
1909 /* Invalidate prevtrack_id3 */
1910 memset(othertrack_id3, 0, sizeof(struct mp3entry));
1912 if (prev_ti && prev_ti->audio_hid < 0)
1914 /* No audio left so we clear all the track info. */
1915 clear_track_info(prev_ti);
1918 send_event(PLAYBACK_EVENT_TRACK_CHANGE, thistrack_id3);
1919 playlist_update_resume_info(audio_current_track());
1923 * Layout audio buffer as follows - iram buffer depends on target:
1924 * [|SWAP:iram][|TALK]|FILE|GUARD|PCM|[SWAP:dram[|iram]|]
1926 static void audio_reset_buffer(void)
1928 /* see audio_get_recording_buffer if this is modified */
1929 logf("audio_reset_buffer");
1931 /* If the setup of anything allocated before the file buffer is
1932 changed, do check the adjustments after the buffer_alloc call
1933 as it will likely be affected and need sliding over */
1935 /* Initially set up file buffer as all space available */
1936 malloc_buf = audiobuf + talk_get_bufsize();
1938 /* Align the malloc buf to line size.
1939 * Especially important to cf targets that do line reads/writes.
1940 * Also for targets which need aligned DMA storage buffers */
1941 malloc_buf = (unsigned char *)(((uintptr_t)malloc_buf + (CACHEALIGN_SIZE - 1)) & ~(CACHEALIGN_SIZE - 1));
1942 filebuf = malloc_buf; /* filebuf line align implied */
1943 filebuflen = (audiobufend - filebuf) & ~(CACHEALIGN_SIZE - 1);
1945 /* Subtract whatever the pcm buffer says it used plus the guard buffer */
1946 const size_t pcmbuf_size = pcmbuf_init(filebuf + filebuflen) +GUARD_BUFSIZE;
1947 if(pcmbuf_size > filebuflen)
1948 panicf("%s(): EOM (%zu > %zu)", __func__, pcmbuf_size, filebuflen);
1950 filebuflen -= pcmbuf_size;
1952 /* Make sure filebuflen is a longword multiple after adjustment - filebuf
1953 will already be line aligned */
1954 filebuflen &= ~3;
1956 buffering_reset(filebuf, filebuflen);
1958 /* Clear any references to the file buffer */
1959 buffer_state = AUDIOBUF_STATE_INITIALIZED;
1961 #if defined(ROCKBOX_HAS_LOGF) && defined(LOGF_ENABLE)
1962 /* Make sure everything adds up - yes, some info is a bit redundant but
1963 aids viewing and the sumation of certain variables should add up to
1964 the location of others. */
1966 size_t pcmbufsize;
1967 const unsigned char *pcmbuf = pcmbuf_get_meminfo(&pcmbufsize);
1968 logf("mabuf: %08X", (unsigned)malloc_buf);
1969 logf("fbuf: %08X", (unsigned)filebuf);
1970 logf("fbufe: %08X", (unsigned)(filebuf + filebuflen));
1971 logf("gbuf: %08X", (unsigned)(filebuf + filebuflen));
1972 logf("gbufe: %08X", (unsigned)(filebuf + filebuflen + GUARD_BUFSIZE));
1973 logf("pcmb: %08X", (unsigned)pcmbuf);
1974 logf("pcmbe: %08X", (unsigned)(pcmbuf + pcmbufsize));
1976 #endif
1979 static void audio_thread(void)
1981 struct queue_event ev;
1983 pcm_postinit();
1985 audio_thread_ready = true;
1987 while (1)
1989 if (filling != STATE_FILLING && filling != STATE_IDLE) {
1990 /* End of buffering, let's calculate the watermark and unboost */
1991 set_filebuf_watermark();
1992 cancel_cpu_boost();
1995 if (!pcmbuf_queue_scan(&ev))
1996 queue_wait_w_tmo(&audio_queue, &ev, HZ/2);
1998 switch (ev.id) {
2000 case Q_AUDIO_FILL_BUFFER:
2001 LOGFQUEUE("audio < Q_AUDIO_FILL_BUFFER %d", (int)ev.data);
2002 audio_fill_file_buffer((bool)ev.data, 0);
2003 break;
2005 case Q_AUDIO_FINISH_LOAD:
2006 LOGFQUEUE("audio < Q_AUDIO_FINISH_LOAD");
2007 audio_finish_load_track();
2008 buf_set_base_handle(CUR_TI->audio_hid);
2009 break;
2011 case Q_AUDIO_PLAY:
2012 LOGFQUEUE("audio < Q_AUDIO_PLAY");
2013 if (playing && ev.data <= 0)
2014 audio_new_playlist();
2015 else
2017 audio_stop_playback();
2018 audio_play_start((size_t)ev.data);
2020 break;
2022 case Q_AUDIO_STOP:
2023 LOGFQUEUE("audio < Q_AUDIO_STOP");
2024 if (playing)
2025 audio_stop_playback();
2026 if (ev.data != 0)
2027 queue_clear(&audio_queue);
2028 break;
2030 case Q_AUDIO_PAUSE:
2031 LOGFQUEUE("audio < Q_AUDIO_PAUSE");
2032 if (!(bool) ev.data && skipped_during_pause
2033 #ifdef HAVE_CROSSFADE
2034 && !pcmbuf_is_crossfade_active()
2035 #endif
2037 pcmbuf_play_stop(); /* Flush old track on resume after skip */
2038 skipped_during_pause = false;
2039 if (!playing)
2040 break;
2041 pcmbuf_pause((bool)ev.data);
2042 paused = (bool)ev.data;
2043 break;
2045 case Q_AUDIO_SKIP:
2046 LOGFQUEUE("audio < Q_AUDIO_SKIP");
2047 audio_initiate_track_change((long)ev.data);
2048 break;
2050 case Q_AUDIO_PRE_FF_REWIND:
2051 LOGFQUEUE("audio < Q_AUDIO_PRE_FF_REWIND");
2052 if (!playing)
2053 break;
2054 pcmbuf_pause(true);
2055 break;
2057 case Q_AUDIO_FF_REWIND:
2058 LOGFQUEUE("audio < Q_AUDIO_FF_REWIND");
2059 if (!playing)
2060 break;
2062 if ((long)ev.data == 0)
2064 /* About to restart the track - send track finish
2065 events if not already done. */
2066 if (thistrack_id3 == audio_current_track())
2067 send_event(PLAYBACK_EVENT_TRACK_FINISH, thistrack_id3);
2070 if (automatic_skip)
2072 /* An automatic track skip is in progress. Finalize it,
2073 then go back to the previous track */
2074 audio_finalise_track_change();
2075 ci.new_track = -1;
2077 ci.seek_time = (long)ev.data+1;
2078 break;
2080 case Q_AUDIO_CHECK_NEW_TRACK:
2081 LOGFQUEUE("audio < Q_AUDIO_CHECK_NEW_TRACK");
2082 queue_reply(&audio_queue, audio_check_new_track());
2083 break;
2085 case Q_AUDIO_DIR_SKIP:
2086 LOGFQUEUE("audio < Q_AUDIO_DIR_SKIP");
2087 audio_initiate_dir_change(ev.data);
2088 break;
2090 case Q_AUDIO_FLUSH:
2091 LOGFQUEUE("audio < Q_AUDIO_FLUSH");
2092 audio_invalidate_tracks();
2093 break;
2095 case Q_AUDIO_TRACK_CHANGED:
2096 /* PCM track change done */
2097 LOGFQUEUE("audio < Q_AUDIO_TRACK_CHANGED");
2098 audio_finalise_track_change();
2099 break;
2100 #if (CONFIG_PLATFORM & PLATFORM_NATIVE)
2101 case SYS_USB_CONNECTED:
2102 LOGFQUEUE("audio < SYS_USB_CONNECTED");
2103 if (playing)
2104 audio_stop_playback();
2105 #ifdef PLAYBACK_VOICE
2106 voice_stop();
2107 #endif
2108 usb_acknowledge(SYS_USB_CONNECTED_ACK);
2109 usb_wait_for_disconnect(&audio_queue);
2111 /* Mark all entries null. */
2112 audio_clear_track_entries();
2114 /* release tracks to make sure all handles are closed */
2115 audio_release_tracks();
2116 break;
2117 #endif
2119 case SYS_TIMEOUT:
2120 LOGFQUEUE_SYS_TIMEOUT("audio < SYS_TIMEOUT");
2121 break;
2123 default:
2124 /* LOGFQUEUE("audio < default : %08lX", ev.id); */
2125 break;
2126 } /* end switch */
2127 } /* end while */
2130 /* Initialize the audio system - called from init() in main.c.
2131 * Last function because of all the references to internal symbols
2133 void audio_init(void)
2135 unsigned int audio_thread_id;
2137 /* Can never do this twice */
2138 if (audio_is_initialized)
2140 logf("audio: already initialized");
2141 return;
2144 logf("audio: initializing");
2146 /* Initialize queues before giving control elsewhere in case it likes
2147 to send messages. Thread creation will be delayed however so nothing
2148 starts running until ready if something yields such as talk_init. */
2149 queue_init(&audio_queue, true);
2150 queue_init(&codec_queue, false);
2151 queue_init(&pcmbuf_queue, false);
2153 pcm_init();
2155 codec_init_codec_api();
2157 thistrack_id3 = &mp3entry_buf[0];
2158 othertrack_id3 = &mp3entry_buf[1];
2160 /* cuesheet support */
2161 if (global_settings.cuesheet)
2162 curr_cue = (struct cuesheet*)buffer_alloc(sizeof(struct cuesheet));
2164 /* initialize the buffer */
2165 filebuf = audiobuf;
2167 /* audio_reset_buffer must to know the size of voice buffer so init
2168 talk first */
2169 talk_init();
2171 make_codec_thread();
2173 audio_thread_id = create_thread(audio_thread, audio_stack,
2174 sizeof(audio_stack), CREATE_THREAD_FROZEN,
2175 audio_thread_name IF_PRIO(, PRIORITY_USER_INTERFACE)
2176 IF_COP(, CPU));
2178 queue_enable_queue_send(&audio_queue, &audio_queue_sender_list,
2179 audio_thread_id);
2181 #ifdef PLAYBACK_VOICE
2182 voice_thread_init();
2183 #endif
2185 #ifdef HAVE_CROSSFADE
2186 /* Set crossfade setting for next buffer init which should be about... */
2187 pcmbuf_request_crossfade_enable(global_settings.crossfade);
2188 #endif
2190 /* initialize the buffering system */
2192 buffering_init();
2193 /* ...now! Set up the buffers */
2194 audio_reset_buffer();
2196 int i;
2197 for(i = 0; i < MAX_TRACK; i++)
2199 tracks[i].audio_hid = -1;
2200 tracks[i].id3_hid = -1;
2201 tracks[i].codec_hid = -1;
2202 tracks[i].cuesheet_hid = -1;
2204 #ifdef HAVE_ALBUMART
2205 FOREACH_ALBUMART(i)
2207 int j;
2208 for (j = 0; j < MAX_TRACK; j++)
2210 tracks[j].aa_hid[i] = -1;
2213 #endif
2215 add_event(BUFFER_EVENT_REBUFFER, false, buffering_handle_rebuffer_callback);
2216 add_event(BUFFER_EVENT_FINISHED, false, buffering_handle_finished_callback);
2218 /* Probably safe to say */
2219 audio_is_initialized = true;
2221 sound_settings_apply();
2222 #ifdef HAVE_DISK_STORAGE
2223 audio_set_buffer_margin(global_settings.buffer_margin);
2224 #endif
2226 /* it's safe to let the threads run now */
2227 #ifdef PLAYBACK_VOICE
2228 voice_thread_resume();
2229 #endif
2230 thread_thaw(codec_thread_id);
2231 thread_thaw(audio_thread_id);
2233 } /* audio_init */
2235 bool audio_is_thread_ready(void)
2237 return audio_thread_ready;
2240 size_t audio_get_filebuflen(void)
2242 return filebuflen;
2245 int get_audio_hid()
2247 return CUR_TI->audio_hid;
2250 int *get_codec_hid()
2252 return &tracks[track_ridx].codec_hid;