Define sd_drive_nr also when HAVE_HOTSWAP is defined (fix red).
[kugel-rb.git] / apps / playback.c
blobff20172d83ce3e71b85684554ad26f16622ef175
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"
52 #ifdef HAVE_RECORDING
53 #include "pcm_record.h"
54 #endif
56 #define PLAYBACK_VOICE
58 /* amount of guess-space to allow for codecs that must hunt and peck
59 * for their correct seeek target, 32k seems a good size */
60 #define AUDIO_REBUFFER_GUESS_SIZE (1024*32)
62 /* Define LOGF_ENABLE to enable logf output in this file */
63 /*#define LOGF_ENABLE*/
64 #include "logf.h"
66 /* macros to enable logf for queues
67 logging on SYS_TIMEOUT can be disabled */
68 #ifdef SIMULATOR
69 /* Define this for logf output of all queuing except SYS_TIMEOUT */
70 #define PLAYBACK_LOGQUEUES
71 /* Define this to logf SYS_TIMEOUT messages */
72 /*#define PLAYBACK_LOGQUEUES_SYS_TIMEOUT*/
73 #endif
75 #ifdef PLAYBACK_LOGQUEUES
76 #define LOGFQUEUE logf
77 #else
78 #define LOGFQUEUE(...)
79 #endif
81 #ifdef PLAYBACK_LOGQUEUES_SYS_TIMEOUT
82 #define LOGFQUEUE_SYS_TIMEOUT logf
83 #else
84 #define LOGFQUEUE_SYS_TIMEOUT(...)
85 #endif
88 static enum filling_state {
89 STATE_IDLE, /* audio is stopped: nothing to do */
90 STATE_FILLING, /* adding tracks to the buffer */
91 STATE_FULL, /* can't add any more tracks */
92 STATE_END_OF_PLAYLIST, /* all remaining tracks have been added */
93 STATE_FINISHED, /* all remaining tracks are fully buffered */
94 } filling;
96 /* As defined in plugins/lib/xxx2wav.h */
97 #define GUARD_BUFSIZE (32*1024)
99 bool audio_is_initialized = false;
100 static bool audio_thread_ready SHAREDBSS_ATTR = false;
102 /* Variables are commented with the threads that use them: *
103 * A=audio, C=codec, V=voice. A suffix of - indicates that *
104 * the variable is read but not updated on that thread. */
105 /* TBD: Split out "audio" and "playback" (ie. calling) threads */
107 /* Main state control */
108 static volatile bool playing SHAREDBSS_ATTR = false;/* Is audio playing? (A) */
109 static volatile bool paused SHAREDBSS_ATTR = false; /* Is audio paused? (A/C-) */
110 extern volatile bool audio_codec_loaded; /* Codec loaded? (C/A-) */
112 /* Ring buffer where compressed audio and codecs are loaded */
113 static unsigned char *filebuf = NULL; /* Start of buffer (A/C-) */
114 static unsigned char *malloc_buf = NULL; /* Start of malloc buffer (A/C-) */
115 static size_t filebuflen = 0; /* Size of buffer (A/C-) */
116 /* FIXME: make buf_ridx (C/A-) */
118 /* Possible arrangements of the buffer */
119 enum audio_buffer_state
121 AUDIOBUF_STATE_TRASHED = -1, /* trashed; must be reset */
122 AUDIOBUF_STATE_INITIALIZED = 0, /* voice+audio OR audio-only */
123 AUDIOBUF_STATE_VOICED_ONLY = 1, /* voice-only */
125 static int buffer_state = AUDIOBUF_STATE_TRASHED; /* Buffer state */
127 /* These are used to store the current and next (or prev if the current is the last)
128 * mp3entry's in a round-robin system. This guarentees that the pointer returned
129 * by audio_current/next_track will be valid for the full duration of the
130 * currently playing track */
131 static struct mp3entry mp3entry_buf[2];
132 struct mp3entry *thistrack_id3, /* the currently playing track */
133 *othertrack_id3; /* prev track during track-change-transition, or end of playlist,
134 * next track otherwise */
135 static struct mp3entry unbuffered_id3; /* the id3 for the first unbuffered track */
137 /* for cuesheet support */
138 static struct cuesheet *curr_cue = NULL;
141 #define MAX_MULTIPLE_AA 2
143 #ifdef HAVE_ALBUMART
144 static struct albumart_slot {
145 struct dim dim; /* holds width, height of the albumart */
146 int used; /* counter, increments if something uses it */
147 } albumart_slots[MAX_MULTIPLE_AA];
149 #define FOREACH_ALBUMART(i) for(i = 0;i < MAX_MULTIPLE_AA; i++)
150 #endif
153 #define MAX_TRACK 128
154 #define MAX_TRACK_MASK (MAX_TRACK-1)
156 /* Track info structure about songs in the file buffer (A/C-) */
157 static struct track_info {
158 int audio_hid; /* The ID for the track's buffer handle */
159 int id3_hid; /* The ID for the track's metadata handle */
160 int codec_hid; /* The ID for the track's codec handle */
161 #ifdef HAVE_ALBUMART
162 int aa_hid[MAX_MULTIPLE_AA];/* The ID for the track's album art handle */
163 #endif
164 int cuesheet_hid; /* The ID for the track's parsed cueesheet handle */
166 size_t filesize; /* File total length */
168 bool taginfo_ready; /* Is metadata read */
170 } tracks[MAX_TRACK];
172 static volatile int track_ridx = 0; /* Track being decoded (A/C-) */
173 static int track_widx = 0; /* Track being buffered (A) */
174 #define CUR_TI (&tracks[track_ridx]) /* Playing track info pointer (A/C-) */
176 static struct track_info *prev_ti = NULL; /* Pointer to the previously played
177 track */
179 /* Information used only for filling the buffer */
180 /* Playlist steps from playing track to next track to be buffered (A) */
181 static int last_peek_offset = 0;
183 /* Scrobbler support */
184 static unsigned long prev_track_elapsed = 0; /* Previous track elapsed time (C/A-)*/
186 /* Track change controls */
187 bool automatic_skip = false; /* Who initiated in-progress skip? (C/A-) */
188 extern bool track_transition; /* Are we in a track transition? */
189 static bool dir_skip = false; /* Is a directory skip pending? (A) */
190 static bool new_playlist = false; /* Are we starting a new playlist? (A) */
191 static int wps_offset = 0; /* Pending track change offset, to keep WPS responsive (A) */
192 static bool skipped_during_pause = false; /* Do we need to clear the PCM buffer when playback resumes (A) */
194 static bool start_play_g = false; /* Used by audio_load_track to notify
195 audio_finish_load_track about start_play */
197 /* True when a track load is in progress, i.e. audio_load_track() has returned
198 * but audio_finish_load_track() hasn't been called yet. Used to avoid allowing
199 * audio_load_track() to get called twice in a row, which would cause problems.
201 static bool track_load_started = false;
203 #ifdef HAVE_DISK_STORAGE
204 static size_t buffer_margin = 5; /* Buffer margin aka anti-skip buffer (A/C-) */
205 #endif
207 /* Event queues */
208 struct event_queue audio_queue SHAREDBSS_ATTR;
209 struct event_queue codec_queue SHAREDBSS_ATTR;
210 static struct event_queue pcmbuf_queue SHAREDBSS_ATTR;
212 extern struct codec_api ci;
213 extern unsigned int codec_thread_id;
215 /* Multiple threads */
216 /* Set the watermark to trigger buffer fill (A/C) */
217 static void set_filebuf_watermark(void);
219 /* Audio thread */
220 static struct queue_sender_list audio_queue_sender_list SHAREDBSS_ATTR;
221 static long audio_stack[(DEFAULT_STACK_SIZE + 0x1000)/sizeof(long)];
222 static const char audio_thread_name[] = "audio";
224 static void audio_thread(void);
225 static void audio_initiate_track_change(long direction);
226 static bool audio_have_tracks(void);
227 static void audio_reset_buffer(void);
228 static void audio_stop_playback(void);
231 /**************************************/
234 /** Pcmbuf callbacks */
236 /* Between the codec and PCM track change, we need to keep updating the
237 * "elapsed" value of the previous (to the codec, but current to the
238 * user/PCM/WPS) track, so that the progressbar reaches the end.
239 * During that transition, the WPS will display othertrack_id3. */
240 void audio_pcmbuf_position_callback(unsigned int time)
242 time += othertrack_id3->elapsed;
244 if (time >= othertrack_id3->length)
246 /* we just played the end of the track, so stop this callback */
247 track_transition = false;
248 othertrack_id3->elapsed = othertrack_id3->length;
250 else
251 othertrack_id3->elapsed = time;
254 /* Post message from pcmbuf that the end of the previous track
255 * has just been played. */
256 void audio_post_track_change(bool pcmbuf)
258 if (pcmbuf)
260 LOGFQUEUE("pcmbuf > pcmbuf Q_AUDIO_TRACK_CHANGED");
261 queue_post(&pcmbuf_queue, Q_AUDIO_TRACK_CHANGED, 0);
263 else
265 LOGFQUEUE("pcmbuf > audio Q_AUDIO_TRACK_CHANGED");
266 queue_post(&audio_queue, Q_AUDIO_TRACK_CHANGED, 0);
270 /* Scan the pcmbuf queue and return true if a message pulled */
271 static bool pcmbuf_queue_scan(struct queue_event *ev)
273 if (!queue_empty(&pcmbuf_queue))
275 /* Transfer message to audio queue */
276 pcm_play_lock();
277 /* Pull message - never, ever any blocking call! */
278 queue_wait_w_tmo(&pcmbuf_queue, ev, 0);
279 pcm_play_unlock();
280 return true;
283 return false;
287 /** Helper functions */
289 static struct mp3entry *bufgetid3(int handle_id)
291 if (handle_id < 0)
292 return NULL;
294 struct mp3entry *id3;
295 ssize_t ret = bufgetdata(handle_id, 0, (void *)&id3);
297 if (ret < 0 || ret != sizeof(struct mp3entry))
298 return NULL;
300 return id3;
303 static bool clear_track_info(struct track_info *track)
305 /* bufclose returns true if the handle is not found, or if it is closed
306 * successfully, so these checks are safe on non-existant handles */
307 if (!track)
308 return false;
310 if (track->codec_hid >= 0) {
311 if (bufclose(track->codec_hid))
312 track->codec_hid = -1;
313 else
314 return false;
317 if (track->id3_hid >= 0) {
318 if (bufclose(track->id3_hid))
319 track->id3_hid = -1;
320 else
321 return false;
324 if (track->audio_hid >= 0) {
325 if (bufclose(track->audio_hid))
326 track->audio_hid = -1;
327 else
328 return false;
331 #ifdef HAVE_ALBUMART
333 int i;
334 FOREACH_ALBUMART(i)
336 if (track->aa_hid[i] >= 0) {
337 if (bufclose(track->aa_hid[i]))
338 track->aa_hid[i] = -1;
339 else
340 return false;
344 #endif
346 if (track->cuesheet_hid >= 0) {
347 if (bufclose(track->cuesheet_hid))
348 track->cuesheet_hid = -1;
349 else
350 return false;
353 track->filesize = 0;
354 track->taginfo_ready = false;
356 return true;
359 /* --- External interfaces --- */
361 /* This sends a stop message and the audio thread will dump all it's
362 subsequenct messages */
363 void audio_hard_stop(void)
365 /* Stop playback */
366 LOGFQUEUE("audio >| audio Q_AUDIO_STOP: 1");
367 queue_send(&audio_queue, Q_AUDIO_STOP, 1);
368 #ifdef PLAYBACK_VOICE
369 voice_stop();
370 #endif
373 bool audio_restore_playback(int type)
375 switch (type)
377 case AUDIO_WANT_PLAYBACK:
378 if (buffer_state != AUDIOBUF_STATE_INITIALIZED)
379 audio_reset_buffer();
380 return true;
381 case AUDIO_WANT_VOICE:
382 if (buffer_state == AUDIOBUF_STATE_TRASHED)
383 audio_reset_buffer();
384 return true;
385 default:
386 return false;
390 unsigned char *audio_get_buffer(bool talk_buf, size_t *buffer_size)
392 unsigned char *buf, *end;
394 if (audio_is_initialized)
396 audio_hard_stop();
398 /* else buffer_state will be AUDIOBUF_STATE_TRASHED at this point */
400 /* Reset the buffering thread so that it doesn't try to use the data */
401 buffering_reset(filebuf, filebuflen);
403 if (buffer_size == NULL)
405 /* Special case for talk_init to use since it already knows it's
406 trashed */
407 buffer_state = AUDIOBUF_STATE_TRASHED;
408 return NULL;
411 if (talk_buf || buffer_state == AUDIOBUF_STATE_TRASHED
412 || !talk_voice_required())
414 logf("get buffer: talk, audio");
415 /* Ok to use everything from audiobuf to audiobufend - voice is loaded,
416 the talk buffer is not needed because voice isn't being used, or
417 could be AUDIOBUF_STATE_TRASHED already. If state is
418 AUDIOBUF_STATE_VOICED_ONLY, no problem as long as memory isn't written
419 without the caller knowing what's going on. Changing certain settings
420 may move it to a worse condition but the memory in use by something
421 else will remain undisturbed.
423 if (buffer_state != AUDIOBUF_STATE_TRASHED)
425 talk_buffer_steal();
426 buffer_state = AUDIOBUF_STATE_TRASHED;
429 buf = audiobuf;
430 end = audiobufend;
432 else
434 /* Safe to just return this if already AUDIOBUF_STATE_VOICED_ONLY or
435 still AUDIOBUF_STATE_INITIALIZED */
436 /* Skip talk buffer and move pcm buffer to end to maximize available
437 contiguous memory - no audio running means voice will not need the
438 swap space */
439 logf("get buffer: audio");
440 buf = audiobuf + talk_get_bufsize();
441 end = audiobufend - pcmbuf_init(audiobufend);
442 buffer_state = AUDIOBUF_STATE_VOICED_ONLY;
445 *buffer_size = end - buf;
447 return buf;
450 bool audio_buffer_state_trashed(void)
452 return buffer_state == AUDIOBUF_STATE_TRASHED;
455 #ifdef HAVE_RECORDING
456 unsigned char *audio_get_recording_buffer(size_t *buffer_size)
458 /* Stop audio, voice and obtain all available buffer space */
459 audio_hard_stop();
460 talk_buffer_steal();
462 unsigned char *end = audiobufend;
463 buffer_state = AUDIOBUF_STATE_TRASHED;
464 *buffer_size = end - audiobuf;
466 return (unsigned char *)audiobuf;
469 bool audio_load_encoder(int afmt)
471 #ifndef SIMULATOR
472 const char *enc_fn = get_codec_filename(afmt | CODEC_TYPE_ENCODER);
473 if (!enc_fn)
474 return false;
476 audio_remove_encoder();
477 ci.enc_codec_loaded = 0; /* clear any previous error condition */
479 LOGFQUEUE("codec > Q_ENCODER_LOAD_DISK");
480 queue_post(&codec_queue, Q_ENCODER_LOAD_DISK, (intptr_t)enc_fn);
482 while (ci.enc_codec_loaded == 0)
483 yield();
485 logf("codec loaded: %d", ci.enc_codec_loaded);
487 return ci.enc_codec_loaded > 0;
488 #else
489 (void)afmt;
490 return true;
491 #endif
492 } /* audio_load_encoder */
494 void audio_remove_encoder(void)
496 #ifndef SIMULATOR
497 /* force encoder codec unload (if currently loaded) */
498 if (ci.enc_codec_loaded <= 0)
499 return;
501 ci.stop_encoder = true;
502 while (ci.enc_codec_loaded > 0)
503 yield();
504 #endif
505 } /* audio_remove_encoder */
507 #endif /* HAVE_RECORDING */
510 struct mp3entry* audio_current_track(void)
512 const char *filename;
513 struct playlist_track_info trackinfo;
514 int cur_idx;
515 int offset = ci.new_track + wps_offset;
516 struct mp3entry *write_id3;
518 cur_idx = (track_ridx + offset) & MAX_TRACK_MASK;
520 if (cur_idx == track_ridx && *thistrack_id3->path)
522 /* The usual case */
523 if (tracks[cur_idx].cuesheet_hid >= 0 && !thistrack_id3->cuesheet)
525 bufread(tracks[cur_idx].cuesheet_hid, sizeof(struct cuesheet), curr_cue);
526 thistrack_id3->cuesheet = curr_cue;
527 cue_spoof_id3(thistrack_id3->cuesheet, thistrack_id3);
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;
541 cue_spoof_id3(othertrack_id3->cuesheet, othertrack_id3);
543 return othertrack_id3;
546 if (offset != 0)
548 /* Codec may be using thistrack_id3, so it must not be overwritten.
549 If this is a manual skip, othertrack_id3 will become
550 thistrack_id3 in audio_check_new_track().
551 FIXME: If this is an automatic skip, it probably means multiple
552 short tracks fit in the PCM buffer. Overwriting othertrack_id3
553 can lead to an incorrect value later.
554 Note that othertrack_id3 may also be used for next track.
556 write_id3 = othertrack_id3;
558 else
560 write_id3 = thistrack_id3;
563 if (tracks[cur_idx].id3_hid >= 0)
565 /* The current track's info has been buffered but not read yet, so get it */
566 if (bufread(tracks[cur_idx].id3_hid, sizeof(struct mp3entry), write_id3)
567 == sizeof(struct mp3entry))
568 return write_id3;
571 /* We didn't find the ID3 metadata, so we fill temp_id3 with the little info
572 we have and return that. */
574 memset(write_id3, 0, sizeof(struct mp3entry));
576 playlist_get_track_info(NULL, playlist_next(0)+wps_offset, &trackinfo);
577 filename = trackinfo.filename;
578 if (!filename)
579 filename = "No file!";
581 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
582 if (tagcache_fill_tags(write_id3, filename))
583 return write_id3;
584 #endif
586 strlcpy(write_id3->path, filename, sizeof(write_id3->path));
587 write_id3->title = strrchr(write_id3->path, '/');
588 if (!write_id3->title)
589 write_id3->title = &write_id3->path[0];
590 else
591 write_id3->title++;
593 return write_id3;
596 struct mp3entry* audio_next_track(void)
598 int next_idx;
599 int offset = ci.new_track + wps_offset;
601 if (!audio_have_tracks())
602 return NULL;
604 if (wps_offset == -1 && *thistrack_id3->path)
606 /* We're in a track transition. The next track for the WPS is the one
607 currently being decoded. */
608 return thistrack_id3;
611 next_idx = (track_ridx + offset + 1) & MAX_TRACK_MASK;
613 if (tracks[next_idx].id3_hid >= 0)
615 if (bufread(tracks[next_idx].id3_hid, sizeof(struct mp3entry), othertrack_id3)
616 == sizeof(struct mp3entry))
617 return othertrack_id3;
618 else
619 return NULL;
622 if (next_idx == track_widx)
624 /* The next track hasn't been buffered yet, so we return the static
625 version of its metadata. */
626 return &unbuffered_id3;
629 return NULL;
632 #ifdef HAVE_ALBUMART
633 int playback_current_aa_hid(int slot)
635 if (slot < 0)
636 return -1;
637 int cur_idx;
638 int offset = ci.new_track + wps_offset;
640 cur_idx = track_ridx + offset;
641 cur_idx &= MAX_TRACK_MASK;
643 return tracks[cur_idx].aa_hid[slot];
646 int playback_claim_aa_slot(struct dim *dim)
648 int i;
649 /* first try to find a slot already having the size to reuse it
650 * since we don't want albumart of the same size buffered multiple times */
651 FOREACH_ALBUMART(i)
653 struct albumart_slot *slot = &albumart_slots[i];
654 if (slot->dim.width == dim->width
655 && slot->dim.height == dim->height)
657 slot->used++;
658 return i;
661 /* size is new, find a free slot */
662 FOREACH_ALBUMART(i)
664 if (!albumart_slots[i].used)
666 albumart_slots[i].used++;
667 albumart_slots[i].dim = *dim;
668 return i;
671 /* sorry, no free slot */
672 return -1;
675 void playback_release_aa_slot(int slot)
677 /* invalidate the albumart_slot */
678 struct albumart_slot *aa_slot = &albumart_slots[slot];
679 if (aa_slot->used > 0)
680 aa_slot->used--;
683 #endif
684 void audio_play(long offset)
686 logf("audio_play");
688 #ifdef PLAYBACK_VOICE
689 /* Truncate any existing voice output so we don't have spelling
690 * etc. over the first part of the played track */
691 talk_force_shutup();
692 #endif
694 /* Start playback */
695 LOGFQUEUE("audio >| audio Q_AUDIO_PLAY: %ld", offset);
696 /* Don't return until playback has actually started */
697 queue_send(&audio_queue, Q_AUDIO_PLAY, offset);
700 void audio_stop(void)
702 /* Stop playback */
703 LOGFQUEUE("audio >| audio Q_AUDIO_STOP");
704 /* Don't return until playback has actually stopped */
705 queue_send(&audio_queue, Q_AUDIO_STOP, 0);
708 void audio_pause(void)
710 LOGFQUEUE("audio >| audio Q_AUDIO_PAUSE");
711 /* Don't return until playback has actually paused */
712 queue_send(&audio_queue, Q_AUDIO_PAUSE, true);
715 void audio_resume(void)
717 LOGFQUEUE("audio >| audio Q_AUDIO_PAUSE resume");
718 /* Don't return until playback has actually resumed */
719 queue_send(&audio_queue, Q_AUDIO_PAUSE, false);
722 void audio_skip(int direction)
724 if (playlist_check(ci.new_track + wps_offset + direction))
726 if (global_settings.beep)
727 pcmbuf_beep(2000, 100, 2500*global_settings.beep);
729 LOGFQUEUE("audio > audio Q_AUDIO_SKIP %d", direction);
730 queue_post(&audio_queue, Q_AUDIO_SKIP, direction);
731 /* Update wps while our message travels inside deep playback queues. */
732 wps_offset += direction;
734 else
736 /* No more tracks. */
737 if (global_settings.beep)
738 pcmbuf_beep(1000, 100, 1500*global_settings.beep);
742 void audio_next(void)
744 audio_skip(1);
747 void audio_prev(void)
749 audio_skip(-1);
752 void audio_next_dir(void)
754 LOGFQUEUE("audio > audio Q_AUDIO_DIR_SKIP 1");
755 queue_post(&audio_queue, Q_AUDIO_DIR_SKIP, 1);
758 void audio_prev_dir(void)
760 LOGFQUEUE("audio > audio Q_AUDIO_DIR_SKIP -1");
761 queue_post(&audio_queue, Q_AUDIO_DIR_SKIP, -1);
764 void audio_pre_ff_rewind(void)
766 LOGFQUEUE("audio > audio Q_AUDIO_PRE_FF_REWIND");
767 queue_post(&audio_queue, Q_AUDIO_PRE_FF_REWIND, 0);
770 void audio_ff_rewind(long newpos)
772 LOGFQUEUE("audio > audio Q_AUDIO_FF_REWIND");
773 queue_post(&audio_queue, Q_AUDIO_FF_REWIND, newpos);
776 void audio_flush_and_reload_tracks(void)
778 LOGFQUEUE("audio > audio Q_AUDIO_FLUSH");
779 queue_post(&audio_queue, Q_AUDIO_FLUSH, 0);
782 void audio_error_clear(void)
784 #ifdef AUDIO_HAVE_RECORDING
785 pcm_rec_error_clear();
786 #endif
789 int audio_status(void)
791 int ret = 0;
793 if (playing)
794 ret |= AUDIO_STATUS_PLAY;
796 if (paused)
797 ret |= AUDIO_STATUS_PAUSE;
799 #ifdef HAVE_RECORDING
800 /* Do this here for constitency with mpeg.c version */
801 /* FIXME: pcm_rec_status() is deprecated */
802 ret |= pcm_rec_status();
803 #endif
805 return ret;
808 int audio_get_file_pos(void)
810 return 0;
813 #ifdef HAVE_DISK_STORAGE
814 void audio_set_buffer_margin(int setting)
816 static const unsigned short lookup[] = {5, 15, 30, 60, 120, 180, 300, 600};
817 buffer_margin = lookup[setting];
818 logf("buffer margin: %ld", (long)buffer_margin);
819 set_filebuf_watermark();
821 #endif
823 #ifdef HAVE_CROSSFADE
824 /* Take necessary steps to enable or disable the crossfade setting */
825 void audio_set_crossfade(int enable)
827 size_t offset;
828 bool was_playing;
829 size_t size;
831 /* Tell it the next setting to use */
832 pcmbuf_request_crossfade_enable(enable);
834 /* Return if size hasn't changed or this is too early to determine
835 which in the second case there's no way we could be playing
836 anything at all */
837 if (pcmbuf_is_same_size()) return;
839 offset = 0;
840 was_playing = playing;
842 /* Playback has to be stopped before changing the buffer size */
843 if (was_playing)
845 /* Store the track resume position */
846 offset = thistrack_id3->offset;
849 /* Blast it - audio buffer will have to be setup again next time
850 something plays */
851 audio_get_buffer(true, &size);
853 /* Restart playback if audio was running previously */
854 if (was_playing)
855 audio_play(offset);
857 #endif
859 /* --- Routines called from multiple threads --- */
861 static void set_filebuf_watermark(void)
863 if (!filebuf)
864 return; /* Audio buffers not yet set up */
866 #ifdef HAVE_DISK_STORAGE
867 int seconds;
868 int spinup = ata_spinup_time();
869 if (spinup)
870 seconds = (spinup / HZ) + 1;
871 else
872 seconds = 5;
874 seconds += buffer_margin;
875 #else
876 /* flash storage */
877 int seconds = 1;
878 #endif
880 /* bitrate of last track in buffer dictates watermark */
881 struct mp3entry* id3 = NULL;
882 if (tracks[track_widx].taginfo_ready)
883 id3 = bufgetid3(tracks[track_widx].id3_hid);
884 else
885 id3 = bufgetid3(tracks[track_widx-1].id3_hid);
886 if (!id3) {
887 logf("fwmark: No id3 for last track (r%d/w%d), aborting!", track_ridx, track_widx);
888 return;
890 size_t bytes = id3->bitrate * (1000/8) * seconds;
891 buf_set_watermark(bytes);
892 logf("fwmark: %d", bytes);
895 /* --- Buffering callbacks --- */
897 static void buffering_low_buffer_callback(void *data)
899 (void)data;
900 logf("low buffer callback");
902 if (filling == STATE_FULL || filling == STATE_END_OF_PLAYLIST) {
903 /* force a refill */
904 LOGFQUEUE("buffering > audio Q_AUDIO_FILL_BUFFER");
905 queue_post(&audio_queue, Q_AUDIO_FILL_BUFFER, 0);
909 static void buffering_handle_rebuffer_callback(void *data)
911 (void)data;
912 LOGFQUEUE("audio >| audio Q_AUDIO_FLUSH");
913 queue_post(&audio_queue, Q_AUDIO_FLUSH, 0);
916 static void buffering_handle_finished_callback(void *data)
918 logf("handle %d finished buffering", *(int*)data);
919 int hid = (*(int*)data);
921 if (hid == tracks[track_widx].id3_hid)
923 int offset = ci.new_track + wps_offset;
924 int next_idx = (track_ridx + offset + 1) & MAX_TRACK_MASK;
925 /* The metadata handle for the last loaded track has been buffered.
926 We can ask the audio thread to load the rest of the track's data. */
927 LOGFQUEUE("audio >| audio Q_AUDIO_FINISH_LOAD");
928 queue_post(&audio_queue, Q_AUDIO_FINISH_LOAD, 0);
929 if (tracks[next_idx].id3_hid == hid)
930 send_event(PLAYBACK_EVENT_NEXTTRACKID3_AVAILABLE, NULL);
932 else
934 /* This is most likely an audio handle, so we strip the useless
935 trailing tags that are left. */
936 strip_tags(hid);
938 if (hid == tracks[track_widx-1].audio_hid
939 && filling == STATE_END_OF_PLAYLIST)
941 /* This was the last track in the playlist.
942 We now have all the data we need. */
943 logf("last track finished buffering");
944 filling = STATE_FINISHED;
950 /* --- Audio thread --- */
952 static bool audio_have_tracks(void)
954 return (audio_track_count() != 0);
957 static int audio_free_track_count(void)
959 /* Used tracks + free tracks adds up to MAX_TRACK - 1 */
960 return MAX_TRACK - 1 - audio_track_count();
963 int audio_track_count(void)
965 /* Calculate difference from track_ridx to track_widx
966 * taking into account a possible wrap-around. */
967 return (MAX_TRACK + track_widx - track_ridx) & MAX_TRACK_MASK;
970 long audio_filebufused(void)
972 return (long) buf_used();
975 /* Update track info after successful a codec track change */
976 static void audio_update_trackinfo(void)
978 /* Load the curent track's metadata into curtrack_id3 */
979 if (CUR_TI->id3_hid >= 0)
980 copy_mp3entry(thistrack_id3, bufgetid3(CUR_TI->id3_hid));
982 /* Reset current position */
983 thistrack_id3->elapsed = 0;
984 thistrack_id3->offset = 0;
986 /* Update the codec API */
987 ci.filesize = CUR_TI->filesize;
988 ci.id3 = thistrack_id3;
989 ci.curpos = 0;
990 ci.taginfo_ready = &CUR_TI->taginfo_ready;
993 /* Clear tracks between write and read, non inclusive */
994 static void audio_clear_track_entries(void)
996 int cur_idx = track_widx;
998 logf("Clearing tracks: r%d/w%d", track_ridx, track_widx);
1000 /* Loop over all tracks from write-to-read */
1001 while (1)
1003 cur_idx = (cur_idx + 1) & MAX_TRACK_MASK;
1005 if (cur_idx == track_ridx)
1006 break;
1008 clear_track_info(&tracks[cur_idx]);
1012 /* Clear all tracks */
1013 static bool audio_release_tracks(void)
1015 int i, cur_idx;
1017 logf("releasing all tracks");
1019 for(i = 0; i < MAX_TRACK; i++)
1021 cur_idx = (track_ridx + i) & MAX_TRACK_MASK;
1022 if (!clear_track_info(&tracks[cur_idx]))
1023 return false;
1026 return true;
1029 static bool audio_loadcodec(bool start_play)
1031 int prev_track;
1032 char codec_path[MAX_PATH]; /* Full path to codec */
1033 const struct mp3entry *id3, *prev_id3;
1035 if (tracks[track_widx].id3_hid < 0) {
1036 return false;
1039 id3 = bufgetid3(tracks[track_widx].id3_hid);
1040 if (!id3)
1041 return false;
1043 const char *codec_fn = get_codec_filename(id3->codectype);
1044 if (codec_fn == NULL)
1045 return false;
1047 tracks[track_widx].codec_hid = -1;
1049 if (start_play)
1051 /* Load the codec directly from disk and save some memory. */
1052 track_ridx = track_widx;
1053 ci.filesize = CUR_TI->filesize;
1054 ci.id3 = thistrack_id3;
1055 ci.taginfo_ready = &CUR_TI->taginfo_ready;
1056 ci.curpos = 0;
1057 LOGFQUEUE("codec > codec Q_CODEC_LOAD_DISK");
1058 queue_post(&codec_queue, Q_CODEC_LOAD_DISK, (intptr_t)codec_fn);
1059 return true;
1061 else
1063 /* If we already have another track than this one buffered */
1064 if (track_widx != track_ridx)
1066 prev_track = (track_widx - 1) & MAX_TRACK_MASK;
1068 id3 = bufgetid3(tracks[track_widx].id3_hid);
1069 prev_id3 = bufgetid3(tracks[prev_track].id3_hid);
1071 /* If the previous codec is the same as this one, there is no need
1072 * to put another copy of it on the file buffer */
1073 if (id3 && prev_id3 &&
1074 get_codec_base_type(id3->codectype) ==
1075 get_codec_base_type(prev_id3->codectype)
1076 && audio_codec_loaded)
1078 logf("Reusing prev. codec");
1079 return true;
1084 codec_get_full_path(codec_path, codec_fn);
1086 tracks[track_widx].codec_hid = bufopen(codec_path, 0, TYPE_CODEC, NULL);
1087 if (tracks[track_widx].codec_hid < 0)
1088 return false;
1090 logf("Loaded codec");
1092 return true;
1095 /* Load metadata for the next track (with bufopen). The rest of the track
1096 loading will be handled by audio_finish_load_track once the metadata has been
1097 actually loaded by the buffering thread. */
1098 static bool audio_load_track(size_t offset, bool start_play)
1100 const char *trackname;
1101 int fd = -1;
1103 if (track_load_started) {
1104 /* There is already a track load in progress, so track_widx hasn't been
1105 incremented yet. Loading another track would overwrite the one that
1106 hasn't finished loading. */
1107 logf("audio_load_track(): a track load is already in progress");
1108 return false;
1111 start_play_g = start_play; /* will be read by audio_finish_load_track */
1113 /* Stop buffer filling if there is no free track entries.
1114 Don't fill up the last track entry (we wan't to store next track
1115 metadata there). */
1116 if (!audio_free_track_count())
1118 logf("No free tracks");
1119 return false;
1122 last_peek_offset++;
1123 tracks[track_widx].taginfo_ready = false;
1125 logf("Buffering track: r%d/w%d", track_ridx, track_widx);
1126 /* Get track name from current playlist read position. */
1127 while ((trackname = playlist_peek(last_peek_offset)) != NULL)
1129 /* Handle broken playlists. */
1130 fd = open(trackname, O_RDONLY);
1131 if (fd < 0)
1133 logf("Open failed");
1134 /* Skip invalid entry from playlist. */
1135 playlist_skip_entry(NULL, last_peek_offset);
1137 else
1138 break;
1141 if (!trackname)
1143 logf("End-of-playlist");
1144 memset(&unbuffered_id3, 0, sizeof(struct mp3entry));
1145 filling = STATE_END_OF_PLAYLIST;
1147 if (thistrack_id3->length == 0 && thistrack_id3->filesize == 0)
1149 /* Stop playback if no valid track was found. */
1150 audio_stop_playback();
1153 return false;
1156 tracks[track_widx].filesize = filesize(fd);
1158 if (offset > tracks[track_widx].filesize)
1159 offset = 0;
1161 /* Set default values */
1162 if (start_play)
1164 buf_set_watermark(filebuflen/2);
1165 dsp_configure(ci.dsp, DSP_RESET, 0);
1166 playlist_update_resume_info(audio_current_track());
1169 /* Get track metadata if we don't already have it. */
1170 if (tracks[track_widx].id3_hid < 0)
1172 tracks[track_widx].id3_hid = bufopen(trackname, 0, TYPE_ID3, NULL);
1174 if (tracks[track_widx].id3_hid < 0)
1176 /* Buffer is full. */
1177 get_metadata(&unbuffered_id3, fd, trackname);
1178 last_peek_offset--;
1179 close(fd);
1180 logf("buffer is full for now (get metadata)");
1181 filling = STATE_FULL;
1182 return false;
1185 if (track_widx == track_ridx)
1187 /* TODO: Superfluos buffering call? */
1188 buf_request_buffer_handle(tracks[track_widx].id3_hid);
1189 struct mp3entry *id3 = bufgetid3(tracks[track_widx].id3_hid);
1190 if (id3)
1192 copy_mp3entry(thistrack_id3, id3);
1193 thistrack_id3->offset = offset;
1195 else
1196 memset(thistrack_id3, 0, sizeof(struct mp3entry));
1199 if (start_play)
1201 playlist_update_resume_info(audio_current_track());
1205 close(fd);
1206 track_load_started = true; /* Remember that we've started loading a track */
1207 return true;
1210 /* Second part of the track loading: We now have the metadata available, so we
1211 can load the codec, the album art and finally the audio data.
1212 This is called on the audio thread after the buffering thread calls the
1213 buffering_handle_finished_callback callback. */
1214 static void audio_finish_load_track(void)
1216 size_t file_offset = 0;
1217 size_t offset = 0;
1218 bool start_play = start_play_g;
1220 track_load_started = false;
1222 if (tracks[track_widx].id3_hid < 0) {
1223 logf("No metadata");
1224 return;
1227 struct mp3entry *track_id3;
1229 if (track_widx == track_ridx)
1230 track_id3 = thistrack_id3;
1231 else
1232 track_id3 = bufgetid3(tracks[track_widx].id3_hid);
1234 if (track_id3->length == 0 && track_id3->filesize == 0)
1236 logf("audio_finish_load_track: invalid metadata");
1238 /* Invalid metadata */
1239 bufclose(tracks[track_widx].id3_hid);
1240 tracks[track_widx].id3_hid = -1;
1242 /* Skip invalid entry from playlist. */
1243 playlist_skip_entry(NULL, last_peek_offset--);
1245 /* load next track */
1246 LOGFQUEUE("audio > audio Q_AUDIO_FILL_BUFFER %d", (int)start_play);
1247 queue_post(&audio_queue, Q_AUDIO_FILL_BUFFER, start_play);
1249 return;
1251 /* Try to load a cuesheet for the track */
1252 if (curr_cue)
1254 char cuepath[MAX_PATH];
1255 if (look_for_cuesheet_file(track_id3->path, cuepath))
1257 void *temp;
1258 tracks[track_widx].cuesheet_hid =
1259 bufalloc(NULL, sizeof(struct cuesheet), TYPE_CUESHEET);
1260 if (tracks[track_widx].cuesheet_hid >= 0)
1262 bufgetdata(tracks[track_widx].cuesheet_hid,
1263 sizeof(struct cuesheet), &temp);
1264 struct cuesheet *cuesheet = (struct cuesheet*)temp;
1265 if (!parse_cuesheet(cuepath, cuesheet))
1267 bufclose(tracks[track_widx].cuesheet_hid);
1268 track_id3->cuesheet = NULL;
1273 #ifdef HAVE_ALBUMART
1275 int i;
1276 char aa_path[MAX_PATH];
1277 FOREACH_ALBUMART(i)
1279 /* albumart_slots may change during a yield of bufopen,
1280 * but that's no problem */
1281 if (tracks[track_widx].aa_hid[i] >= 0 || !albumart_slots[i].used)
1282 continue;
1283 /* find_albumart will error out if the wps doesn't have AA */
1284 if (find_albumart(track_id3, aa_path, sizeof(aa_path),
1285 &(albumart_slots[i].dim)))
1287 int aa_hid = bufopen(aa_path, 0, TYPE_BITMAP,
1288 &(albumart_slots[i].dim));
1290 if(aa_hid == ERR_BUFFER_FULL)
1292 filling = STATE_FULL;
1293 logf("buffer is full for now (get album art)");
1294 return; /* No space for track's album art, not an error */
1296 else if (aa_hid < 0)
1298 /* another error, ignore AlbumArt */
1299 logf("Album art loading failed");
1301 tracks[track_widx].aa_hid[i] = aa_hid;
1306 #endif
1308 /* Load the codec. */
1309 if (!audio_loadcodec(start_play))
1311 if (tracks[track_widx].codec_hid == ERR_BUFFER_FULL)
1313 /* No space for codec on buffer, not an error */
1314 filling = STATE_FULL;
1315 return;
1318 /* This is an error condition, either no codec was found, or reading
1319 * the codec file failed part way through, either way, skip the track */
1320 /* FIXME: We should not use splashf from audio thread! */
1321 splashf(HZ*2, "No codec for: %s", track_id3->path);
1322 /* Skip invalid entry from playlist. */
1323 playlist_skip_entry(NULL, last_peek_offset);
1324 return;
1327 track_id3->elapsed = 0;
1328 offset = track_id3->offset;
1330 enum data_type type = TYPE_PACKET_AUDIO;
1332 switch (track_id3->codectype) {
1333 case AFMT_MPA_L1:
1334 case AFMT_MPA_L2:
1335 case AFMT_MPA_L3:
1336 if (offset > 0) {
1337 file_offset = offset;
1338 track_id3->offset = offset;
1340 break;
1342 case AFMT_WAVPACK:
1343 if (offset > 0) {
1344 file_offset = offset;
1345 track_id3->offset = offset;
1346 track_id3->elapsed = track_id3->length / 2;
1348 break;
1350 case AFMT_OGG_VORBIS:
1351 case AFMT_SPEEX:
1352 case AFMT_FLAC:
1353 case AFMT_PCM_WAV:
1354 case AFMT_A52:
1355 case AFMT_MP4_AAC:
1356 case AFMT_MPC:
1357 case AFMT_APE:
1358 case AFMT_WMA:
1359 if (offset > 0)
1360 track_id3->offset = offset;
1361 break;
1363 case AFMT_NSF:
1364 case AFMT_SPC:
1365 case AFMT_SID:
1366 logf("Loading atomic %d",track_id3->codectype);
1367 type = TYPE_ATOMIC_AUDIO;
1368 break;
1371 logf("load track: %s", track_id3->path);
1373 if (file_offset > AUDIO_REBUFFER_GUESS_SIZE)
1374 file_offset -= AUDIO_REBUFFER_GUESS_SIZE;
1375 else if (track_id3->first_frame_offset)
1376 file_offset = track_id3->first_frame_offset;
1377 else
1378 file_offset = 0;
1380 tracks[track_widx].audio_hid = bufopen(track_id3->path, file_offset, type,
1381 NULL);
1383 /* No space left, not an error */
1384 if (tracks[track_widx].audio_hid == ERR_BUFFER_FULL)
1386 filling = STATE_FULL;
1387 logf("buffer is full for now (load audio)");
1388 return;
1390 else if (tracks[track_widx].audio_hid < 0)
1392 /* another error, do not continue either */
1393 logf("Could not add audio data handle");
1394 return;
1397 /* All required data is now available for the codec. */
1398 tracks[track_widx].taginfo_ready = true;
1400 if (start_play)
1402 ci.curpos=file_offset;
1403 buf_request_buffer_handle(tracks[track_widx].audio_hid);
1406 track_widx = (track_widx + 1) & MAX_TRACK_MASK;
1408 send_event(PLAYBACK_EVENT_TRACK_BUFFER, track_id3);
1410 /* load next track */
1411 LOGFQUEUE("audio > audio Q_AUDIO_FILL_BUFFER");
1412 queue_post(&audio_queue, Q_AUDIO_FILL_BUFFER, 0);
1414 return;
1417 static void audio_fill_file_buffer(bool start_play, size_t offset)
1419 trigger_cpu_boost();
1421 /* No need to rebuffer if there are track skips pending,
1422 * however don't cancel buffering on skipping while filling. */
1423 if (ci.new_track != 0 && filling != STATE_FILLING)
1424 return;
1425 filling = STATE_FILLING;
1427 /* Must reset the buffer before use if trashed or voice only - voice
1428 file size shouldn't have changed so we can go straight from
1429 AUDIOBUF_STATE_VOICED_ONLY to AUDIOBUF_STATE_INITIALIZED */
1430 if (buffer_state != AUDIOBUF_STATE_INITIALIZED)
1431 audio_reset_buffer();
1433 logf("Starting buffer fill");
1435 if (!start_play)
1436 audio_clear_track_entries();
1438 /* Save the current resume position once. */
1439 playlist_update_resume_info(audio_current_track());
1441 audio_load_track(offset, start_play);
1444 static void audio_rebuffer(void)
1446 logf("Forcing rebuffer");
1448 clear_track_info(CUR_TI);
1450 /* Reset track pointers */
1451 track_widx = track_ridx;
1452 audio_clear_track_entries();
1454 /* Reset a possibly interrupted track load */
1455 track_load_started = false;
1457 /* Fill the buffer */
1458 last_peek_offset = -1;
1459 ci.curpos = 0;
1461 if (!CUR_TI->taginfo_ready)
1462 memset(thistrack_id3, 0, sizeof(struct mp3entry));
1464 audio_fill_file_buffer(false, 0);
1467 /* Called on request from the codec to get a new track. This is the codec part
1468 of the track transition. */
1469 static int audio_check_new_track(void)
1471 int track_count = audio_track_count();
1472 int old_track_ridx = track_ridx;
1473 int i, idx;
1474 bool forward;
1475 struct mp3entry *temp = thistrack_id3;
1477 /* Now it's good time to send track finish events. */
1478 send_event(PLAYBACK_EVENT_TRACK_FINISH, thistrack_id3);
1479 /* swap the mp3entry pointers */
1480 thistrack_id3 = othertrack_id3;
1481 othertrack_id3 = temp;
1482 ci.id3 = thistrack_id3;
1483 memset(thistrack_id3, 0, sizeof(struct mp3entry));
1485 if (dir_skip)
1487 dir_skip = false;
1488 /* regardless of the return value we need to rebuffer.
1489 if it fails the old playlist will resume, else the
1490 next dir will start playing */
1491 playlist_next_dir(ci.new_track);
1492 ci.new_track = 0;
1493 audio_rebuffer();
1494 goto skip_done;
1497 if (new_playlist)
1498 ci.new_track = 0;
1500 /* If the playlist isn't that big */
1501 if (automatic_skip)
1503 while (!playlist_check(ci.new_track))
1505 if (ci.new_track >= 0)
1507 LOGFQUEUE("audio >|= codec Q_CODEC_REQUEST_FAILED");
1508 return Q_CODEC_REQUEST_FAILED;
1510 ci.new_track++;
1514 /* Update the playlist */
1515 last_peek_offset -= ci.new_track;
1517 if (playlist_next(ci.new_track) < 0)
1519 LOGFQUEUE("audio >|= codec Q_CODEC_REQUEST_FAILED");
1520 return Q_CODEC_REQUEST_FAILED;
1523 if (new_playlist)
1525 ci.new_track = 1;
1526 new_playlist = false;
1529 /* Save a pointer to the old track to allow later clearing */
1530 prev_ti = CUR_TI;
1532 for (i = 0; i < ci.new_track; i++)
1534 idx = (track_ridx + i) & MAX_TRACK_MASK;
1535 struct mp3entry *id3 = bufgetid3(tracks[idx].id3_hid);
1536 ssize_t offset = buf_handle_offset(tracks[idx].audio_hid);
1537 if (!id3 || offset < 0 || (unsigned)offset > id3->first_frame_offset)
1539 /* We don't have all the audio data for that track, so clear it,
1540 but keep the metadata. */
1541 if (tracks[idx].audio_hid >= 0 && bufclose(tracks[idx].audio_hid))
1543 tracks[idx].audio_hid = -1;
1544 tracks[idx].filesize = 0;
1549 /* Move to the new track */
1550 track_ridx = (track_ridx + ci.new_track) & MAX_TRACK_MASK;
1553 if (automatic_skip)
1555 wps_offset = -ci.new_track;
1558 /* If it is not safe to even skip this many track entries */
1559 if (ci.new_track >= track_count || ci.new_track <= track_count - MAX_TRACK)
1561 ci.new_track = 0;
1562 audio_rebuffer();
1563 goto skip_done;
1566 forward = ci.new_track > 0;
1567 ci.new_track = 0;
1569 /* If the target track is clearly not in memory */
1570 if (CUR_TI->filesize == 0 || !CUR_TI->taginfo_ready)
1572 audio_rebuffer();
1573 goto skip_done;
1576 /* When skipping backwards, it is possible that we've found a track that's
1577 * buffered, but which is around the track-wrap and therefore not the track
1578 * we are looking for */
1579 if (!forward)
1581 int cur_idx = track_ridx;
1582 bool taginfo_ready = true;
1583 /* We've wrapped the buffer backwards if new > old */
1584 bool wrap = track_ridx > old_track_ridx;
1586 while (1)
1588 cur_idx = (cur_idx + 1) & MAX_TRACK_MASK;
1590 /* if we've advanced past the wrap when cur_idx is zeroed */
1591 if (!cur_idx)
1592 wrap = false;
1594 /* if we aren't still on the wrap and we've caught the old track */
1595 if (!(wrap || cur_idx < old_track_ridx))
1596 break;
1598 /* If we hit a track in between without valid tag info, bail */
1599 if (!tracks[cur_idx].taginfo_ready)
1601 taginfo_ready = false;
1602 break;
1605 if (!taginfo_ready)
1607 audio_rebuffer();
1611 skip_done:
1612 audio_update_trackinfo();
1613 LOGFQUEUE("audio >|= codec Q_CODEC_REQUEST_COMPLETE");
1614 return Q_CODEC_REQUEST_COMPLETE;
1617 unsigned long audio_prev_elapsed(void)
1619 return prev_track_elapsed;
1622 void audio_set_prev_elapsed(unsigned long setting)
1624 prev_track_elapsed = setting;
1627 static void audio_stop_codec_flush(void)
1629 ci.stop_codec = true;
1630 pcmbuf_pause(true);
1632 while (audio_codec_loaded)
1633 yield();
1635 /* If the audio codec is not loaded any more, and the audio is still
1636 * playing, it is now and _only_ now safe to call this function from the
1637 * audio thread */
1638 if (pcm_is_playing())
1640 pcmbuf_play_stop();
1641 pcm_play_lock();
1642 queue_clear(&pcmbuf_queue);
1643 pcm_play_unlock();
1645 pcmbuf_pause(paused);
1648 static void audio_stop_playback(void)
1650 if (playing)
1652 /* If we were playing, save resume information */
1653 struct mp3entry *id3 = NULL;
1655 if (!ci.stop_codec)
1657 /* Set this early, the outside code yields and may allow the codec
1658 to try to wait for a reply on a buffer wait */
1659 ci.stop_codec = true;
1660 id3 = audio_current_track();
1663 /* Save the current playing spot, or NULL if the playlist has ended */
1664 playlist_update_resume_info(id3);
1666 /* TODO: Create auto bookmark too? */
1668 prev_track_elapsed = othertrack_id3->elapsed;
1670 remove_event(BUFFER_EVENT_BUFFER_LOW, buffering_low_buffer_callback);
1673 audio_stop_codec_flush();
1674 paused = false;
1675 playing = false;
1676 track_load_started = false;
1678 filling = STATE_IDLE;
1680 /* Mark all entries null. */
1681 audio_clear_track_entries();
1683 /* Close all tracks */
1684 audio_release_tracks();
1687 static void audio_play_start(size_t offset)
1689 int i;
1691 #if INPUT_SRC_CAPS != 0
1692 audio_set_input_source(AUDIO_SRC_PLAYBACK, SRCF_PLAYBACK);
1693 audio_set_output_source(AUDIO_SRC_PLAYBACK);
1694 #endif
1696 /* Wait for any previously playing audio to flush - TODO: Not necessary? */
1697 paused = false;
1698 audio_stop_codec_flush();
1700 playing = true;
1701 track_load_started = false;
1703 ci.new_track = 0;
1704 ci.seek_time = 0;
1705 wps_offset = 0;
1707 sound_set_volume(global_settings.volume);
1708 track_widx = track_ridx = 0;
1710 /* Clear all track entries. */
1711 for (i = 0; i < MAX_TRACK; i++) {
1712 clear_track_info(&tracks[i]);
1715 last_peek_offset = -1;
1717 /* Officially playing */
1718 queue_reply(&audio_queue, 1);
1720 audio_fill_file_buffer(true, offset);
1722 add_event(BUFFER_EVENT_BUFFER_LOW, false, buffering_low_buffer_callback);
1724 LOGFQUEUE("audio > audio Q_AUDIO_TRACK_CHANGED");
1725 queue_post(&audio_queue, Q_AUDIO_TRACK_CHANGED, 0);
1729 /* Invalidates all but currently playing track. */
1730 static void audio_invalidate_tracks(void)
1732 if (audio_have_tracks())
1734 last_peek_offset = 0;
1735 track_widx = track_ridx;
1737 /* Mark all other entries null (also buffered wrong metadata). */
1738 audio_clear_track_entries();
1740 track_widx = (track_widx + 1) & MAX_TRACK_MASK;
1742 audio_fill_file_buffer(false, 0);
1746 static void audio_new_playlist(void)
1748 /* Prepare to start a new fill from the beginning of the playlist */
1749 last_peek_offset = -1;
1750 if (audio_have_tracks())
1752 if (paused)
1753 skipped_during_pause = true;
1754 track_widx = track_ridx;
1755 audio_clear_track_entries();
1757 track_widx = (track_widx + 1) & MAX_TRACK_MASK;
1759 /* Mark the current track as invalid to prevent skipping back to it */
1760 CUR_TI->taginfo_ready = false;
1763 /* Signal the codec to initiate a track change forward */
1764 new_playlist = true;
1765 ci.new_track = 1;
1767 /* Officially playing */
1768 queue_reply(&audio_queue, 1);
1770 audio_fill_file_buffer(false, 0);
1773 /* Called on manual track skip */
1774 static void audio_initiate_track_change(long direction)
1776 logf("audio_initiate_track_change(%ld)", direction);
1778 ci.new_track += direction;
1779 wps_offset -= direction;
1780 if (paused)
1781 skipped_during_pause = true;
1784 /* Called on manual dir skip */
1785 static void audio_initiate_dir_change(long direction)
1787 dir_skip = true;
1788 ci.new_track = direction;
1789 if (paused)
1790 skipped_during_pause = true;
1793 /* Called when PCM track change is complete */
1794 static void audio_finalise_track_change(void)
1796 logf("audio_finalise_track_change");
1798 if (automatic_skip)
1800 wps_offset = 0;
1801 automatic_skip = false;
1803 /* Invalidate prevtrack_id3 */
1804 memset(othertrack_id3, 0, sizeof(struct mp3entry));
1806 if (prev_ti && prev_ti->audio_hid < 0)
1808 /* No audio left so we clear all the track info. */
1809 clear_track_info(prev_ti);
1812 send_event(PLAYBACK_EVENT_TRACK_CHANGE, thistrack_id3);
1813 playlist_update_resume_info(audio_current_track());
1817 * Layout audio buffer as follows - iram buffer depends on target:
1818 * [|SWAP:iram][|TALK]|FILE|GUARD|PCM|[SWAP:dram[|iram]|]
1820 static void audio_reset_buffer(void)
1822 /* see audio_get_recording_buffer if this is modified */
1823 logf("audio_reset_buffer");
1825 /* If the setup of anything allocated before the file buffer is
1826 changed, do check the adjustments after the buffer_alloc call
1827 as it will likely be affected and need sliding over */
1829 /* Initially set up file buffer as all space available */
1830 malloc_buf = audiobuf + talk_get_bufsize();
1831 /* Align the malloc buf to line size. Especially important to cf
1832 targets that do line reads/writes. */
1833 malloc_buf = (unsigned char *)(((uintptr_t)malloc_buf + 15) & ~15);
1834 filebuf = malloc_buf; /* filebuf line align implied */
1835 filebuflen = audiobufend - filebuf;
1837 filebuflen &= ~15;
1839 /* Subtract whatever the pcm buffer says it used plus the guard buffer */
1840 const size_t pcmbuf_size = pcmbuf_init(filebuf + filebuflen) +GUARD_BUFSIZE;
1842 #ifdef DEBUG
1843 if(pcmbuf_size > filebuflen)
1844 panicf("Not enough memory for pcmbuf_init() : %d > %d",
1845 (int)pcmbuf_size, (int)filebuflen);
1846 #endif
1848 filebuflen -= pcmbuf_size;
1850 /* Make sure filebuflen is a longword multiple after adjustment - filebuf
1851 will already be line aligned */
1852 filebuflen &= ~3;
1854 buffering_reset(filebuf, filebuflen);
1856 /* Clear any references to the file buffer */
1857 buffer_state = AUDIOBUF_STATE_INITIALIZED;
1859 #if defined(ROCKBOX_HAS_LOGF) && defined(LOGF_ENABLE)
1860 /* Make sure everything adds up - yes, some info is a bit redundant but
1861 aids viewing and the sumation of certain variables should add up to
1862 the location of others. */
1864 size_t pcmbufsize;
1865 const unsigned char *pcmbuf = pcmbuf_get_meminfo(&pcmbufsize);
1866 logf("mabuf: %08X", (unsigned)malloc_buf);
1867 logf("fbuf: %08X", (unsigned)filebuf);
1868 logf("fbufe: %08X", (unsigned)(filebuf + filebuflen));
1869 logf("gbuf: %08X", (unsigned)(filebuf + filebuflen));
1870 logf("gbufe: %08X", (unsigned)(filebuf + filebuflen + GUARD_BUFSIZE));
1871 logf("pcmb: %08X", (unsigned)pcmbuf);
1872 logf("pcmbe: %08X", (unsigned)(pcmbuf + pcmbufsize));
1874 #endif
1877 static void audio_thread(void)
1879 struct queue_event ev;
1881 pcm_postinit();
1883 audio_thread_ready = true;
1885 while (1)
1887 if (filling != STATE_FILLING && filling != STATE_IDLE) {
1888 /* End of buffering, let's calculate the watermark and unboost */
1889 set_filebuf_watermark();
1890 cancel_cpu_boost();
1893 if (!pcmbuf_queue_scan(&ev))
1894 queue_wait_w_tmo(&audio_queue, &ev, HZ/2);
1896 switch (ev.id) {
1898 case Q_AUDIO_FILL_BUFFER:
1899 LOGFQUEUE("audio < Q_AUDIO_FILL_BUFFER %d", (int)ev.data);
1900 audio_fill_file_buffer((bool)ev.data, 0);
1901 break;
1903 case Q_AUDIO_FINISH_LOAD:
1904 LOGFQUEUE("audio < Q_AUDIO_FINISH_LOAD");
1905 audio_finish_load_track();
1906 buf_set_base_handle(CUR_TI->audio_hid);
1907 break;
1909 case Q_AUDIO_PLAY:
1910 LOGFQUEUE("audio < Q_AUDIO_PLAY");
1911 if (playing && ev.data <= 0)
1912 audio_new_playlist();
1913 else
1915 audio_stop_playback();
1916 audio_play_start((size_t)ev.data);
1918 break;
1920 case Q_AUDIO_STOP:
1921 LOGFQUEUE("audio < Q_AUDIO_STOP");
1922 if (playing)
1923 audio_stop_playback();
1924 if (ev.data != 0)
1925 queue_clear(&audio_queue);
1926 break;
1928 case Q_AUDIO_PAUSE:
1929 LOGFQUEUE("audio < Q_AUDIO_PAUSE");
1930 if (!(bool) ev.data && skipped_during_pause
1931 #ifdef HAVE_CROSSFADE
1932 && !pcmbuf_is_crossfade_active()
1933 #endif
1935 pcmbuf_play_stop(); /* Flush old track on resume after skip */
1936 skipped_during_pause = false;
1937 if (!playing)
1938 break;
1939 pcmbuf_pause((bool)ev.data);
1940 paused = (bool)ev.data;
1941 break;
1943 case Q_AUDIO_SKIP:
1944 LOGFQUEUE("audio < Q_AUDIO_SKIP");
1945 audio_initiate_track_change((long)ev.data);
1946 break;
1948 case Q_AUDIO_PRE_FF_REWIND:
1949 LOGFQUEUE("audio < Q_AUDIO_PRE_FF_REWIND");
1950 if (!playing)
1951 break;
1952 pcmbuf_pause(true);
1953 break;
1955 case Q_AUDIO_FF_REWIND:
1956 LOGFQUEUE("audio < Q_AUDIO_FF_REWIND");
1957 if (!playing)
1958 break;
1959 if (automatic_skip)
1961 /* An automatic track skip is in progress. Finalize it,
1962 then go back to the previous track */
1963 audio_finalise_track_change();
1964 ci.new_track = -1;
1966 ci.seek_time = (long)ev.data+1;
1967 break;
1969 case Q_AUDIO_CHECK_NEW_TRACK:
1970 LOGFQUEUE("audio < Q_AUDIO_CHECK_NEW_TRACK");
1971 queue_reply(&audio_queue, audio_check_new_track());
1972 break;
1974 case Q_AUDIO_DIR_SKIP:
1975 LOGFQUEUE("audio < Q_AUDIO_DIR_SKIP");
1976 audio_initiate_dir_change(ev.data);
1977 break;
1979 case Q_AUDIO_FLUSH:
1980 LOGFQUEUE("audio < Q_AUDIO_FLUSH");
1981 audio_invalidate_tracks();
1982 break;
1984 case Q_AUDIO_TRACK_CHANGED:
1985 /* PCM track change done */
1986 LOGFQUEUE("audio < Q_AUDIO_TRACK_CHANGED");
1987 audio_finalise_track_change();
1988 break;
1989 #ifndef SIMULATOR
1990 case SYS_USB_CONNECTED:
1991 LOGFQUEUE("audio < SYS_USB_CONNECTED");
1992 if (playing)
1993 audio_stop_playback();
1994 #ifdef PLAYBACK_VOICE
1995 voice_stop();
1996 #endif
1997 usb_acknowledge(SYS_USB_CONNECTED_ACK);
1998 usb_wait_for_disconnect(&audio_queue);
2000 /* Mark all entries null. */
2001 audio_clear_track_entries();
2003 /* release tracks to make sure all handles are closed */
2004 audio_release_tracks();
2005 break;
2006 #endif
2008 case SYS_TIMEOUT:
2009 LOGFQUEUE_SYS_TIMEOUT("audio < SYS_TIMEOUT");
2010 break;
2012 default:
2013 /* LOGFQUEUE("audio < default : %08lX", ev.id); */
2014 break;
2015 } /* end switch */
2016 } /* end while */
2019 /* Initialize the audio system - called from init() in main.c.
2020 * Last function because of all the references to internal symbols
2022 void audio_init(void)
2024 unsigned int audio_thread_id;
2026 /* Can never do this twice */
2027 if (audio_is_initialized)
2029 logf("audio: already initialized");
2030 return;
2033 logf("audio: initializing");
2035 /* Initialize queues before giving control elsewhere in case it likes
2036 to send messages. Thread creation will be delayed however so nothing
2037 starts running until ready if something yields such as talk_init. */
2038 queue_init(&audio_queue, true);
2039 queue_init(&codec_queue, false);
2040 queue_init(&pcmbuf_queue, false);
2042 pcm_init();
2044 codec_init_codec_api();
2046 thistrack_id3 = &mp3entry_buf[0];
2047 othertrack_id3 = &mp3entry_buf[1];
2049 /* cuesheet support */
2050 if (global_settings.cuesheet)
2051 curr_cue = (struct cuesheet*)buffer_alloc(sizeof(struct cuesheet));
2053 /* initialize the buffer */
2054 filebuf = audiobuf;
2056 /* audio_reset_buffer must to know the size of voice buffer so init
2057 talk first */
2058 talk_init();
2060 make_codec_thread();
2062 audio_thread_id = create_thread(audio_thread, audio_stack,
2063 sizeof(audio_stack), CREATE_THREAD_FROZEN,
2064 audio_thread_name IF_PRIO(, PRIORITY_USER_INTERFACE)
2065 IF_COP(, CPU));
2067 queue_enable_queue_send(&audio_queue, &audio_queue_sender_list,
2068 audio_thread_id);
2070 #ifdef PLAYBACK_VOICE
2071 voice_thread_init();
2072 #endif
2074 #ifdef HAVE_CROSSFADE
2075 /* Set crossfade setting for next buffer init which should be about... */
2076 pcmbuf_request_crossfade_enable(global_settings.crossfade);
2077 #endif
2079 /* initialize the buffering system */
2081 buffering_init();
2082 /* ...now! Set up the buffers */
2083 audio_reset_buffer();
2085 int i;
2086 for(i = 0; i < MAX_TRACK; i++)
2088 tracks[i].audio_hid = -1;
2089 tracks[i].id3_hid = -1;
2090 tracks[i].codec_hid = -1;
2091 tracks[i].cuesheet_hid = -1;
2093 #ifdef HAVE_ALBUMART
2094 FOREACH_ALBUMART(i)
2096 int j;
2097 for (j = 0; j < MAX_TRACK; j++)
2099 tracks[j].aa_hid[i] = -1;
2102 #endif
2104 add_event(BUFFER_EVENT_REBUFFER, false, buffering_handle_rebuffer_callback);
2105 add_event(BUFFER_EVENT_FINISHED, false, buffering_handle_finished_callback);
2107 /* Probably safe to say */
2108 audio_is_initialized = true;
2110 sound_settings_apply();
2111 #ifdef HAVE_DISK_STORAGE
2112 audio_set_buffer_margin(global_settings.buffer_margin);
2113 #endif
2115 /* it's safe to let the threads run now */
2116 #ifdef PLAYBACK_VOICE
2117 voice_thread_resume();
2118 #endif
2119 thread_thaw(codec_thread_id);
2120 thread_thaw(audio_thread_id);
2122 } /* audio_init */
2124 bool audio_is_thread_ready(void)
2126 return audio_thread_ready;
2129 size_t audio_get_filebuflen(void)
2131 return filebuflen;
2134 int get_audio_hid()
2136 return CUR_TI->audio_hid;
2139 int *get_codec_hid()
2141 return &tracks[track_ridx].codec_hid;