playback.c: don't assume cacheline size is 16 bytes
[kugel-rb.git] / apps / playback.c
blobe8a6efc109a4d33aa84a86e038cc945ae0083b50
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 SKINNABLE_SCREENS_COUNT
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 #if (CONFIG_PLATFORM & PLATFORM_NATIVE)
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 #if (CONFIG_PLATFORM & PLATFORM_NATIVE)
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;
528 return thistrack_id3;
530 else if (automatic_skip && offset == -1 && *othertrack_id3->path)
532 /* We're in a track transition. The codec has moved on to the next track,
533 but the audio being played is still the same (now previous) track.
534 othertrack_id3.elapsed is being updated in an ISR by
535 codec_pcmbuf_position_callback */
536 if (tracks[cur_idx].cuesheet_hid >= 0 && !thistrack_id3->cuesheet)
538 bufread(tracks[cur_idx].cuesheet_hid, sizeof(struct cuesheet), curr_cue);
539 othertrack_id3->cuesheet = curr_cue;
541 return othertrack_id3;
544 if (offset != 0)
546 /* Codec may be using thistrack_id3, so it must not be overwritten.
547 If this is a manual skip, othertrack_id3 will become
548 thistrack_id3 in audio_check_new_track().
549 FIXME: If this is an automatic skip, it probably means multiple
550 short tracks fit in the PCM buffer. Overwriting othertrack_id3
551 can lead to an incorrect value later.
552 Note that othertrack_id3 may also be used for next track.
554 write_id3 = othertrack_id3;
556 else
558 write_id3 = thistrack_id3;
561 if (tracks[cur_idx].id3_hid >= 0)
563 /* The current track's info has been buffered but not read yet, so get it */
564 if (bufread(tracks[cur_idx].id3_hid, sizeof(struct mp3entry), write_id3)
565 == sizeof(struct mp3entry))
566 return write_id3;
569 /* We didn't find the ID3 metadata, so we fill temp_id3 with the little info
570 we have and return that. */
572 memset(write_id3, 0, sizeof(struct mp3entry));
574 playlist_get_track_info(NULL, playlist_next(0)+wps_offset, &trackinfo);
575 filename = trackinfo.filename;
576 if (!filename)
577 filename = "No file!";
579 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
580 if (tagcache_fill_tags(write_id3, filename))
581 return write_id3;
582 #endif
584 strlcpy(write_id3->path, filename, sizeof(write_id3->path));
585 write_id3->title = strrchr(write_id3->path, '/');
586 if (!write_id3->title)
587 write_id3->title = &write_id3->path[0];
588 else
589 write_id3->title++;
591 return write_id3;
594 struct mp3entry* audio_next_track(void)
596 int next_idx;
597 int offset = ci.new_track + wps_offset;
599 if (!audio_have_tracks())
600 return NULL;
602 if (wps_offset == -1 && *thistrack_id3->path)
604 /* We're in a track transition. The next track for the WPS is the one
605 currently being decoded. */
606 return thistrack_id3;
609 next_idx = (track_ridx + offset + 1) & MAX_TRACK_MASK;
611 if (tracks[next_idx].id3_hid >= 0)
613 if (bufread(tracks[next_idx].id3_hid, sizeof(struct mp3entry), othertrack_id3)
614 == sizeof(struct mp3entry))
615 return othertrack_id3;
616 else
617 return NULL;
620 if (next_idx == track_widx)
622 /* The next track hasn't been buffered yet, so we return the static
623 version of its metadata. */
624 return &unbuffered_id3;
627 return NULL;
630 /* gets a pointer to the id3 data, Not thread safe!, DON'T yield()/sleep() */
631 bool audio_peek_track(struct mp3entry** id3, int offset)
633 int next_idx;
634 int new_offset = ci.new_track + wps_offset + offset;
636 if (!audio_have_tracks())
637 return false;
638 next_idx = (track_ridx + new_offset) & MAX_TRACK_MASK;
640 if (tracks[next_idx].id3_hid >= 0)
642 return bufgetdata(tracks[next_idx].id3_hid, 0, (void**)id3)
643 == sizeof(struct mp3entry);
645 return false;
648 #ifdef HAVE_ALBUMART
649 int playback_current_aa_hid(int slot)
651 if (slot < 0)
652 return -1;
653 int cur_idx;
654 int offset = ci.new_track + wps_offset;
656 cur_idx = track_ridx + offset;
657 cur_idx &= MAX_TRACK_MASK;
659 return tracks[cur_idx].aa_hid[slot];
662 int playback_claim_aa_slot(struct dim *dim)
664 int i;
665 /* first try to find a slot already having the size to reuse it
666 * since we don't want albumart of the same size buffered multiple times */
667 FOREACH_ALBUMART(i)
669 struct albumart_slot *slot = &albumart_slots[i];
670 if (slot->dim.width == dim->width
671 && slot->dim.height == dim->height)
673 slot->used++;
674 return i;
677 /* size is new, find a free slot */
678 FOREACH_ALBUMART(i)
680 if (!albumart_slots[i].used)
682 albumart_slots[i].used++;
683 albumart_slots[i].dim = *dim;
684 return i;
687 /* sorry, no free slot */
688 return -1;
691 void playback_release_aa_slot(int slot)
693 /* invalidate the albumart_slot */
694 struct albumart_slot *aa_slot = &albumart_slots[slot];
695 if (aa_slot->used > 0)
696 aa_slot->used--;
699 #endif
700 void audio_play(long offset)
702 logf("audio_play");
704 #ifdef PLAYBACK_VOICE
705 /* Truncate any existing voice output so we don't have spelling
706 * etc. over the first part of the played track */
707 talk_force_shutup();
708 #endif
710 /* Start playback */
711 LOGFQUEUE("audio >| audio Q_AUDIO_PLAY: %ld", offset);
712 /* Don't return until playback has actually started */
713 queue_send(&audio_queue, Q_AUDIO_PLAY, offset);
716 void audio_stop(void)
718 /* Stop playback */
719 LOGFQUEUE("audio >| audio Q_AUDIO_STOP");
720 /* Don't return until playback has actually stopped */
721 queue_send(&audio_queue, Q_AUDIO_STOP, 0);
724 void audio_pause(void)
726 LOGFQUEUE("audio >| audio Q_AUDIO_PAUSE");
727 /* Don't return until playback has actually paused */
728 queue_send(&audio_queue, Q_AUDIO_PAUSE, true);
731 void audio_resume(void)
733 LOGFQUEUE("audio >| audio Q_AUDIO_PAUSE resume");
734 /* Don't return until playback has actually resumed */
735 queue_send(&audio_queue, Q_AUDIO_PAUSE, false);
738 void audio_skip(int direction)
740 if (playlist_check(ci.new_track + wps_offset + direction))
742 if (global_settings.beep)
743 pcmbuf_beep(2000, 100, 2500*global_settings.beep);
745 LOGFQUEUE("audio > audio Q_AUDIO_SKIP %d", direction);
746 queue_post(&audio_queue, Q_AUDIO_SKIP, direction);
747 /* Update wps while our message travels inside deep playback queues. */
748 wps_offset += direction;
750 else
752 /* No more tracks. */
753 if (global_settings.beep)
754 pcmbuf_beep(1000, 100, 1500*global_settings.beep);
758 void audio_next(void)
760 audio_skip(1);
763 void audio_prev(void)
765 audio_skip(-1);
768 void audio_next_dir(void)
770 LOGFQUEUE("audio > audio Q_AUDIO_DIR_SKIP 1");
771 queue_post(&audio_queue, Q_AUDIO_DIR_SKIP, 1);
774 void audio_prev_dir(void)
776 LOGFQUEUE("audio > audio Q_AUDIO_DIR_SKIP -1");
777 queue_post(&audio_queue, Q_AUDIO_DIR_SKIP, -1);
780 void audio_pre_ff_rewind(void)
782 LOGFQUEUE("audio > audio Q_AUDIO_PRE_FF_REWIND");
783 queue_post(&audio_queue, Q_AUDIO_PRE_FF_REWIND, 0);
786 void audio_ff_rewind(long newpos)
788 LOGFQUEUE("audio > audio Q_AUDIO_FF_REWIND");
789 queue_post(&audio_queue, Q_AUDIO_FF_REWIND, newpos);
792 void audio_flush_and_reload_tracks(void)
794 LOGFQUEUE("audio > audio Q_AUDIO_FLUSH");
795 queue_post(&audio_queue, Q_AUDIO_FLUSH, 0);
798 void audio_error_clear(void)
800 #ifdef AUDIO_HAVE_RECORDING
801 pcm_rec_error_clear();
802 #endif
805 int audio_status(void)
807 int ret = 0;
809 if (playing)
810 ret |= AUDIO_STATUS_PLAY;
812 if (paused)
813 ret |= AUDIO_STATUS_PAUSE;
815 #ifdef HAVE_RECORDING
816 /* Do this here for constitency with mpeg.c version */
817 /* FIXME: pcm_rec_status() is deprecated */
818 ret |= pcm_rec_status();
819 #endif
821 return ret;
824 int audio_get_file_pos(void)
826 return 0;
829 #ifdef HAVE_DISK_STORAGE
830 void audio_set_buffer_margin(int setting)
832 static const unsigned short lookup[] = {5, 15, 30, 60, 120, 180, 300, 600};
833 buffer_margin = lookup[setting];
834 logf("buffer margin: %ld", (long)buffer_margin);
835 set_filebuf_watermark();
837 #endif
839 #ifdef HAVE_CROSSFADE
840 /* Take necessary steps to enable or disable the crossfade setting */
841 void audio_set_crossfade(int enable)
843 size_t offset;
844 bool was_playing;
845 size_t size;
847 /* Tell it the next setting to use */
848 pcmbuf_request_crossfade_enable(enable);
850 /* Return if size hasn't changed or this is too early to determine
851 which in the second case there's no way we could be playing
852 anything at all */
853 if (pcmbuf_is_same_size()) return;
855 offset = 0;
856 was_playing = playing;
858 /* Playback has to be stopped before changing the buffer size */
859 if (was_playing)
861 /* Store the track resume position */
862 offset = thistrack_id3->offset;
865 /* Blast it - audio buffer will have to be setup again next time
866 something plays */
867 audio_get_buffer(true, &size);
869 /* Restart playback if audio was running previously */
870 if (was_playing)
871 audio_play(offset);
873 #endif
875 /* --- Routines called from multiple threads --- */
877 static void set_filebuf_watermark(void)
879 if (!filebuf)
880 return; /* Audio buffers not yet set up */
882 #ifdef HAVE_DISK_STORAGE
883 int seconds;
884 int spinup = ata_spinup_time();
885 if (spinup)
886 seconds = (spinup / HZ) + 1;
887 else
888 seconds = 5;
890 seconds += buffer_margin;
891 #else
892 /* flash storage */
893 int seconds = 1;
894 #endif
896 /* bitrate of last track in buffer dictates watermark */
897 struct mp3entry* id3 = NULL;
898 if (tracks[track_widx].taginfo_ready)
899 id3 = bufgetid3(tracks[track_widx].id3_hid);
900 else
901 id3 = bufgetid3(tracks[track_widx-1].id3_hid);
902 if (!id3) {
903 logf("fwmark: No id3 for last track (r%d/w%d), aborting!", track_ridx, track_widx);
904 return;
906 size_t bytes = id3->bitrate * (1000/8) * seconds;
907 buf_set_watermark(bytes);
908 logf("fwmark: %d", bytes);
911 /* --- Buffering callbacks --- */
913 static void buffering_low_buffer_callback(void *data)
915 (void)data;
916 logf("low buffer callback");
918 if (filling == STATE_FULL || filling == STATE_END_OF_PLAYLIST) {
919 /* force a refill */
920 LOGFQUEUE("buffering > audio Q_AUDIO_FILL_BUFFER");
921 queue_post(&audio_queue, Q_AUDIO_FILL_BUFFER, 0);
925 static void buffering_handle_rebuffer_callback(void *data)
927 (void)data;
928 LOGFQUEUE("audio >| audio Q_AUDIO_FLUSH");
929 queue_post(&audio_queue, Q_AUDIO_FLUSH, 0);
932 static void buffering_handle_finished_callback(void *data)
934 logf("handle %d finished buffering", *(int*)data);
935 int hid = (*(int*)data);
937 if (hid == tracks[track_widx].id3_hid)
939 int offset = ci.new_track + wps_offset;
940 int next_idx = (track_ridx + offset + 1) & MAX_TRACK_MASK;
941 /* The metadata handle for the last loaded track has been buffered.
942 We can ask the audio thread to load the rest of the track's data. */
943 LOGFQUEUE("audio >| audio Q_AUDIO_FINISH_LOAD");
944 queue_post(&audio_queue, Q_AUDIO_FINISH_LOAD, 0);
945 if (tracks[next_idx].id3_hid == hid)
946 send_event(PLAYBACK_EVENT_NEXTTRACKID3_AVAILABLE, NULL);
948 else
950 /* This is most likely an audio handle, so we strip the useless
951 trailing tags that are left. */
952 strip_tags(hid);
954 if (hid == tracks[track_widx-1].audio_hid
955 && filling == STATE_END_OF_PLAYLIST)
957 /* This was the last track in the playlist.
958 We now have all the data we need. */
959 logf("last track finished buffering");
960 filling = STATE_FINISHED;
966 /* --- Audio thread --- */
968 static bool audio_have_tracks(void)
970 return (audio_track_count() != 0);
973 static int audio_free_track_count(void)
975 /* Used tracks + free tracks adds up to MAX_TRACK - 1 */
976 return MAX_TRACK - 1 - audio_track_count();
979 int audio_track_count(void)
981 /* Calculate difference from track_ridx to track_widx
982 * taking into account a possible wrap-around. */
983 return (MAX_TRACK + track_widx - track_ridx) & MAX_TRACK_MASK;
986 long audio_filebufused(void)
988 return (long) buf_used();
991 /* Update track info after successful a codec track change */
992 static void audio_update_trackinfo(void)
994 /* Load the curent track's metadata into curtrack_id3 */
995 if (CUR_TI->id3_hid >= 0)
996 copy_mp3entry(thistrack_id3, bufgetid3(CUR_TI->id3_hid));
998 /* Reset current position */
999 thistrack_id3->elapsed = 0;
1000 thistrack_id3->offset = 0;
1002 /* Update the codec API */
1003 ci.filesize = CUR_TI->filesize;
1004 ci.id3 = thistrack_id3;
1005 ci.curpos = 0;
1006 ci.taginfo_ready = &CUR_TI->taginfo_ready;
1009 /* Clear tracks between write and read, non inclusive */
1010 static void audio_clear_track_entries(void)
1012 int cur_idx = track_widx;
1014 logf("Clearing tracks: r%d/w%d", track_ridx, track_widx);
1016 /* Loop over all tracks from write-to-read */
1017 while (1)
1019 cur_idx = (cur_idx + 1) & MAX_TRACK_MASK;
1021 if (cur_idx == track_ridx)
1022 break;
1024 clear_track_info(&tracks[cur_idx]);
1028 /* Clear all tracks */
1029 static bool audio_release_tracks(void)
1031 int i, cur_idx;
1033 logf("releasing all tracks");
1035 for(i = 0; i < MAX_TRACK; i++)
1037 cur_idx = (track_ridx + i) & MAX_TRACK_MASK;
1038 if (!clear_track_info(&tracks[cur_idx]))
1039 return false;
1042 return true;
1045 static bool audio_loadcodec(bool start_play)
1047 int prev_track;
1048 char codec_path[MAX_PATH]; /* Full path to codec */
1049 const struct mp3entry *id3, *prev_id3;
1051 if (tracks[track_widx].id3_hid < 0) {
1052 return false;
1055 id3 = bufgetid3(tracks[track_widx].id3_hid);
1056 if (!id3)
1057 return false;
1059 const char *codec_fn = get_codec_filename(id3->codectype);
1060 if (codec_fn == NULL)
1061 return false;
1063 tracks[track_widx].codec_hid = -1;
1065 if (start_play)
1067 /* Load the codec directly from disk and save some memory. */
1068 track_ridx = track_widx;
1069 ci.filesize = CUR_TI->filesize;
1070 ci.id3 = thistrack_id3;
1071 ci.taginfo_ready = &CUR_TI->taginfo_ready;
1072 ci.curpos = 0;
1073 LOGFQUEUE("codec > codec Q_CODEC_LOAD_DISK");
1074 queue_post(&codec_queue, Q_CODEC_LOAD_DISK, (intptr_t)codec_fn);
1075 return true;
1077 else
1079 /* If we already have another track than this one buffered */
1080 if (track_widx != track_ridx)
1082 prev_track = (track_widx - 1) & MAX_TRACK_MASK;
1084 id3 = bufgetid3(tracks[track_widx].id3_hid);
1085 prev_id3 = bufgetid3(tracks[prev_track].id3_hid);
1087 /* If the previous codec is the same as this one, there is no need
1088 * to put another copy of it on the file buffer */
1089 if (id3 && prev_id3 &&
1090 get_codec_base_type(id3->codectype) ==
1091 get_codec_base_type(prev_id3->codectype)
1092 && audio_codec_loaded)
1094 logf("Reusing prev. codec");
1095 return true;
1100 codec_get_full_path(codec_path, codec_fn);
1102 tracks[track_widx].codec_hid = bufopen(codec_path, 0, TYPE_CODEC, NULL);
1103 if (tracks[track_widx].codec_hid < 0)
1104 return false;
1106 logf("Loaded codec");
1108 return true;
1111 /* Load metadata for the next track (with bufopen). The rest of the track
1112 loading will be handled by audio_finish_load_track once the metadata has been
1113 actually loaded by the buffering thread. */
1114 static bool audio_load_track(size_t offset, bool start_play)
1116 const char *trackname;
1117 int fd = -1;
1119 if (track_load_started) {
1120 /* There is already a track load in progress, so track_widx hasn't been
1121 incremented yet. Loading another track would overwrite the one that
1122 hasn't finished loading. */
1123 logf("audio_load_track(): a track load is already in progress");
1124 return false;
1127 start_play_g = start_play; /* will be read by audio_finish_load_track */
1129 /* Stop buffer filling if there is no free track entries.
1130 Don't fill up the last track entry (we wan't to store next track
1131 metadata there). */
1132 if (!audio_free_track_count())
1134 logf("No free tracks");
1135 return false;
1138 last_peek_offset++;
1139 tracks[track_widx].taginfo_ready = false;
1141 logf("Buffering track: r%d/w%d", track_ridx, track_widx);
1142 /* Get track name from current playlist read position. */
1143 while ((trackname = playlist_peek(last_peek_offset)) != NULL)
1145 /* Handle broken playlists. */
1146 fd = open(trackname, O_RDONLY);
1147 if (fd < 0)
1149 logf("Open failed");
1150 /* Skip invalid entry from playlist. */
1151 playlist_skip_entry(NULL, last_peek_offset);
1153 else
1154 break;
1157 if (!trackname)
1159 logf("End-of-playlist");
1160 memset(&unbuffered_id3, 0, sizeof(struct mp3entry));
1161 filling = STATE_END_OF_PLAYLIST;
1163 if (thistrack_id3->length == 0 && thistrack_id3->filesize == 0)
1165 /* Stop playback if no valid track was found. */
1166 audio_stop_playback();
1169 return false;
1172 tracks[track_widx].filesize = filesize(fd);
1174 if (offset > tracks[track_widx].filesize)
1175 offset = 0;
1177 /* Set default values */
1178 if (start_play)
1180 buf_set_watermark(filebuflen/2);
1181 dsp_configure(ci.dsp, DSP_RESET, 0);
1182 playlist_update_resume_info(audio_current_track());
1185 /* Get track metadata if we don't already have it. */
1186 if (tracks[track_widx].id3_hid < 0)
1188 tracks[track_widx].id3_hid = bufopen(trackname, 0, TYPE_ID3, NULL);
1190 if (tracks[track_widx].id3_hid < 0)
1192 /* Buffer is full. */
1193 get_metadata(&unbuffered_id3, fd, trackname);
1194 last_peek_offset--;
1195 close(fd);
1196 logf("buffer is full for now (get metadata)");
1197 filling = STATE_FULL;
1198 return false;
1201 if (track_widx == track_ridx)
1203 /* TODO: Superfluos buffering call? */
1204 buf_request_buffer_handle(tracks[track_widx].id3_hid);
1205 struct mp3entry *id3 = bufgetid3(tracks[track_widx].id3_hid);
1206 if (id3)
1208 copy_mp3entry(thistrack_id3, id3);
1209 thistrack_id3->offset = offset;
1211 else
1212 memset(thistrack_id3, 0, sizeof(struct mp3entry));
1215 if (start_play)
1217 playlist_update_resume_info(audio_current_track());
1221 close(fd);
1222 track_load_started = true; /* Remember that we've started loading a track */
1223 return true;
1226 /* Second part of the track loading: We now have the metadata available, so we
1227 can load the codec, the album art and finally the audio data.
1228 This is called on the audio thread after the buffering thread calls the
1229 buffering_handle_finished_callback callback. */
1230 static void audio_finish_load_track(void)
1232 size_t file_offset = 0;
1233 size_t offset = 0;
1234 bool start_play = start_play_g;
1236 track_load_started = false;
1238 if (tracks[track_widx].id3_hid < 0) {
1239 logf("No metadata");
1240 return;
1243 struct mp3entry *track_id3;
1245 if (track_widx == track_ridx)
1246 track_id3 = thistrack_id3;
1247 else
1248 track_id3 = bufgetid3(tracks[track_widx].id3_hid);
1250 if (track_id3->length == 0 && track_id3->filesize == 0)
1252 logf("audio_finish_load_track: invalid metadata");
1254 /* Invalid metadata */
1255 bufclose(tracks[track_widx].id3_hid);
1256 tracks[track_widx].id3_hid = -1;
1258 /* Skip invalid entry from playlist. */
1259 playlist_skip_entry(NULL, last_peek_offset--);
1261 /* load next track */
1262 LOGFQUEUE("audio > audio Q_AUDIO_FILL_BUFFER %d", (int)start_play);
1263 queue_post(&audio_queue, Q_AUDIO_FILL_BUFFER, start_play);
1265 return;
1267 /* Try to load a cuesheet for the track */
1268 if (curr_cue)
1270 char cuepath[MAX_PATH];
1271 if (look_for_cuesheet_file(track_id3->path, cuepath))
1273 void *temp;
1274 tracks[track_widx].cuesheet_hid =
1275 bufalloc(NULL, sizeof(struct cuesheet), TYPE_CUESHEET);
1276 if (tracks[track_widx].cuesheet_hid >= 0)
1278 bufgetdata(tracks[track_widx].cuesheet_hid,
1279 sizeof(struct cuesheet), &temp);
1280 struct cuesheet *cuesheet = (struct cuesheet*)temp;
1281 if (!parse_cuesheet(cuepath, cuesheet))
1283 bufclose(tracks[track_widx].cuesheet_hid);
1284 track_id3->cuesheet = NULL;
1289 #ifdef HAVE_ALBUMART
1291 int i;
1292 char aa_path[MAX_PATH];
1293 FOREACH_ALBUMART(i)
1295 /* albumart_slots may change during a yield of bufopen,
1296 * but that's no problem */
1297 if (tracks[track_widx].aa_hid[i] >= 0 || !albumart_slots[i].used)
1298 continue;
1299 /* find_albumart will error out if the wps doesn't have AA */
1300 if (find_albumart(track_id3, aa_path, sizeof(aa_path),
1301 &(albumart_slots[i].dim)))
1303 int aa_hid = bufopen(aa_path, 0, TYPE_BITMAP,
1304 &(albumart_slots[i].dim));
1306 if(aa_hid == ERR_BUFFER_FULL)
1308 filling = STATE_FULL;
1309 logf("buffer is full for now (get album art)");
1310 return; /* No space for track's album art, not an error */
1312 else if (aa_hid < 0)
1314 /* another error, ignore AlbumArt */
1315 logf("Album art loading failed");
1317 tracks[track_widx].aa_hid[i] = aa_hid;
1322 #endif
1324 /* Load the codec. */
1325 if (!audio_loadcodec(start_play))
1327 if (tracks[track_widx].codec_hid == ERR_BUFFER_FULL)
1329 /* No space for codec on buffer, not an error */
1330 filling = STATE_FULL;
1331 return;
1334 /* This is an error condition, either no codec was found, or reading
1335 * the codec file failed part way through, either way, skip the track */
1336 /* FIXME: We should not use splashf from audio thread! */
1337 splashf(HZ*2, "No codec for: %s", track_id3->path);
1338 /* Skip invalid entry from playlist. */
1339 playlist_skip_entry(NULL, last_peek_offset);
1340 return;
1343 track_id3->elapsed = 0;
1344 offset = track_id3->offset;
1345 size_t resume_rewind = (global_settings.resume_rewind *
1346 track_id3->bitrate * 1000) / 8;
1348 if (offset < resume_rewind)
1350 offset = 0;
1352 else
1354 offset -= resume_rewind;
1357 enum data_type type = TYPE_PACKET_AUDIO;
1359 switch (track_id3->codectype) {
1360 case AFMT_MPA_L1:
1361 case AFMT_MPA_L2:
1362 case AFMT_MPA_L3:
1363 if (offset > 0) {
1364 file_offset = offset;
1366 break;
1368 case AFMT_WAVPACK:
1369 if (offset > 0) {
1370 file_offset = offset;
1371 track_id3->elapsed = track_id3->length / 2;
1373 break;
1375 case AFMT_NSF:
1376 case AFMT_SPC:
1377 case AFMT_SID:
1378 logf("Loading atomic %d",track_id3->codectype);
1379 type = TYPE_ATOMIC_AUDIO;
1380 break;
1382 default:
1383 /* no special treatment needed */
1384 break;
1387 track_id3->offset = offset;
1389 logf("load track: %s", track_id3->path);
1391 if (file_offset > AUDIO_REBUFFER_GUESS_SIZE)
1392 file_offset -= AUDIO_REBUFFER_GUESS_SIZE;
1393 else if (track_id3->first_frame_offset)
1394 file_offset = track_id3->first_frame_offset;
1395 else
1396 file_offset = 0;
1398 tracks[track_widx].audio_hid = bufopen(track_id3->path, file_offset, type,
1399 NULL);
1401 /* No space left, not an error */
1402 if (tracks[track_widx].audio_hid == ERR_BUFFER_FULL)
1404 filling = STATE_FULL;
1405 logf("buffer is full for now (load audio)");
1406 return;
1408 else if (tracks[track_widx].audio_hid < 0)
1410 /* another error, do not continue either */
1411 logf("Could not add audio data handle");
1412 return;
1415 /* All required data is now available for the codec. */
1416 tracks[track_widx].taginfo_ready = true;
1418 if (start_play)
1420 ci.curpos=file_offset;
1421 buf_request_buffer_handle(tracks[track_widx].audio_hid);
1424 track_widx = (track_widx + 1) & MAX_TRACK_MASK;
1426 send_event(PLAYBACK_EVENT_TRACK_BUFFER, track_id3);
1428 /* load next track */
1429 LOGFQUEUE("audio > audio Q_AUDIO_FILL_BUFFER");
1430 queue_post(&audio_queue, Q_AUDIO_FILL_BUFFER, 0);
1432 return;
1435 static void audio_fill_file_buffer(bool start_play, size_t offset)
1437 trigger_cpu_boost();
1439 /* No need to rebuffer if there are track skips pending,
1440 * however don't cancel buffering on skipping while filling. */
1441 if (ci.new_track != 0 && filling != STATE_FILLING)
1442 return;
1443 filling = STATE_FILLING;
1445 /* Must reset the buffer before use if trashed or voice only - voice
1446 file size shouldn't have changed so we can go straight from
1447 AUDIOBUF_STATE_VOICED_ONLY to AUDIOBUF_STATE_INITIALIZED */
1448 if (buffer_state != AUDIOBUF_STATE_INITIALIZED)
1449 audio_reset_buffer();
1451 logf("Starting buffer fill");
1453 if (!start_play)
1454 audio_clear_track_entries();
1456 /* Save the current resume position once. */
1457 playlist_update_resume_info(audio_current_track());
1459 audio_load_track(offset, start_play);
1462 static void audio_rebuffer(void)
1464 logf("Forcing rebuffer");
1466 clear_track_info(CUR_TI);
1468 /* Reset track pointers */
1469 track_widx = track_ridx;
1470 audio_clear_track_entries();
1472 /* Reset a possibly interrupted track load */
1473 track_load_started = false;
1475 /* Fill the buffer */
1476 last_peek_offset = -1;
1477 ci.curpos = 0;
1479 if (!CUR_TI->taginfo_ready)
1480 memset(thistrack_id3, 0, sizeof(struct mp3entry));
1482 audio_fill_file_buffer(false, 0);
1485 /* Called on request from the codec to get a new track. This is the codec part
1486 of the track transition. */
1487 static int audio_check_new_track(void)
1489 int track_count = audio_track_count();
1490 int old_track_ridx = track_ridx;
1491 int i, idx;
1492 bool forward;
1493 struct mp3entry *temp = thistrack_id3;
1495 /* Now it's good time to send track finish events. */
1496 send_event(PLAYBACK_EVENT_TRACK_FINISH, thistrack_id3);
1497 /* swap the mp3entry pointers */
1498 thistrack_id3 = othertrack_id3;
1499 othertrack_id3 = temp;
1500 ci.id3 = thistrack_id3;
1501 memset(thistrack_id3, 0, sizeof(struct mp3entry));
1503 if (dir_skip)
1505 dir_skip = false;
1506 /* regardless of the return value we need to rebuffer.
1507 if it fails the old playlist will resume, else the
1508 next dir will start playing */
1509 playlist_next_dir(ci.new_track);
1510 ci.new_track = 0;
1511 audio_rebuffer();
1512 goto skip_done;
1515 if (new_playlist)
1516 ci.new_track = 0;
1518 /* If the playlist isn't that big */
1519 if (automatic_skip)
1521 while (!playlist_check(ci.new_track))
1523 if (ci.new_track >= 0)
1525 LOGFQUEUE("audio >|= codec Q_CODEC_REQUEST_FAILED");
1526 return Q_CODEC_REQUEST_FAILED;
1528 ci.new_track++;
1532 /* Update the playlist */
1533 last_peek_offset -= ci.new_track;
1535 if (playlist_next(ci.new_track) < 0)
1537 LOGFQUEUE("audio >|= codec Q_CODEC_REQUEST_FAILED");
1538 return Q_CODEC_REQUEST_FAILED;
1541 if (new_playlist)
1543 ci.new_track = 1;
1544 new_playlist = false;
1547 /* Save a pointer to the old track to allow later clearing */
1548 prev_ti = CUR_TI;
1550 for (i = 0; i < ci.new_track; i++)
1552 idx = (track_ridx + i) & MAX_TRACK_MASK;
1553 struct mp3entry *id3 = bufgetid3(tracks[idx].id3_hid);
1554 ssize_t offset = buf_handle_offset(tracks[idx].audio_hid);
1555 if (!id3 || offset < 0 || (unsigned)offset > id3->first_frame_offset)
1557 /* We don't have all the audio data for that track, so clear it,
1558 but keep the metadata. */
1559 if (tracks[idx].audio_hid >= 0 && bufclose(tracks[idx].audio_hid))
1561 tracks[idx].audio_hid = -1;
1562 tracks[idx].filesize = 0;
1567 /* Move to the new track */
1568 track_ridx = (track_ridx + ci.new_track) & MAX_TRACK_MASK;
1569 buf_set_base_handle(CUR_TI->audio_hid);
1572 if (automatic_skip)
1574 wps_offset = -ci.new_track;
1577 /* If it is not safe to even skip this many track entries */
1578 if (ci.new_track >= track_count || ci.new_track <= track_count - MAX_TRACK)
1580 ci.new_track = 0;
1581 audio_rebuffer();
1582 goto skip_done;
1585 forward = ci.new_track > 0;
1586 ci.new_track = 0;
1588 /* If the target track is clearly not in memory */
1589 if (CUR_TI->filesize == 0 || !CUR_TI->taginfo_ready)
1591 audio_rebuffer();
1592 goto skip_done;
1595 /* When skipping backwards, it is possible that we've found a track that's
1596 * buffered, but which is around the track-wrap and therefore not the track
1597 * we are looking for */
1598 if (!forward)
1600 int cur_idx = track_ridx;
1601 bool taginfo_ready = true;
1602 /* We've wrapped the buffer backwards if new > old */
1603 bool wrap = track_ridx > old_track_ridx;
1605 while (1)
1607 cur_idx = (cur_idx + 1) & MAX_TRACK_MASK;
1609 /* if we've advanced past the wrap when cur_idx is zeroed */
1610 if (!cur_idx)
1611 wrap = false;
1613 /* if we aren't still on the wrap and we've caught the old track */
1614 if (!(wrap || cur_idx < old_track_ridx))
1615 break;
1617 /* If we hit a track in between without valid tag info, bail */
1618 if (!tracks[cur_idx].taginfo_ready)
1620 taginfo_ready = false;
1621 break;
1624 if (!taginfo_ready)
1626 audio_rebuffer();
1630 skip_done:
1631 audio_update_trackinfo();
1632 LOGFQUEUE("audio >|= codec Q_CODEC_REQUEST_COMPLETE");
1633 return Q_CODEC_REQUEST_COMPLETE;
1636 unsigned long audio_prev_elapsed(void)
1638 return prev_track_elapsed;
1641 void audio_set_prev_elapsed(unsigned long setting)
1643 prev_track_elapsed = setting;
1646 static void audio_stop_codec_flush(void)
1648 ci.stop_codec = true;
1649 pcmbuf_pause(true);
1651 while (audio_codec_loaded)
1652 yield();
1654 /* If the audio codec is not loaded any more, and the audio is still
1655 * playing, it is now and _only_ now safe to call this function from the
1656 * audio thread */
1657 if (pcm_is_playing())
1659 pcmbuf_play_stop();
1660 pcm_play_lock();
1661 queue_clear(&pcmbuf_queue);
1662 pcm_play_unlock();
1664 pcmbuf_pause(paused);
1667 static void audio_stop_playback(void)
1669 if (playing)
1671 /* If we were playing, save resume information */
1672 struct mp3entry *id3 = NULL;
1674 if (!ci.stop_codec)
1676 /* Set this early, the outside code yields and may allow the codec
1677 to try to wait for a reply on a buffer wait */
1678 ci.stop_codec = true;
1679 id3 = audio_current_track();
1682 /* Save the current playing spot, or NULL if the playlist has ended */
1683 playlist_update_resume_info(id3);
1685 /* TODO: Create auto bookmark too? */
1687 prev_track_elapsed = othertrack_id3->elapsed;
1689 remove_event(BUFFER_EVENT_BUFFER_LOW, buffering_low_buffer_callback);
1692 audio_stop_codec_flush();
1693 paused = false;
1694 playing = false;
1695 track_load_started = false;
1697 filling = STATE_IDLE;
1699 /* Mark all entries null. */
1700 audio_clear_track_entries();
1702 /* Close all tracks */
1703 audio_release_tracks();
1706 static void audio_play_start(size_t offset)
1708 int i;
1710 send_event(PLAYBACK_EVENT_START_PLAYBACK, NULL);
1711 #if INPUT_SRC_CAPS != 0
1712 audio_set_input_source(AUDIO_SRC_PLAYBACK, SRCF_PLAYBACK);
1713 audio_set_output_source(AUDIO_SRC_PLAYBACK);
1714 #endif
1716 /* Wait for any previously playing audio to flush - TODO: Not necessary? */
1717 paused = false;
1718 audio_stop_codec_flush();
1720 playing = true;
1721 track_load_started = false;
1723 ci.new_track = 0;
1724 ci.seek_time = 0;
1725 wps_offset = 0;
1727 sound_set_volume(global_settings.volume);
1728 track_widx = track_ridx = 0;
1729 buf_set_base_handle(-1);
1731 /* Clear all track entries. */
1732 for (i = 0; i < MAX_TRACK; i++) {
1733 clear_track_info(&tracks[i]);
1736 last_peek_offset = -1;
1738 /* Officially playing */
1739 queue_reply(&audio_queue, 1);
1741 audio_fill_file_buffer(true, offset);
1743 add_event(BUFFER_EVENT_BUFFER_LOW, false, buffering_low_buffer_callback);
1745 LOGFQUEUE("audio > audio Q_AUDIO_TRACK_CHANGED");
1746 queue_post(&audio_queue, Q_AUDIO_TRACK_CHANGED, 0);
1750 /* Invalidates all but currently playing track. */
1751 static void audio_invalidate_tracks(void)
1753 if (audio_have_tracks())
1755 last_peek_offset = 0;
1756 track_widx = track_ridx;
1758 /* Mark all other entries null (also buffered wrong metadata). */
1759 audio_clear_track_entries();
1761 track_widx = (track_widx + 1) & MAX_TRACK_MASK;
1763 audio_fill_file_buffer(false, 0);
1764 send_event(PLAYBACK_EVENT_TRACK_CHANGE, thistrack_id3);
1768 static void audio_new_playlist(void)
1770 /* Prepare to start a new fill from the beginning of the playlist */
1771 last_peek_offset = -1;
1772 if (audio_have_tracks())
1774 if (paused)
1775 skipped_during_pause = true;
1776 track_widx = track_ridx;
1777 audio_clear_track_entries();
1779 track_widx = (track_widx + 1) & MAX_TRACK_MASK;
1781 /* Mark the current track as invalid to prevent skipping back to it */
1782 CUR_TI->taginfo_ready = false;
1785 /* Signal the codec to initiate a track change forward */
1786 new_playlist = true;
1787 ci.new_track = 1;
1789 /* Officially playing */
1790 queue_reply(&audio_queue, 1);
1792 audio_fill_file_buffer(false, 0);
1795 /* Called on manual track skip */
1796 static void audio_initiate_track_change(long direction)
1798 logf("audio_initiate_track_change(%ld)", direction);
1800 ci.new_track += direction;
1801 wps_offset -= direction;
1802 if (paused)
1803 skipped_during_pause = true;
1806 /* Called on manual dir skip */
1807 static void audio_initiate_dir_change(long direction)
1809 dir_skip = true;
1810 ci.new_track = direction;
1811 if (paused)
1812 skipped_during_pause = true;
1815 /* Called when PCM track change is complete */
1816 static void audio_finalise_track_change(void)
1818 logf("audio_finalise_track_change");
1820 if (automatic_skip)
1822 wps_offset = 0;
1823 automatic_skip = false;
1825 /* Invalidate prevtrack_id3 */
1826 memset(othertrack_id3, 0, sizeof(struct mp3entry));
1828 if (prev_ti && prev_ti->audio_hid < 0)
1830 /* No audio left so we clear all the track info. */
1831 clear_track_info(prev_ti);
1834 send_event(PLAYBACK_EVENT_TRACK_CHANGE, thistrack_id3);
1835 playlist_update_resume_info(audio_current_track());
1839 * Layout audio buffer as follows - iram buffer depends on target:
1840 * [|SWAP:iram][|TALK]|FILE|GUARD|PCM|[SWAP:dram[|iram]|]
1842 static void audio_reset_buffer(void)
1844 /* see audio_get_recording_buffer if this is modified */
1845 logf("audio_reset_buffer");
1847 /* If the setup of anything allocated before the file buffer is
1848 changed, do check the adjustments after the buffer_alloc call
1849 as it will likely be affected and need sliding over */
1851 /* Initially set up file buffer as all space available */
1852 malloc_buf = audiobuf + talk_get_bufsize();
1854 /* Align the malloc buf to line size.
1855 * Especially important to cf targets that do line reads/writes.
1856 * Also for targets which need aligned DMA storage buffers */
1857 malloc_buf = (unsigned char *)(((uintptr_t)malloc_buf + (CACHEALIGN_SIZE - 1)) & ~(CACHEALIGN_SIZE - 1));
1858 filebuf = malloc_buf; /* filebuf line align implied */
1859 filebuflen = (audiobufend - filebuf) & ~(CACHEALIGN_SIZE - 1);
1861 /* Subtract whatever the pcm buffer says it used plus the guard buffer */
1862 const size_t pcmbuf_size = pcmbuf_init(filebuf + filebuflen) +GUARD_BUFSIZE;
1864 #ifdef DEBUG
1865 if(pcmbuf_size > filebuflen)
1866 panicf("Not enough memory for pcmbuf_init() : %d > %d",
1867 (int)pcmbuf_size, (int)filebuflen);
1868 #endif
1870 filebuflen -= pcmbuf_size;
1872 /* Make sure filebuflen is a longword multiple after adjustment - filebuf
1873 will already be line aligned */
1874 filebuflen &= ~3;
1876 buffering_reset(filebuf, filebuflen);
1878 /* Clear any references to the file buffer */
1879 buffer_state = AUDIOBUF_STATE_INITIALIZED;
1881 #if defined(ROCKBOX_HAS_LOGF) && defined(LOGF_ENABLE)
1882 /* Make sure everything adds up - yes, some info is a bit redundant but
1883 aids viewing and the sumation of certain variables should add up to
1884 the location of others. */
1886 size_t pcmbufsize;
1887 const unsigned char *pcmbuf = pcmbuf_get_meminfo(&pcmbufsize);
1888 logf("mabuf: %08X", (unsigned)malloc_buf);
1889 logf("fbuf: %08X", (unsigned)filebuf);
1890 logf("fbufe: %08X", (unsigned)(filebuf + filebuflen));
1891 logf("gbuf: %08X", (unsigned)(filebuf + filebuflen));
1892 logf("gbufe: %08X", (unsigned)(filebuf + filebuflen + GUARD_BUFSIZE));
1893 logf("pcmb: %08X", (unsigned)pcmbuf);
1894 logf("pcmbe: %08X", (unsigned)(pcmbuf + pcmbufsize));
1896 #endif
1899 static void audio_thread(void)
1901 struct queue_event ev;
1903 pcm_postinit();
1905 audio_thread_ready = true;
1907 while (1)
1909 if (filling != STATE_FILLING && filling != STATE_IDLE) {
1910 /* End of buffering, let's calculate the watermark and unboost */
1911 set_filebuf_watermark();
1912 cancel_cpu_boost();
1915 if (!pcmbuf_queue_scan(&ev))
1916 queue_wait_w_tmo(&audio_queue, &ev, HZ/2);
1918 switch (ev.id) {
1920 case Q_AUDIO_FILL_BUFFER:
1921 LOGFQUEUE("audio < Q_AUDIO_FILL_BUFFER %d", (int)ev.data);
1922 audio_fill_file_buffer((bool)ev.data, 0);
1923 break;
1925 case Q_AUDIO_FINISH_LOAD:
1926 LOGFQUEUE("audio < Q_AUDIO_FINISH_LOAD");
1927 audio_finish_load_track();
1928 buf_set_base_handle(CUR_TI->audio_hid);
1929 break;
1931 case Q_AUDIO_PLAY:
1932 LOGFQUEUE("audio < Q_AUDIO_PLAY");
1933 if (playing && ev.data <= 0)
1934 audio_new_playlist();
1935 else
1937 audio_stop_playback();
1938 audio_play_start((size_t)ev.data);
1940 break;
1942 case Q_AUDIO_STOP:
1943 LOGFQUEUE("audio < Q_AUDIO_STOP");
1944 if (playing)
1945 audio_stop_playback();
1946 if (ev.data != 0)
1947 queue_clear(&audio_queue);
1948 break;
1950 case Q_AUDIO_PAUSE:
1951 LOGFQUEUE("audio < Q_AUDIO_PAUSE");
1952 if (!(bool) ev.data && skipped_during_pause
1953 #ifdef HAVE_CROSSFADE
1954 && !pcmbuf_is_crossfade_active()
1955 #endif
1957 pcmbuf_play_stop(); /* Flush old track on resume after skip */
1958 skipped_during_pause = false;
1959 if (!playing)
1960 break;
1961 pcmbuf_pause((bool)ev.data);
1962 paused = (bool)ev.data;
1963 break;
1965 case Q_AUDIO_SKIP:
1966 LOGFQUEUE("audio < Q_AUDIO_SKIP");
1967 audio_initiate_track_change((long)ev.data);
1968 break;
1970 case Q_AUDIO_PRE_FF_REWIND:
1971 LOGFQUEUE("audio < Q_AUDIO_PRE_FF_REWIND");
1972 if (!playing)
1973 break;
1974 pcmbuf_pause(true);
1975 break;
1977 case Q_AUDIO_FF_REWIND:
1978 LOGFQUEUE("audio < Q_AUDIO_FF_REWIND");
1979 if (!playing)
1980 break;
1981 if (automatic_skip)
1983 /* An automatic track skip is in progress. Finalize it,
1984 then go back to the previous track */
1985 audio_finalise_track_change();
1986 ci.new_track = -1;
1988 ci.seek_time = (long)ev.data+1;
1989 break;
1991 case Q_AUDIO_CHECK_NEW_TRACK:
1992 LOGFQUEUE("audio < Q_AUDIO_CHECK_NEW_TRACK");
1993 queue_reply(&audio_queue, audio_check_new_track());
1994 break;
1996 case Q_AUDIO_DIR_SKIP:
1997 LOGFQUEUE("audio < Q_AUDIO_DIR_SKIP");
1998 audio_initiate_dir_change(ev.data);
1999 break;
2001 case Q_AUDIO_FLUSH:
2002 LOGFQUEUE("audio < Q_AUDIO_FLUSH");
2003 audio_invalidate_tracks();
2004 break;
2006 case Q_AUDIO_TRACK_CHANGED:
2007 /* PCM track change done */
2008 LOGFQUEUE("audio < Q_AUDIO_TRACK_CHANGED");
2009 audio_finalise_track_change();
2010 break;
2011 #if (CONFIG_PLATFORM & PLATFORM_NATIVE)
2012 case SYS_USB_CONNECTED:
2013 LOGFQUEUE("audio < SYS_USB_CONNECTED");
2014 if (playing)
2015 audio_stop_playback();
2016 #ifdef PLAYBACK_VOICE
2017 voice_stop();
2018 #endif
2019 usb_acknowledge(SYS_USB_CONNECTED_ACK);
2020 usb_wait_for_disconnect(&audio_queue);
2022 /* Mark all entries null. */
2023 audio_clear_track_entries();
2025 /* release tracks to make sure all handles are closed */
2026 audio_release_tracks();
2027 break;
2028 #endif
2030 case SYS_TIMEOUT:
2031 LOGFQUEUE_SYS_TIMEOUT("audio < SYS_TIMEOUT");
2032 break;
2034 default:
2035 /* LOGFQUEUE("audio < default : %08lX", ev.id); */
2036 break;
2037 } /* end switch */
2038 } /* end while */
2041 /* Initialize the audio system - called from init() in main.c.
2042 * Last function because of all the references to internal symbols
2044 void audio_init(void)
2046 unsigned int audio_thread_id;
2048 /* Can never do this twice */
2049 if (audio_is_initialized)
2051 logf("audio: already initialized");
2052 return;
2055 logf("audio: initializing");
2057 /* Initialize queues before giving control elsewhere in case it likes
2058 to send messages. Thread creation will be delayed however so nothing
2059 starts running until ready if something yields such as talk_init. */
2060 queue_init(&audio_queue, true);
2061 queue_init(&codec_queue, false);
2062 queue_init(&pcmbuf_queue, false);
2064 pcm_init();
2066 codec_init_codec_api();
2068 thistrack_id3 = &mp3entry_buf[0];
2069 othertrack_id3 = &mp3entry_buf[1];
2071 /* cuesheet support */
2072 if (global_settings.cuesheet)
2073 curr_cue = (struct cuesheet*)buffer_alloc(sizeof(struct cuesheet));
2075 /* initialize the buffer */
2076 filebuf = audiobuf;
2078 /* audio_reset_buffer must to know the size of voice buffer so init
2079 talk first */
2080 talk_init();
2082 make_codec_thread();
2084 audio_thread_id = create_thread(audio_thread, audio_stack,
2085 sizeof(audio_stack), CREATE_THREAD_FROZEN,
2086 audio_thread_name IF_PRIO(, PRIORITY_USER_INTERFACE)
2087 IF_COP(, CPU));
2089 queue_enable_queue_send(&audio_queue, &audio_queue_sender_list,
2090 audio_thread_id);
2092 #ifdef PLAYBACK_VOICE
2093 voice_thread_init();
2094 #endif
2096 #ifdef HAVE_CROSSFADE
2097 /* Set crossfade setting for next buffer init which should be about... */
2098 pcmbuf_request_crossfade_enable(global_settings.crossfade);
2099 #endif
2101 /* initialize the buffering system */
2103 buffering_init();
2104 /* ...now! Set up the buffers */
2105 audio_reset_buffer();
2107 int i;
2108 for(i = 0; i < MAX_TRACK; i++)
2110 tracks[i].audio_hid = -1;
2111 tracks[i].id3_hid = -1;
2112 tracks[i].codec_hid = -1;
2113 tracks[i].cuesheet_hid = -1;
2115 #ifdef HAVE_ALBUMART
2116 FOREACH_ALBUMART(i)
2118 int j;
2119 for (j = 0; j < MAX_TRACK; j++)
2121 tracks[j].aa_hid[i] = -1;
2124 #endif
2126 add_event(BUFFER_EVENT_REBUFFER, false, buffering_handle_rebuffer_callback);
2127 add_event(BUFFER_EVENT_FINISHED, false, buffering_handle_finished_callback);
2129 /* Probably safe to say */
2130 audio_is_initialized = true;
2132 sound_settings_apply();
2133 #ifdef HAVE_DISK_STORAGE
2134 audio_set_buffer_margin(global_settings.buffer_margin);
2135 #endif
2137 /* it's safe to let the threads run now */
2138 #ifdef PLAYBACK_VOICE
2139 voice_thread_resume();
2140 #endif
2141 thread_thaw(codec_thread_id);
2142 thread_thaw(audio_thread_id);
2144 } /* audio_init */
2146 bool audio_is_thread_ready(void)
2148 return audio_thread_ready;
2151 size_t audio_get_filebuflen(void)
2153 return filebuflen;
2156 int get_audio_hid()
2158 return CUR_TI->audio_hid;
2161 int *get_codec_hid()
2163 return &tracks[track_ridx].codec_hid;