Forgot to remove wps_data.remove_wps in checkwps too.
[kugel-rb.git] / apps / playback.c
blobd3c4b46a99a30ce88ffd02d18b38301669b7ecd9
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 static int buffer_state = AUDIOBUF_STATE_TRASHED; /* Buffer state */
121 /* These are used to store the current and next (or prev if the current is the last)
122 * mp3entry's in a round-robin system. This guarentees that the pointer returned
123 * by audio_current/next_track will be valid for the full duration of the
124 * currently playing track */
125 static struct mp3entry mp3entry_buf[2];
126 struct mp3entry *thistrack_id3, /* the currently playing track */
127 *othertrack_id3; /* prev track during track-change-transition, or end of playlist,
128 * next track otherwise */
129 static struct mp3entry unbuffered_id3; /* the id3 for the first unbuffered track */
131 /* for cuesheet support */
132 static struct cuesheet *curr_cue = NULL;
135 #define MAX_MULTIPLE_AA 2
137 #ifdef HAVE_ALBUMART
138 static struct albumart_slot {
139 struct dim dim; /* holds width, height of the albumart */
140 int used; /* counter, increments if something uses it */
141 } albumart_slots[MAX_MULTIPLE_AA];
143 #define FOREACH_ALBUMART(i) for(i = 0;i < MAX_MULTIPLE_AA; i++)
144 #endif
147 #define MAX_TRACK 128
148 #define MAX_TRACK_MASK (MAX_TRACK-1)
150 /* Track info structure about songs in the file buffer (A/C-) */
151 static struct track_info {
152 int audio_hid; /* The ID for the track's buffer handle */
153 int id3_hid; /* The ID for the track's metadata handle */
154 int codec_hid; /* The ID for the track's codec handle */
155 #ifdef HAVE_ALBUMART
156 int aa_hid[MAX_MULTIPLE_AA];/* The ID for the track's album art handle */
157 #endif
158 int cuesheet_hid; /* The ID for the track's parsed cueesheet handle */
160 size_t filesize; /* File total length */
162 bool taginfo_ready; /* Is metadata read */
164 } tracks[MAX_TRACK];
166 static volatile int track_ridx = 0; /* Track being decoded (A/C-) */
167 static int track_widx = 0; /* Track being buffered (A) */
168 #define CUR_TI (&tracks[track_ridx]) /* Playing track info pointer (A/C-) */
170 static struct track_info *prev_ti = NULL; /* Pointer to the previously played
171 track */
173 /* Information used only for filling the buffer */
174 /* Playlist steps from playing track to next track to be buffered (A) */
175 static int last_peek_offset = 0;
177 /* Scrobbler support */
178 static unsigned long prev_track_elapsed = 0; /* Previous track elapsed time (C/A-)*/
180 /* Track change controls */
181 bool automatic_skip = false; /* Who initiated in-progress skip? (C/A-) */
182 extern bool track_transition; /* Are we in a track transition? */
183 static bool dir_skip = false; /* Is a directory skip pending? (A) */
184 static bool new_playlist = false; /* Are we starting a new playlist? (A) */
185 static int wps_offset = 0; /* Pending track change offset, to keep WPS responsive (A) */
186 static bool skipped_during_pause = false; /* Do we need to clear the PCM buffer when playback resumes (A) */
188 static bool start_play_g = false; /* Used by audio_load_track to notify
189 audio_finish_load_track about start_play */
191 /* True when a track load is in progress, i.e. audio_load_track() has returned
192 * but audio_finish_load_track() hasn't been called yet. Used to avoid allowing
193 * audio_load_track() to get called twice in a row, which would cause problems.
195 static bool track_load_started = false;
197 #ifdef HAVE_DISK_STORAGE
198 static size_t buffer_margin = 5; /* Buffer margin aka anti-skip buffer (A/C-) */
199 #endif
201 /* Event queues */
202 struct event_queue audio_queue SHAREDBSS_ATTR;
203 struct event_queue codec_queue SHAREDBSS_ATTR;
204 static struct event_queue pcmbuf_queue SHAREDBSS_ATTR;
206 extern struct codec_api ci;
207 extern unsigned int codec_thread_id;
209 /* Multiple threads */
210 /* Set the watermark to trigger buffer fill (A/C) */
211 static void set_filebuf_watermark(void);
213 /* Audio thread */
214 static struct queue_sender_list audio_queue_sender_list SHAREDBSS_ATTR;
215 static long audio_stack[(DEFAULT_STACK_SIZE + 0x1000)/sizeof(long)];
216 static const char audio_thread_name[] = "audio";
218 static void audio_thread(void);
219 static void audio_initiate_track_change(long direction);
220 static bool audio_have_tracks(void);
221 static void audio_reset_buffer(void);
222 static void audio_stop_playback(void);
225 /**************************************/
227 /* Between the codec and PCM track change, we need to keep updating the
228 "elapsed" value of the previous (to the codec, but current to the
229 user/PCM/WPS) track, so that the progressbar reaches the end.
230 During that transition, the WPS will display othertrack_id3. */
231 void audio_pcmbuf_position_callback(size_t size)
233 /* This is called from an ISR, so be quick */
234 unsigned int time = size * 1000 / 4 / NATIVE_FREQUENCY +
235 othertrack_id3->elapsed;
237 if (time >= othertrack_id3->length)
239 if(track_transition){logf("playback: (callback) track transition false");}
240 track_transition = false;
241 othertrack_id3->elapsed = othertrack_id3->length;
243 else
244 othertrack_id3->elapsed = time;
247 /* Post message from pcmbuf that the end of the previous track
248 * has just been played. */
249 void audio_post_track_change(void)
251 LOGFQUEUE("pcmbuf > pcmbuf Q_AUDIO_TRACK_CHANGED");
252 queue_post(&pcmbuf_queue, Q_AUDIO_TRACK_CHANGED, 0);
255 /* Scan the pcmbuf queue and return true if a message pulled.
256 * Permissible Context(s): Thread
258 static bool pcmbuf_queue_scan(struct queue_event *ev)
260 if (!queue_empty(&pcmbuf_queue))
262 /* Transfer message to audio queue */
263 pcm_play_lock();
264 /* Pull message - never, ever any blocking call! */
265 queue_wait_w_tmo(&pcmbuf_queue, ev, 0);
266 pcm_play_unlock();
267 return true;
270 return false;
273 /* --- Helper functions --- */
275 static struct mp3entry *bufgetid3(int handle_id)
277 if (handle_id < 0)
278 return NULL;
280 struct mp3entry *id3;
281 ssize_t ret = bufgetdata(handle_id, 0, (void *)&id3);
283 if (ret < 0 || ret != sizeof(struct mp3entry))
284 return NULL;
286 return id3;
289 static bool clear_track_info(struct track_info *track)
291 /* bufclose returns true if the handle is not found, or if it is closed
292 * successfully, so these checks are safe on non-existant handles */
293 if (!track)
294 return false;
296 if (track->codec_hid >= 0) {
297 if (bufclose(track->codec_hid))
298 track->codec_hid = -1;
299 else
300 return false;
303 if (track->id3_hid >= 0) {
304 if (bufclose(track->id3_hid))
305 track->id3_hid = -1;
306 else
307 return false;
310 if (track->audio_hid >= 0) {
311 if (bufclose(track->audio_hid))
312 track->audio_hid = -1;
313 else
314 return false;
317 #ifdef HAVE_ALBUMART
319 int i;
320 FOREACH_ALBUMART(i)
322 if (track->aa_hid[i] >= 0) {
323 if (bufclose(track->aa_hid[i]))
324 track->aa_hid[i] = -1;
325 else
326 return false;
330 #endif
332 if (track->cuesheet_hid >= 0) {
333 if (bufclose(track->cuesheet_hid))
334 track->cuesheet_hid = -1;
335 else
336 return false;
339 track->filesize = 0;
340 track->taginfo_ready = false;
342 return true;
345 /* --- External interfaces --- */
347 /* This sends a stop message and the audio thread will dump all it's
348 subsequenct messages */
349 void audio_hard_stop(void)
351 /* Stop playback */
352 LOGFQUEUE("audio >| audio Q_AUDIO_STOP: 1");
353 queue_send(&audio_queue, Q_AUDIO_STOP, 1);
354 #ifdef PLAYBACK_VOICE
355 voice_stop();
356 #endif
359 bool audio_restore_playback(int type)
361 switch (type)
363 case AUDIO_WANT_PLAYBACK:
364 if (buffer_state != AUDIOBUF_STATE_INITIALIZED)
365 audio_reset_buffer();
366 return true;
367 case AUDIO_WANT_VOICE:
368 if (buffer_state == AUDIOBUF_STATE_TRASHED)
369 audio_reset_buffer();
370 return true;
371 default:
372 return false;
376 unsigned char *audio_get_buffer(bool talk_buf, size_t *buffer_size)
378 unsigned char *buf, *end;
380 if (audio_is_initialized)
382 audio_hard_stop();
384 /* else buffer_state will be AUDIOBUF_STATE_TRASHED at this point */
386 /* Reset the buffering thread so that it doesn't try to use the data */
387 buffering_reset(filebuf, filebuflen);
389 if (buffer_size == NULL)
391 /* Special case for talk_init to use since it already knows it's
392 trashed */
393 buffer_state = AUDIOBUF_STATE_TRASHED;
394 return NULL;
397 if (talk_buf || buffer_state == AUDIOBUF_STATE_TRASHED
398 || !talk_voice_required())
400 logf("get buffer: talk, audio");
401 /* Ok to use everything from audiobuf to audiobufend - voice is loaded,
402 the talk buffer is not needed because voice isn't being used, or
403 could be AUDIOBUF_STATE_TRASHED already. If state is
404 AUDIOBUF_STATE_VOICED_ONLY, no problem as long as memory isn't written
405 without the caller knowing what's going on. Changing certain settings
406 may move it to a worse condition but the memory in use by something
407 else will remain undisturbed.
409 if (buffer_state != AUDIOBUF_STATE_TRASHED)
411 talk_buffer_steal();
412 buffer_state = AUDIOBUF_STATE_TRASHED;
415 buf = audiobuf;
416 end = audiobufend;
418 else
420 /* Safe to just return this if already AUDIOBUF_STATE_VOICED_ONLY or
421 still AUDIOBUF_STATE_INITIALIZED */
422 /* Skip talk buffer and move pcm buffer to end to maximize available
423 contiguous memory - no audio running means voice will not need the
424 swap space */
425 logf("get buffer: audio");
426 buf = audiobuf + talk_get_bufsize();
427 end = audiobufend - pcmbuf_init(audiobufend);
428 buffer_state = AUDIOBUF_STATE_VOICED_ONLY;
431 *buffer_size = end - buf;
433 return buf;
436 int audio_buffer_state(void)
438 return buffer_state;
441 #ifdef HAVE_RECORDING
442 unsigned char *audio_get_recording_buffer(size_t *buffer_size)
444 /* Stop audio, voice and obtain all available buffer space */
445 audio_hard_stop();
446 talk_buffer_steal();
448 unsigned char *end = audiobufend;
449 buffer_state = AUDIOBUF_STATE_TRASHED;
450 *buffer_size = end - audiobuf;
452 return (unsigned char *)audiobuf;
455 bool audio_load_encoder(int afmt)
457 #ifndef SIMULATOR
458 const char *enc_fn = get_codec_filename(afmt | CODEC_TYPE_ENCODER);
459 if (!enc_fn)
460 return false;
462 audio_remove_encoder();
463 ci.enc_codec_loaded = 0; /* clear any previous error condition */
465 LOGFQUEUE("codec > Q_ENCODER_LOAD_DISK");
466 queue_post(&codec_queue, Q_ENCODER_LOAD_DISK, (intptr_t)enc_fn);
468 while (ci.enc_codec_loaded == 0)
469 yield();
471 logf("codec loaded: %d", ci.enc_codec_loaded);
473 return ci.enc_codec_loaded > 0;
474 #else
475 (void)afmt;
476 return true;
477 #endif
478 } /* audio_load_encoder */
480 void audio_remove_encoder(void)
482 #ifndef SIMULATOR
483 /* force encoder codec unload (if currently loaded) */
484 if (ci.enc_codec_loaded <= 0)
485 return;
487 ci.stop_encoder = true;
488 while (ci.enc_codec_loaded > 0)
489 yield();
490 #endif
491 } /* audio_remove_encoder */
493 #endif /* HAVE_RECORDING */
496 struct mp3entry* audio_current_track(void)
498 const char *filename;
499 struct playlist_track_info trackinfo;
500 int cur_idx;
501 int offset = ci.new_track + wps_offset;
502 struct mp3entry *write_id3;
504 cur_idx = (track_ridx + offset) & MAX_TRACK_MASK;
506 if (cur_idx == track_ridx && *thistrack_id3->path)
508 /* The usual case */
509 if (tracks[cur_idx].cuesheet_hid >= 0 && !thistrack_id3->cuesheet)
511 bufread(tracks[cur_idx].cuesheet_hid, sizeof(struct cuesheet), curr_cue);
512 thistrack_id3->cuesheet = curr_cue;
513 cue_spoof_id3(thistrack_id3->cuesheet, thistrack_id3);
515 return thistrack_id3;
517 else if (automatic_skip && offset == -1 && *othertrack_id3->path)
519 /* We're in a track transition. The codec has moved on to the next track,
520 but the audio being played is still the same (now previous) track.
521 othertrack_id3.elapsed is being updated in an ISR by
522 codec_pcmbuf_position_callback */
523 if (tracks[cur_idx].cuesheet_hid >= 0 && !thistrack_id3->cuesheet)
525 bufread(tracks[cur_idx].cuesheet_hid, sizeof(struct cuesheet), curr_cue);
526 othertrack_id3->cuesheet = curr_cue;
527 cue_spoof_id3(othertrack_id3->cuesheet, othertrack_id3);
529 return othertrack_id3;
532 if (offset != 0)
534 /* Codec may be using thistrack_id3, so it must not be overwritten.
535 If this is a manual skip, othertrack_id3 will become
536 thistrack_id3 in audio_check_new_track().
537 FIXME: If this is an automatic skip, it probably means multiple
538 short tracks fit in the PCM buffer. Overwriting othertrack_id3
539 can lead to an incorrect value later.
540 Note that othertrack_id3 may also be used for next track.
542 write_id3 = othertrack_id3;
544 else
546 write_id3 = thistrack_id3;
549 if (tracks[cur_idx].id3_hid >= 0)
551 /* The current track's info has been buffered but not read yet, so get it */
552 if (bufread(tracks[cur_idx].id3_hid, sizeof(struct mp3entry), write_id3)
553 == sizeof(struct mp3entry))
554 return write_id3;
557 /* We didn't find the ID3 metadata, so we fill temp_id3 with the little info
558 we have and return that. */
560 memset(write_id3, 0, sizeof(struct mp3entry));
562 playlist_get_track_info(NULL, playlist_next(0)+wps_offset, &trackinfo);
563 filename = trackinfo.filename;
564 if (!filename)
565 filename = "No file!";
567 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
568 if (tagcache_fill_tags(write_id3, filename))
569 return write_id3;
570 #endif
572 strlcpy(write_id3->path, filename, sizeof(write_id3->path));
573 write_id3->title = strrchr(write_id3->path, '/');
574 if (!write_id3->title)
575 write_id3->title = &write_id3->path[0];
576 else
577 write_id3->title++;
579 return write_id3;
582 struct mp3entry* audio_next_track(void)
584 int next_idx;
585 int offset = ci.new_track + wps_offset;
587 if (!audio_have_tracks())
588 return NULL;
590 if (wps_offset == -1 && *thistrack_id3->path)
592 /* We're in a track transition. The next track for the WPS is the one
593 currently being decoded. */
594 return thistrack_id3;
597 next_idx = (track_ridx + offset + 1) & MAX_TRACK_MASK;
599 if (tracks[next_idx].id3_hid >= 0)
601 if (bufread(tracks[next_idx].id3_hid, sizeof(struct mp3entry), othertrack_id3)
602 == sizeof(struct mp3entry))
603 return othertrack_id3;
604 else
605 return NULL;
608 if (next_idx == track_widx)
610 /* The next track hasn't been buffered yet, so we return the static
611 version of its metadata. */
612 return &unbuffered_id3;
615 return NULL;
618 #ifdef HAVE_ALBUMART
619 int playback_current_aa_hid(int slot)
621 if (slot < 0)
622 return -1;
623 int cur_idx;
624 int offset = ci.new_track + wps_offset;
626 cur_idx = track_ridx + offset;
627 cur_idx &= MAX_TRACK_MASK;
629 return tracks[cur_idx].aa_hid[slot];
632 int playback_claim_aa_slot(struct dim *dim)
634 int i;
635 /* first try to find a slot already having the size to reuse it
636 * since we don't want albumart of the same size buffered multiple times */
637 FOREACH_ALBUMART(i)
639 struct albumart_slot *slot = &albumart_slots[i];
640 if (slot->dim.width == dim->width
641 && slot->dim.height == dim->height)
643 slot->used++;
644 return i;
647 /* size is new, find a free slot */
648 FOREACH_ALBUMART(i)
650 if (!albumart_slots[i].used)
652 albumart_slots[i].used++;
653 albumart_slots[i].dim = *dim;
654 return i;
657 /* sorry, no free slot */
658 return -1;
661 void playback_release_aa_slot(int slot)
663 /* invalidate the albumart_slot */
664 struct albumart_slot *aa_slot = &albumart_slots[slot];
665 if (aa_slot->used > 0)
666 aa_slot->used--;
669 #endif
670 void audio_play(long offset)
672 logf("audio_play");
674 #ifdef PLAYBACK_VOICE
675 /* Truncate any existing voice output so we don't have spelling
676 * etc. over the first part of the played track */
677 talk_force_shutup();
678 #endif
680 /* Start playback */
681 LOGFQUEUE("audio >| audio Q_AUDIO_PLAY: %ld", offset);
682 /* Don't return until playback has actually started */
683 queue_send(&audio_queue, Q_AUDIO_PLAY, offset);
686 void audio_stop(void)
688 /* Stop playback */
689 LOGFQUEUE("audio >| audio Q_AUDIO_STOP");
690 /* Don't return until playback has actually stopped */
691 queue_send(&audio_queue, Q_AUDIO_STOP, 0);
694 void audio_pause(void)
696 LOGFQUEUE("audio >| audio Q_AUDIO_PAUSE");
697 /* Don't return until playback has actually paused */
698 queue_send(&audio_queue, Q_AUDIO_PAUSE, true);
701 void audio_resume(void)
703 LOGFQUEUE("audio >| audio Q_AUDIO_PAUSE resume");
704 /* Don't return until playback has actually resumed */
705 queue_send(&audio_queue, Q_AUDIO_PAUSE, false);
708 void audio_skip(int direction)
710 if (playlist_check(ci.new_track + wps_offset + direction))
712 if (global_settings.beep)
713 pcmbuf_beep(2000, 100, 2500*global_settings.beep);
715 LOGFQUEUE("audio > audio Q_AUDIO_SKIP %d", direction);
716 queue_post(&audio_queue, Q_AUDIO_SKIP, direction);
717 /* Update wps while our message travels inside deep playback queues. */
718 wps_offset += direction;
720 else
722 /* No more tracks. */
723 if (global_settings.beep)
724 pcmbuf_beep(1000, 100, 1500*global_settings.beep);
728 void audio_next(void)
730 audio_skip(1);
733 void audio_prev(void)
735 audio_skip(-1);
738 void audio_next_dir(void)
740 LOGFQUEUE("audio > audio Q_AUDIO_DIR_SKIP 1");
741 queue_post(&audio_queue, Q_AUDIO_DIR_SKIP, 1);
744 void audio_prev_dir(void)
746 LOGFQUEUE("audio > audio Q_AUDIO_DIR_SKIP -1");
747 queue_post(&audio_queue, Q_AUDIO_DIR_SKIP, -1);
750 void audio_pre_ff_rewind(void)
752 LOGFQUEUE("audio > audio Q_AUDIO_PRE_FF_REWIND");
753 queue_post(&audio_queue, Q_AUDIO_PRE_FF_REWIND, 0);
756 void audio_ff_rewind(long newpos)
758 LOGFQUEUE("audio > audio Q_AUDIO_FF_REWIND");
759 queue_post(&audio_queue, Q_AUDIO_FF_REWIND, newpos);
762 void audio_flush_and_reload_tracks(void)
764 LOGFQUEUE("audio > audio Q_AUDIO_FLUSH");
765 queue_post(&audio_queue, Q_AUDIO_FLUSH, 0);
768 void audio_error_clear(void)
770 #ifdef AUDIO_HAVE_RECORDING
771 pcm_rec_error_clear();
772 #endif
775 int audio_status(void)
777 int ret = 0;
779 if (playing)
780 ret |= AUDIO_STATUS_PLAY;
782 if (paused)
783 ret |= AUDIO_STATUS_PAUSE;
785 #ifdef HAVE_RECORDING
786 /* Do this here for constitency with mpeg.c version */
787 /* FIXME: pcm_rec_status() is deprecated */
788 ret |= pcm_rec_status();
789 #endif
791 return ret;
794 int audio_get_file_pos(void)
796 return 0;
799 #ifdef HAVE_DISK_STORAGE
800 void audio_set_buffer_margin(int setting)
802 static const unsigned short lookup[] = {5, 15, 30, 60, 120, 180, 300, 600};
803 buffer_margin = lookup[setting];
804 logf("buffer margin: %ld", (long)buffer_margin);
805 set_filebuf_watermark();
807 #endif
809 /* Take necessary steps to enable or disable the crossfade setting */
810 void audio_set_crossfade(int enable)
812 size_t offset;
813 bool was_playing;
814 size_t size;
816 /* Tell it the next setting to use */
817 pcmbuf_crossfade_enable(enable);
819 /* Return if size hasn't changed or this is too early to determine
820 which in the second case there's no way we could be playing
821 anything at all */
822 if (pcmbuf_is_same_size())
824 /* This function is a copout and just syncs some variables -
825 to be removed at a later date */
826 pcmbuf_crossfade_enable_finished();
827 return;
830 offset = 0;
831 was_playing = playing;
833 /* Playback has to be stopped before changing the buffer size */
834 if (was_playing)
836 /* Store the track resume position */
837 offset = thistrack_id3->offset;
840 /* Blast it - audio buffer will have to be setup again next time
841 something plays */
842 audio_get_buffer(true, &size);
844 /* Restart playback if audio was running previously */
845 if (was_playing)
846 audio_play(offset);
849 /* --- Routines called from multiple threads --- */
851 static void set_filebuf_watermark(void)
853 if (!filebuf)
854 return; /* Audio buffers not yet set up */
856 #ifdef HAVE_DISK_STORAGE
857 int seconds;
858 int spinup = ata_spinup_time();
859 if (spinup)
860 seconds = (spinup / HZ) + 1;
861 else
862 seconds = 5;
864 seconds += buffer_margin;
865 #else
866 /* flash storage */
867 int seconds = 1;
868 #endif
870 /* bitrate of last track in buffer dictates watermark */
871 struct mp3entry* id3 = NULL;
872 if (tracks[track_widx].taginfo_ready)
873 id3 = bufgetid3(tracks[track_widx].id3_hid);
874 else
875 id3 = bufgetid3(tracks[track_widx-1].id3_hid);
876 if (!id3) {
877 logf("fwmark: No id3 for last track (r%d/w%d), aborting!", track_ridx, track_widx);
878 return;
880 size_t bytes = id3->bitrate * (1000/8) * seconds;
881 buf_set_watermark(bytes);
882 logf("fwmark: %d", bytes);
885 /* --- Buffering callbacks --- */
887 static void buffering_low_buffer_callback(void *data)
889 (void)data;
890 logf("low buffer callback");
892 if (filling == STATE_FULL || filling == STATE_END_OF_PLAYLIST) {
893 /* force a refill */
894 LOGFQUEUE("buffering > audio Q_AUDIO_FILL_BUFFER");
895 queue_post(&audio_queue, Q_AUDIO_FILL_BUFFER, 0);
899 static void buffering_handle_rebuffer_callback(void *data)
901 (void)data;
902 LOGFQUEUE("audio >| audio Q_AUDIO_FLUSH");
903 queue_post(&audio_queue, Q_AUDIO_FLUSH, 0);
906 static void buffering_handle_finished_callback(void *data)
908 logf("handle %d finished buffering", *(int*)data);
909 int hid = (*(int*)data);
911 if (hid == tracks[track_widx].id3_hid)
913 int offset = ci.new_track + wps_offset;
914 int next_idx = (track_ridx + offset + 1) & MAX_TRACK_MASK;
915 /* The metadata handle for the last loaded track has been buffered.
916 We can ask the audio thread to load the rest of the track's data. */
917 LOGFQUEUE("audio >| audio Q_AUDIO_FINISH_LOAD");
918 queue_post(&audio_queue, Q_AUDIO_FINISH_LOAD, 0);
919 if (tracks[next_idx].id3_hid == hid)
920 send_event(PLAYBACK_EVENT_NEXTTRACKID3_AVAILABLE, NULL);
922 else
924 /* This is most likely an audio handle, so we strip the useless
925 trailing tags that are left. */
926 strip_tags(hid);
928 if (hid == tracks[track_widx-1].audio_hid
929 && filling == STATE_END_OF_PLAYLIST)
931 /* This was the last track in the playlist.
932 We now have all the data we need. */
933 logf("last track finished buffering");
934 filling = STATE_FINISHED;
940 /* --- Audio thread --- */
942 static bool audio_have_tracks(void)
944 return (audio_track_count() != 0);
947 static int audio_free_track_count(void)
949 /* Used tracks + free tracks adds up to MAX_TRACK - 1 */
950 return MAX_TRACK - 1 - audio_track_count();
953 int audio_track_count(void)
955 /* Calculate difference from track_ridx to track_widx
956 * taking into account a possible wrap-around. */
957 return (MAX_TRACK + track_widx - track_ridx) & MAX_TRACK_MASK;
960 long audio_filebufused(void)
962 return (long) buf_used();
965 /* Update track info after successful a codec track change */
966 static void audio_update_trackinfo(void)
968 /* Load the curent track's metadata into curtrack_id3 */
969 if (CUR_TI->id3_hid >= 0)
970 copy_mp3entry(thistrack_id3, bufgetid3(CUR_TI->id3_hid));
972 /* Reset current position */
973 thistrack_id3->elapsed = 0;
974 thistrack_id3->offset = 0;
976 /* Update the codec API */
977 ci.filesize = CUR_TI->filesize;
978 ci.id3 = thistrack_id3;
979 ci.curpos = 0;
980 ci.taginfo_ready = &CUR_TI->taginfo_ready;
983 /* Clear tracks between write and read, non inclusive */
984 static void audio_clear_track_entries(void)
986 int cur_idx = track_widx;
988 logf("Clearing tracks: r%d/w%d", track_ridx, track_widx);
990 /* Loop over all tracks from write-to-read */
991 while (1)
993 cur_idx = (cur_idx + 1) & MAX_TRACK_MASK;
995 if (cur_idx == track_ridx)
996 break;
998 clear_track_info(&tracks[cur_idx]);
1002 /* Clear all tracks */
1003 static bool audio_release_tracks(void)
1005 int i, cur_idx;
1007 logf("releasing all tracks");
1009 for(i = 0; i < MAX_TRACK; i++)
1011 cur_idx = (track_ridx + i) & MAX_TRACK_MASK;
1012 if (!clear_track_info(&tracks[cur_idx]))
1013 return false;
1016 return true;
1019 static bool audio_loadcodec(bool start_play)
1021 int prev_track;
1022 char codec_path[MAX_PATH]; /* Full path to codec */
1023 const struct mp3entry *id3, *prev_id3;
1025 if (tracks[track_widx].id3_hid < 0) {
1026 return false;
1029 id3 = bufgetid3(tracks[track_widx].id3_hid);
1030 if (!id3)
1031 return false;
1033 const char *codec_fn = get_codec_filename(id3->codectype);
1034 if (codec_fn == NULL)
1035 return false;
1037 tracks[track_widx].codec_hid = -1;
1039 if (start_play)
1041 /* Load the codec directly from disk and save some memory. */
1042 track_ridx = track_widx;
1043 ci.filesize = CUR_TI->filesize;
1044 ci.id3 = thistrack_id3;
1045 ci.taginfo_ready = &CUR_TI->taginfo_ready;
1046 ci.curpos = 0;
1047 LOGFQUEUE("codec > codec Q_CODEC_LOAD_DISK");
1048 queue_post(&codec_queue, Q_CODEC_LOAD_DISK, (intptr_t)codec_fn);
1049 return true;
1051 else
1053 /* If we already have another track than this one buffered */
1054 if (track_widx != track_ridx)
1056 prev_track = (track_widx - 1) & MAX_TRACK_MASK;
1058 id3 = bufgetid3(tracks[track_widx].id3_hid);
1059 prev_id3 = bufgetid3(tracks[prev_track].id3_hid);
1061 /* If the previous codec is the same as this one, there is no need
1062 * to put another copy of it on the file buffer */
1063 if (id3 && prev_id3 &&
1064 get_codec_base_type(id3->codectype) ==
1065 get_codec_base_type(prev_id3->codectype)
1066 && audio_codec_loaded)
1068 logf("Reusing prev. codec");
1069 return true;
1074 codec_get_full_path(codec_path, codec_fn);
1076 tracks[track_widx].codec_hid = bufopen(codec_path, 0, TYPE_CODEC, NULL);
1077 if (tracks[track_widx].codec_hid < 0)
1078 return false;
1080 logf("Loaded codec");
1082 return true;
1085 /* Load metadata for the next track (with bufopen). The rest of the track
1086 loading will be handled by audio_finish_load_track once the metadata has been
1087 actually loaded by the buffering thread. */
1088 static bool audio_load_track(size_t offset, bool start_play)
1090 const char *trackname;
1091 int fd = -1;
1093 if (track_load_started) {
1094 /* There is already a track load in progress, so track_widx hasn't been
1095 incremented yet. Loading another track would overwrite the one that
1096 hasn't finished loading. */
1097 logf("audio_load_track(): a track load is already in progress");
1098 return false;
1101 start_play_g = start_play; /* will be read by audio_finish_load_track */
1103 /* Stop buffer filling if there is no free track entries.
1104 Don't fill up the last track entry (we wan't to store next track
1105 metadata there). */
1106 if (!audio_free_track_count())
1108 logf("No free tracks");
1109 return false;
1112 last_peek_offset++;
1113 tracks[track_widx].taginfo_ready = false;
1115 logf("Buffering track: r%d/w%d", track_ridx, track_widx);
1116 /* Get track name from current playlist read position. */
1117 while ((trackname = playlist_peek(last_peek_offset)) != NULL)
1119 /* Handle broken playlists. */
1120 fd = open(trackname, O_RDONLY);
1121 if (fd < 0)
1123 logf("Open failed");
1124 /* Skip invalid entry from playlist. */
1125 playlist_skip_entry(NULL, last_peek_offset);
1127 else
1128 break;
1131 if (!trackname)
1133 logf("End-of-playlist");
1134 memset(&unbuffered_id3, 0, sizeof(struct mp3entry));
1135 filling = STATE_END_OF_PLAYLIST;
1137 if (thistrack_id3->length == 0 && thistrack_id3->filesize == 0)
1139 /* Stop playback if no valid track was found. */
1140 audio_stop_playback();
1143 return false;
1146 tracks[track_widx].filesize = filesize(fd);
1148 if (offset > tracks[track_widx].filesize)
1149 offset = 0;
1151 /* Set default values */
1152 if (start_play)
1154 buf_set_watermark(filebuflen/2);
1155 dsp_configure(ci.dsp, DSP_RESET, 0);
1156 playlist_update_resume_info(audio_current_track());
1159 /* Get track metadata if we don't already have it. */
1160 if (tracks[track_widx].id3_hid < 0)
1162 tracks[track_widx].id3_hid = bufopen(trackname, 0, TYPE_ID3, NULL);
1164 if (tracks[track_widx].id3_hid < 0)
1166 /* Buffer is full. */
1167 get_metadata(&unbuffered_id3, fd, trackname);
1168 last_peek_offset--;
1169 close(fd);
1170 logf("buffer is full for now (get metadata)");
1171 filling = STATE_FULL;
1172 return false;
1175 if (track_widx == track_ridx)
1177 /* TODO: Superfluos buffering call? */
1178 buf_request_buffer_handle(tracks[track_widx].id3_hid);
1179 struct mp3entry *id3 = bufgetid3(tracks[track_widx].id3_hid);
1180 if (id3)
1182 copy_mp3entry(thistrack_id3, id3);
1183 thistrack_id3->offset = offset;
1185 else
1186 memset(thistrack_id3, 0, sizeof(struct mp3entry));
1189 if (start_play)
1191 playlist_update_resume_info(audio_current_track());
1195 close(fd);
1196 track_load_started = true; /* Remember that we've started loading a track */
1197 return true;
1200 /* Second part of the track loading: We now have the metadata available, so we
1201 can load the codec, the album art and finally the audio data.
1202 This is called on the audio thread after the buffering thread calls the
1203 buffering_handle_finished_callback callback. */
1204 static void audio_finish_load_track(void)
1206 size_t file_offset = 0;
1207 size_t offset = 0;
1208 bool start_play = start_play_g;
1210 track_load_started = false;
1212 if (tracks[track_widx].id3_hid < 0) {
1213 logf("No metadata");
1214 return;
1217 struct mp3entry *track_id3;
1219 if (track_widx == track_ridx)
1220 track_id3 = thistrack_id3;
1221 else
1222 track_id3 = bufgetid3(tracks[track_widx].id3_hid);
1224 if (track_id3->length == 0 && track_id3->filesize == 0)
1226 logf("audio_finish_load_track: invalid metadata");
1228 /* Invalid metadata */
1229 bufclose(tracks[track_widx].id3_hid);
1230 tracks[track_widx].id3_hid = -1;
1232 /* Skip invalid entry from playlist. */
1233 playlist_skip_entry(NULL, last_peek_offset--);
1235 /* load next track */
1236 LOGFQUEUE("audio > audio Q_AUDIO_FILL_BUFFER %d", (int)start_play);
1237 queue_post(&audio_queue, Q_AUDIO_FILL_BUFFER, start_play);
1239 return;
1241 /* Try to load a cuesheet for the track */
1242 if (curr_cue)
1244 char cuepath[MAX_PATH];
1245 if (look_for_cuesheet_file(track_id3->path, cuepath))
1247 void *temp;
1248 tracks[track_widx].cuesheet_hid =
1249 bufalloc(NULL, sizeof(struct cuesheet), TYPE_CUESHEET);
1250 if (tracks[track_widx].cuesheet_hid >= 0)
1252 bufgetdata(tracks[track_widx].cuesheet_hid,
1253 sizeof(struct cuesheet), &temp);
1254 struct cuesheet *cuesheet = (struct cuesheet*)temp;
1255 if (!parse_cuesheet(cuepath, cuesheet))
1257 bufclose(tracks[track_widx].cuesheet_hid);
1258 track_id3->cuesheet = NULL;
1263 #ifdef HAVE_ALBUMART
1265 int i;
1266 char aa_path[MAX_PATH];
1267 FOREACH_ALBUMART(i)
1269 /* albumart_slots may change during a yield of bufopen,
1270 * but that's no problem */
1271 if (tracks[track_widx].aa_hid[i] >= 0 || !albumart_slots[i].used)
1272 continue;
1273 /* find_albumart will error out if the wps doesn't have AA */
1274 if (find_albumart(track_id3, aa_path, sizeof(aa_path),
1275 &(albumart_slots[i].dim)))
1277 int aa_hid = bufopen(aa_path, 0, TYPE_BITMAP,
1278 &(albumart_slots[i].dim));
1280 if(aa_hid == ERR_BUFFER_FULL)
1282 filling = STATE_FULL;
1283 logf("buffer is full for now (get album art)");
1284 return; /* No space for track's album art, not an error */
1286 else if (aa_hid < 0)
1288 /* another error, ignore AlbumArt */
1289 logf("Album art loading failed");
1291 tracks[track_widx].aa_hid[i] = aa_hid;
1296 #endif
1298 /* Load the codec. */
1299 if (!audio_loadcodec(start_play))
1301 if (tracks[track_widx].codec_hid == ERR_BUFFER_FULL)
1303 /* No space for codec on buffer, not an error */
1304 filling = STATE_FULL;
1305 return;
1308 /* This is an error condition, either no codec was found, or reading
1309 * the codec file failed part way through, either way, skip the track */
1310 /* FIXME: We should not use splashf from audio thread! */
1311 splashf(HZ*2, "No codec for: %s", track_id3->path);
1312 /* Skip invalid entry from playlist. */
1313 playlist_skip_entry(NULL, last_peek_offset);
1314 return;
1317 track_id3->elapsed = 0;
1318 offset = track_id3->offset;
1320 enum data_type type = TYPE_PACKET_AUDIO;
1322 switch (track_id3->codectype) {
1323 case AFMT_MPA_L1:
1324 case AFMT_MPA_L2:
1325 case AFMT_MPA_L3:
1326 if (offset > 0) {
1327 file_offset = offset;
1328 track_id3->offset = offset;
1330 break;
1332 case AFMT_WAVPACK:
1333 if (offset > 0) {
1334 file_offset = offset;
1335 track_id3->offset = offset;
1336 track_id3->elapsed = track_id3->length / 2;
1338 break;
1340 case AFMT_OGG_VORBIS:
1341 case AFMT_SPEEX:
1342 case AFMT_FLAC:
1343 case AFMT_PCM_WAV:
1344 case AFMT_A52:
1345 case AFMT_MP4_AAC:
1346 case AFMT_MPC:
1347 case AFMT_APE:
1348 case AFMT_WMA:
1349 if (offset > 0)
1350 track_id3->offset = offset;
1351 break;
1353 case AFMT_NSF:
1354 case AFMT_SPC:
1355 case AFMT_SID:
1356 logf("Loading atomic %d",track_id3->codectype);
1357 type = TYPE_ATOMIC_AUDIO;
1358 break;
1361 logf("load track: %s", track_id3->path);
1363 if (file_offset > AUDIO_REBUFFER_GUESS_SIZE)
1364 file_offset -= AUDIO_REBUFFER_GUESS_SIZE;
1365 else if (track_id3->first_frame_offset)
1366 file_offset = track_id3->first_frame_offset;
1367 else
1368 file_offset = 0;
1370 tracks[track_widx].audio_hid = bufopen(track_id3->path, file_offset, type,
1371 NULL);
1373 /* No space left, not an error */
1374 if (tracks[track_widx].audio_hid == ERR_BUFFER_FULL)
1376 filling = STATE_FULL;
1377 logf("buffer is full for now (load audio)");
1378 return;
1380 else if (tracks[track_widx].audio_hid < 0)
1382 /* another error, do not continue either */
1383 logf("Could not add audio data handle");
1384 return;
1387 /* All required data is now available for the codec. */
1388 tracks[track_widx].taginfo_ready = true;
1390 if (start_play)
1392 ci.curpos=file_offset;
1393 buf_request_buffer_handle(tracks[track_widx].audio_hid);
1396 track_widx = (track_widx + 1) & MAX_TRACK_MASK;
1398 send_event(PLAYBACK_EVENT_TRACK_BUFFER, track_id3);
1400 /* load next track */
1401 LOGFQUEUE("audio > audio Q_AUDIO_FILL_BUFFER");
1402 queue_post(&audio_queue, Q_AUDIO_FILL_BUFFER, 0);
1404 return;
1407 static void audio_fill_file_buffer(bool start_play, size_t offset)
1409 trigger_cpu_boost();
1411 /* No need to rebuffer if there are track skips pending,
1412 * however don't cancel buffering on skipping while filling. */
1413 if (ci.new_track != 0 && filling != STATE_FILLING)
1414 return;
1415 filling = STATE_FILLING;
1417 /* Must reset the buffer before use if trashed or voice only - voice
1418 file size shouldn't have changed so we can go straight from
1419 AUDIOBUF_STATE_VOICED_ONLY to AUDIOBUF_STATE_INITIALIZED */
1420 if (buffer_state != AUDIOBUF_STATE_INITIALIZED)
1421 audio_reset_buffer();
1423 logf("Starting buffer fill");
1425 if (!start_play)
1426 audio_clear_track_entries();
1428 /* Save the current resume position once. */
1429 playlist_update_resume_info(audio_current_track());
1431 audio_load_track(offset, start_play);
1434 static void audio_rebuffer(void)
1436 logf("Forcing rebuffer");
1438 clear_track_info(CUR_TI);
1440 /* Reset track pointers */
1441 track_widx = track_ridx;
1442 audio_clear_track_entries();
1444 /* Reset a possibly interrupted track load */
1445 track_load_started = false;
1447 /* Fill the buffer */
1448 last_peek_offset = -1;
1449 ci.curpos = 0;
1451 if (!CUR_TI->taginfo_ready)
1452 memset(thistrack_id3, 0, sizeof(struct mp3entry));
1454 audio_fill_file_buffer(false, 0);
1457 /* Called on request from the codec to get a new track. This is the codec part
1458 of the track transition. */
1459 static int audio_check_new_track(void)
1461 int track_count = audio_track_count();
1462 int old_track_ridx = track_ridx;
1463 int i, idx;
1464 bool forward;
1465 struct mp3entry *temp = thistrack_id3;
1467 /* Now it's good time to send track finish events. */
1468 send_event(PLAYBACK_EVENT_TRACK_FINISH, thistrack_id3);
1469 /* swap the mp3entry pointers */
1470 thistrack_id3 = othertrack_id3;
1471 othertrack_id3 = temp;
1472 ci.id3 = thistrack_id3;
1473 memset(thistrack_id3, 0, sizeof(struct mp3entry));
1475 if (dir_skip)
1477 dir_skip = false;
1478 /* regardless of the return value we need to rebuffer.
1479 if it fails the old playlist will resume, else the
1480 next dir will start playing */
1481 playlist_next_dir(ci.new_track);
1482 ci.new_track = 0;
1483 audio_rebuffer();
1484 goto skip_done;
1487 if (new_playlist)
1488 ci.new_track = 0;
1490 /* If the playlist isn't that big */
1491 if (automatic_skip)
1493 while (!playlist_check(ci.new_track))
1495 if (ci.new_track >= 0)
1497 LOGFQUEUE("audio >|= codec Q_CODEC_REQUEST_FAILED");
1498 return Q_CODEC_REQUEST_FAILED;
1500 ci.new_track++;
1504 /* Update the playlist */
1505 last_peek_offset -= ci.new_track;
1507 if (playlist_next(ci.new_track) < 0)
1509 LOGFQUEUE("audio >|= codec Q_CODEC_REQUEST_FAILED");
1510 return Q_CODEC_REQUEST_FAILED;
1513 if (new_playlist)
1515 ci.new_track = 1;
1516 new_playlist = false;
1519 /* Save a pointer to the old track to allow later clearing */
1520 prev_ti = CUR_TI;
1522 for (i = 0; i < ci.new_track; i++)
1524 idx = (track_ridx + i) & MAX_TRACK_MASK;
1525 struct mp3entry *id3 = bufgetid3(tracks[idx].id3_hid);
1526 ssize_t offset = buf_handle_offset(tracks[idx].audio_hid);
1527 if (!id3 || offset < 0 || (unsigned)offset > id3->first_frame_offset)
1529 /* We don't have all the audio data for that track, so clear it,
1530 but keep the metadata. */
1531 if (tracks[idx].audio_hid >= 0 && bufclose(tracks[idx].audio_hid))
1533 tracks[idx].audio_hid = -1;
1534 tracks[idx].filesize = 0;
1539 /* Move to the new track */
1540 track_ridx = (track_ridx + ci.new_track) & MAX_TRACK_MASK;
1542 buf_set_base_handle(CUR_TI->audio_hid);
1544 if (automatic_skip)
1546 wps_offset = -ci.new_track;
1549 /* If it is not safe to even skip this many track entries */
1550 if (ci.new_track >= track_count || ci.new_track <= track_count - MAX_TRACK)
1552 ci.new_track = 0;
1553 audio_rebuffer();
1554 goto skip_done;
1557 forward = ci.new_track > 0;
1558 ci.new_track = 0;
1560 /* If the target track is clearly not in memory */
1561 if (CUR_TI->filesize == 0 || !CUR_TI->taginfo_ready)
1563 audio_rebuffer();
1564 goto skip_done;
1567 /* When skipping backwards, it is possible that we've found a track that's
1568 * buffered, but which is around the track-wrap and therefore not the track
1569 * we are looking for */
1570 if (!forward)
1572 int cur_idx = track_ridx;
1573 bool taginfo_ready = true;
1574 /* We've wrapped the buffer backwards if new > old */
1575 bool wrap = track_ridx > old_track_ridx;
1577 while (1)
1579 cur_idx = (cur_idx + 1) & MAX_TRACK_MASK;
1581 /* if we've advanced past the wrap when cur_idx is zeroed */
1582 if (!cur_idx)
1583 wrap = false;
1585 /* if we aren't still on the wrap and we've caught the old track */
1586 if (!(wrap || cur_idx < old_track_ridx))
1587 break;
1589 /* If we hit a track in between without valid tag info, bail */
1590 if (!tracks[cur_idx].taginfo_ready)
1592 taginfo_ready = false;
1593 break;
1596 if (!taginfo_ready)
1598 audio_rebuffer();
1602 skip_done:
1603 audio_update_trackinfo();
1604 LOGFQUEUE("audio >|= codec Q_CODEC_REQUEST_COMPLETE");
1605 return Q_CODEC_REQUEST_COMPLETE;
1608 unsigned long audio_prev_elapsed(void)
1610 return prev_track_elapsed;
1613 void audio_set_prev_elapsed(unsigned long setting)
1615 prev_track_elapsed = setting;
1618 static void audio_stop_codec_flush(void)
1620 ci.stop_codec = true;
1621 pcmbuf_pause(true);
1623 while (audio_codec_loaded)
1624 yield();
1626 /* If the audio codec is not loaded any more, and the audio is still
1627 * playing, it is now and _only_ now safe to call this function from the
1628 * audio thread */
1629 if (pcm_is_playing())
1631 pcmbuf_play_stop();
1632 pcm_play_lock();
1633 queue_clear(&pcmbuf_queue);
1634 pcm_play_unlock();
1636 pcmbuf_pause(paused);
1639 static void audio_stop_playback(void)
1641 if (playing)
1643 /* If we were playing, save resume information */
1644 struct mp3entry *id3 = NULL;
1646 if (!ci.stop_codec)
1648 /* Set this early, the outside code yields and may allow the codec
1649 to try to wait for a reply on a buffer wait */
1650 ci.stop_codec = true;
1651 id3 = audio_current_track();
1654 /* Save the current playing spot, or NULL if the playlist has ended */
1655 playlist_update_resume_info(id3);
1657 /* TODO: Create auto bookmark too? */
1659 prev_track_elapsed = othertrack_id3->elapsed;
1661 remove_event(BUFFER_EVENT_BUFFER_LOW, buffering_low_buffer_callback);
1664 audio_stop_codec_flush();
1665 paused = false;
1666 playing = false;
1667 track_load_started = false;
1669 filling = STATE_IDLE;
1671 /* Mark all entries null. */
1672 audio_clear_track_entries();
1674 /* Close all tracks */
1675 audio_release_tracks();
1678 static void audio_play_start(size_t offset)
1680 int i;
1682 #if INPUT_SRC_CAPS != 0
1683 audio_set_input_source(AUDIO_SRC_PLAYBACK, SRCF_PLAYBACK);
1684 audio_set_output_source(AUDIO_SRC_PLAYBACK);
1685 #endif
1687 /* Wait for any previously playing audio to flush - TODO: Not necessary? */
1688 paused = false;
1689 audio_stop_codec_flush();
1691 playing = true;
1692 track_load_started = false;
1694 ci.new_track = 0;
1695 ci.seek_time = 0;
1696 wps_offset = 0;
1698 sound_set_volume(global_settings.volume);
1699 track_widx = track_ridx = 0;
1701 /* Clear all track entries. */
1702 for (i = 0; i < MAX_TRACK; i++) {
1703 clear_track_info(&tracks[i]);
1706 last_peek_offset = -1;
1708 /* Officially playing */
1709 queue_reply(&audio_queue, 1);
1711 audio_fill_file_buffer(true, offset);
1713 add_event(BUFFER_EVENT_BUFFER_LOW, false, buffering_low_buffer_callback);
1715 LOGFQUEUE("audio > audio Q_AUDIO_TRACK_CHANGED");
1716 queue_post(&audio_queue, Q_AUDIO_TRACK_CHANGED, 0);
1720 /* Invalidates all but currently playing track. */
1721 static void audio_invalidate_tracks(void)
1723 if (audio_have_tracks())
1725 last_peek_offset = 0;
1726 track_widx = track_ridx;
1728 /* Mark all other entries null (also buffered wrong metadata). */
1729 audio_clear_track_entries();
1731 track_widx = (track_widx + 1) & MAX_TRACK_MASK;
1733 audio_fill_file_buffer(false, 0);
1737 static void audio_new_playlist(void)
1739 /* Prepare to start a new fill from the beginning of the playlist */
1740 last_peek_offset = -1;
1741 if (audio_have_tracks())
1743 if (paused)
1744 skipped_during_pause = true;
1745 track_widx = track_ridx;
1746 audio_clear_track_entries();
1748 track_widx = (track_widx + 1) & MAX_TRACK_MASK;
1750 /* Mark the current track as invalid to prevent skipping back to it */
1751 CUR_TI->taginfo_ready = false;
1754 /* Signal the codec to initiate a track change forward */
1755 new_playlist = true;
1756 ci.new_track = 1;
1758 /* Officially playing */
1759 queue_reply(&audio_queue, 1);
1761 audio_fill_file_buffer(false, 0);
1764 /* Called on manual track skip */
1765 static void audio_initiate_track_change(long direction)
1767 logf("audio_initiate_track_change(%ld)", direction);
1769 ci.new_track += direction;
1770 wps_offset -= direction;
1771 if (paused)
1772 skipped_during_pause = true;
1775 /* Called on manual dir skip */
1776 static void audio_initiate_dir_change(long direction)
1778 dir_skip = true;
1779 ci.new_track = direction;
1780 if (paused)
1781 skipped_during_pause = true;
1784 /* Called when PCM track change is complete */
1785 static void audio_finalise_track_change(void)
1787 logf("audio_finalise_track_change");
1789 if (automatic_skip)
1791 wps_offset = 0;
1792 automatic_skip = false;
1794 /* Invalidate prevtrack_id3 */
1795 memset(othertrack_id3, 0, sizeof(struct mp3entry));
1797 if (prev_ti && prev_ti->audio_hid < 0)
1799 /* No audio left so we clear all the track info. */
1800 clear_track_info(prev_ti);
1803 send_event(PLAYBACK_EVENT_TRACK_CHANGE, thistrack_id3);
1804 playlist_update_resume_info(audio_current_track());
1808 * Layout audio buffer as follows - iram buffer depends on target:
1809 * [|SWAP:iram][|TALK]|FILE|GUARD|PCM|[SWAP:dram[|iram]|]
1811 static void audio_reset_buffer(void)
1813 /* see audio_get_recording_buffer if this is modified */
1814 logf("audio_reset_buffer");
1816 /* If the setup of anything allocated before the file buffer is
1817 changed, do check the adjustments after the buffer_alloc call
1818 as it will likely be affected and need sliding over */
1820 /* Initially set up file buffer as all space available */
1821 malloc_buf = audiobuf + talk_get_bufsize();
1822 /* Align the malloc buf to line size. Especially important to cf
1823 targets that do line reads/writes. */
1824 malloc_buf = (unsigned char *)(((uintptr_t)malloc_buf + 15) & ~15);
1825 filebuf = malloc_buf; /* filebuf line align implied */
1826 filebuflen = audiobufend - filebuf;
1828 filebuflen &= ~15;
1830 /* Subtract whatever the pcm buffer says it used plus the guard buffer */
1831 const size_t pcmbuf_size = pcmbuf_init(filebuf + filebuflen) +GUARD_BUFSIZE;
1833 #ifdef DEBUG
1834 if(pcmbuf_size > filebuflen)
1835 panicf("Not enough memory for pcmbuf_init() : %d > %d",
1836 (int)pcmbuf_size, (int)filebuflen);
1837 #endif
1839 filebuflen -= pcmbuf_size;
1841 /* Make sure filebuflen is a longword multiple after adjustment - filebuf
1842 will already be line aligned */
1843 filebuflen &= ~3;
1845 buffering_reset(filebuf, filebuflen);
1847 /* Clear any references to the file buffer */
1848 buffer_state = AUDIOBUF_STATE_INITIALIZED;
1850 #if defined(ROCKBOX_HAS_LOGF) && defined(LOGF_ENABLE)
1851 /* Make sure everything adds up - yes, some info is a bit redundant but
1852 aids viewing and the sumation of certain variables should add up to
1853 the location of others. */
1855 size_t pcmbufsize;
1856 const unsigned char *pcmbuf = pcmbuf_get_meminfo(&pcmbufsize);
1857 logf("mabuf: %08X", (unsigned)malloc_buf);
1858 logf("fbuf: %08X", (unsigned)filebuf);
1859 logf("fbufe: %08X", (unsigned)(filebuf + filebuflen));
1860 logf("gbuf: %08X", (unsigned)(filebuf + filebuflen));
1861 logf("gbufe: %08X", (unsigned)(filebuf + filebuflen + GUARD_BUFSIZE));
1862 logf("pcmb: %08X", (unsigned)pcmbuf);
1863 logf("pcmbe: %08X", (unsigned)(pcmbuf + pcmbufsize));
1865 #endif
1868 static void audio_thread(void)
1870 struct queue_event ev;
1872 pcm_postinit();
1874 audio_thread_ready = true;
1876 while (1)
1878 if (filling != STATE_FILLING && filling != STATE_IDLE) {
1879 /* End of buffering, let's calculate the watermark and unboost */
1880 set_filebuf_watermark();
1881 cancel_cpu_boost();
1884 if (!pcmbuf_queue_scan(&ev))
1885 queue_wait_w_tmo(&audio_queue, &ev, HZ/2);
1887 switch (ev.id) {
1889 case Q_AUDIO_FILL_BUFFER:
1890 LOGFQUEUE("audio < Q_AUDIO_FILL_BUFFER %d", (int)ev.data);
1891 audio_fill_file_buffer((bool)ev.data, 0);
1892 break;
1894 case Q_AUDIO_FINISH_LOAD:
1895 LOGFQUEUE("audio < Q_AUDIO_FINISH_LOAD");
1896 audio_finish_load_track();
1897 break;
1899 case Q_AUDIO_PLAY:
1900 LOGFQUEUE("audio < Q_AUDIO_PLAY");
1901 if (playing && ev.data <= 0)
1902 audio_new_playlist();
1903 else
1905 audio_stop_playback();
1906 audio_play_start((size_t)ev.data);
1908 break;
1910 case Q_AUDIO_STOP:
1911 LOGFQUEUE("audio < Q_AUDIO_STOP");
1912 if (playing)
1913 audio_stop_playback();
1914 if (ev.data != 0)
1915 queue_clear(&audio_queue);
1916 break;
1918 case Q_AUDIO_PAUSE:
1919 LOGFQUEUE("audio < Q_AUDIO_PAUSE");
1920 if (!(bool) ev.data && skipped_during_pause && !pcmbuf_is_crossfade_active())
1921 pcmbuf_play_stop(); /* Flush old track on resume after skip */
1922 skipped_during_pause = false;
1923 if (!playing)
1924 break;
1925 pcmbuf_pause((bool)ev.data);
1926 paused = (bool)ev.data;
1927 break;
1929 case Q_AUDIO_SKIP:
1930 LOGFQUEUE("audio < Q_AUDIO_SKIP");
1931 audio_initiate_track_change((long)ev.data);
1932 break;
1934 case Q_AUDIO_PRE_FF_REWIND:
1935 LOGFQUEUE("audio < Q_AUDIO_PRE_FF_REWIND");
1936 if (!playing)
1937 break;
1938 pcmbuf_pause(true);
1939 break;
1941 case Q_AUDIO_FF_REWIND:
1942 LOGFQUEUE("audio < Q_AUDIO_FF_REWIND");
1943 if (!playing)
1944 break;
1945 if (automatic_skip)
1947 /* An automatic track skip is in progress. Finalize it,
1948 then go back to the previous track */
1949 audio_finalise_track_change();
1950 ci.new_track = -1;
1952 ci.seek_time = (long)ev.data+1;
1953 break;
1955 case Q_AUDIO_CHECK_NEW_TRACK:
1956 LOGFQUEUE("audio < Q_AUDIO_CHECK_NEW_TRACK");
1957 queue_reply(&audio_queue, audio_check_new_track());
1958 break;
1960 case Q_AUDIO_DIR_SKIP:
1961 LOGFQUEUE("audio < Q_AUDIO_DIR_SKIP");
1962 audio_initiate_dir_change(ev.data);
1963 break;
1965 case Q_AUDIO_FLUSH:
1966 LOGFQUEUE("audio < Q_AUDIO_FLUSH");
1967 audio_invalidate_tracks();
1968 break;
1970 case Q_AUDIO_TRACK_CHANGED:
1971 /* PCM track change done */
1972 LOGFQUEUE("audio < Q_AUDIO_TRACK_CHANGED");
1973 audio_finalise_track_change();
1974 break;
1975 #ifndef SIMULATOR
1976 case SYS_USB_CONNECTED:
1977 LOGFQUEUE("audio < SYS_USB_CONNECTED");
1978 if (playing)
1979 audio_stop_playback();
1980 #ifdef PLAYBACK_VOICE
1981 voice_stop();
1982 #endif
1983 usb_acknowledge(SYS_USB_CONNECTED_ACK);
1984 usb_wait_for_disconnect(&audio_queue);
1986 /* Mark all entries null. */
1987 audio_clear_track_entries();
1989 /* release tracks to make sure all handles are closed */
1990 audio_release_tracks();
1991 break;
1992 #endif
1994 case SYS_TIMEOUT:
1995 LOGFQUEUE_SYS_TIMEOUT("audio < SYS_TIMEOUT");
1996 break;
1998 default:
1999 /* LOGFQUEUE("audio < default : %08lX", ev.id); */
2000 break;
2001 } /* end switch */
2002 } /* end while */
2005 /* Initialize the audio system - called from init() in main.c.
2006 * Last function because of all the references to internal symbols
2008 void audio_init(void)
2010 unsigned int audio_thread_id;
2012 /* Can never do this twice */
2013 if (audio_is_initialized)
2015 logf("audio: already initialized");
2016 return;
2019 logf("audio: initializing");
2021 /* Initialize queues before giving control elsewhere in case it likes
2022 to send messages. Thread creation will be delayed however so nothing
2023 starts running until ready if something yields such as talk_init. */
2024 queue_init(&audio_queue, true);
2025 queue_init(&codec_queue, false);
2026 queue_init(&pcmbuf_queue, false);
2028 pcm_init();
2030 codec_init_codec_api();
2032 thistrack_id3 = &mp3entry_buf[0];
2033 othertrack_id3 = &mp3entry_buf[1];
2035 /* cuesheet support */
2036 if (global_settings.cuesheet)
2037 curr_cue = (struct cuesheet*)buffer_alloc(sizeof(struct cuesheet));
2039 /* initialize the buffer */
2040 filebuf = audiobuf;
2042 /* audio_reset_buffer must to know the size of voice buffer so init
2043 talk first */
2044 talk_init();
2046 make_codec_thread();
2048 audio_thread_id = create_thread(audio_thread, audio_stack,
2049 sizeof(audio_stack), CREATE_THREAD_FROZEN,
2050 audio_thread_name IF_PRIO(, PRIORITY_USER_INTERFACE)
2051 IF_COP(, CPU));
2053 queue_enable_queue_send(&audio_queue, &audio_queue_sender_list,
2054 audio_thread_id);
2056 #ifdef PLAYBACK_VOICE
2057 voice_thread_init();
2058 #endif
2060 /* Set crossfade setting for next buffer init which should be about... */
2061 pcmbuf_crossfade_enable(global_settings.crossfade);
2063 /* initialize the buffering system */
2065 buffering_init();
2066 /* ...now! Set up the buffers */
2067 audio_reset_buffer();
2069 int i;
2070 for(i = 0; i < MAX_TRACK; i++)
2072 tracks[i].audio_hid = -1;
2073 tracks[i].id3_hid = -1;
2074 tracks[i].codec_hid = -1;
2075 tracks[i].cuesheet_hid = -1;
2077 #ifdef HAVE_ALBUMART
2078 FOREACH_ALBUMART(i)
2080 int j;
2081 for (j = 0; j < MAX_TRACK; j++)
2083 tracks[j].aa_hid[i] = -1;
2086 #endif
2088 add_event(BUFFER_EVENT_REBUFFER, false, buffering_handle_rebuffer_callback);
2089 add_event(BUFFER_EVENT_FINISHED, false, buffering_handle_finished_callback);
2091 /* Probably safe to say */
2092 audio_is_initialized = true;
2094 sound_settings_apply();
2095 #ifdef HAVE_DISK_STORAGE
2096 audio_set_buffer_margin(global_settings.buffer_margin);
2097 #endif
2099 /* it's safe to let the threads run now */
2100 #ifdef PLAYBACK_VOICE
2101 voice_thread_resume();
2102 #endif
2103 thread_thaw(codec_thread_id);
2104 thread_thaw(audio_thread_id);
2106 } /* audio_init */
2108 bool audio_is_thread_ready(void)
2110 return audio_thread_ready;
2113 size_t audio_get_filebuflen(void)
2115 return filebuflen;
2118 int get_audio_hid()
2120 return CUR_TI->audio_hid;
2123 int *get_codec_hid()
2125 return &tracks[track_ridx].codec_hid;
2128 bool audio_is_playing(void)
2130 return playing;
2133 bool audio_is_paused(void)
2135 return paused;