Hopefully all green now
[maemo-rb.git] / apps / playback.c
blob3a7faa3d8d3c7b207619b2b8bebe4b15e73a56bb
1 /***************************************************************************
2 * __________ __ ___.
3 * Open \______ \ ____ ____ | | _\_ |__ _______ ___
4 * Source | _// _ \_/ ___\| |/ /| __ \ / _ \ \/ /
5 * Jukebox | | ( <_> ) \___| < | \_\ ( <_> > < <
6 * Firmware |____|_ /\____/ \___ >__|_ \|___ /\____/__/\_ \
7 * \/ \/ \/ \/ \/
8 * $Id$
10 * Copyright (C) 2005-2007 Miika Pekkarinen
11 * Copyright (C) 2007-2008 Nicolas Pennequin
13 * This program is free software; you can redistribute it and/or
14 * modify it under the terms of the GNU General Public License
15 * as published by the Free Software Foundation; either version 2
16 * of the License, or (at your option) any later version.
18 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
19 * KIND, either express or implied.
21 ****************************************************************************/
23 /* TODO: Pause should be handled in here, rather than PCMBUF so that voice can
24 * play whilst audio is paused */
26 #include <string.h>
27 #include "playback.h"
28 #include "codec_thread.h"
29 #include "kernel.h"
30 #include "codecs.h"
31 #include "buffering.h"
32 #include "voice_thread.h"
33 #include "usb.h"
34 #include "ata.h"
35 #include "playlist.h"
36 #include "pcmbuf.h"
37 #include "buffer.h"
38 #include "cuesheet.h"
39 #ifdef HAVE_TAGCACHE
40 #include "tagcache.h"
41 #endif
42 #ifdef HAVE_LCD_BITMAP
43 #ifdef HAVE_ALBUMART
44 #include "albumart.h"
45 #endif
46 #endif
47 #include "sound.h"
48 #include "metadata.h"
49 #include "splash.h"
50 #include "talk.h"
51 #include "panic.h"
53 #ifdef HAVE_RECORDING
54 #include "pcm_record.h"
55 #endif
57 #define PLAYBACK_VOICE
59 /* amount of guess-space to allow for codecs that must hunt and peck
60 * for their correct seeek target, 32k seems a good size */
61 #define AUDIO_REBUFFER_GUESS_SIZE (1024*32)
63 /* Define LOGF_ENABLE to enable logf output in this file */
64 /*#define LOGF_ENABLE*/
65 #include "logf.h"
67 /* macros to enable logf for queues
68 logging on SYS_TIMEOUT can be disabled */
69 #ifdef SIMULATOR
70 /* Define this for logf output of all queuing except SYS_TIMEOUT */
71 #define PLAYBACK_LOGQUEUES
72 /* Define this to logf SYS_TIMEOUT messages */
73 /*#define PLAYBACK_LOGQUEUES_SYS_TIMEOUT*/
74 #endif
76 #ifdef PLAYBACK_LOGQUEUES
77 #define LOGFQUEUE logf
78 #else
79 #define LOGFQUEUE(...)
80 #endif
82 #ifdef PLAYBACK_LOGQUEUES_SYS_TIMEOUT
83 #define LOGFQUEUE_SYS_TIMEOUT logf
84 #else
85 #define LOGFQUEUE_SYS_TIMEOUT(...)
86 #endif
89 static enum filling_state {
90 STATE_IDLE, /* audio is stopped: nothing to do */
91 STATE_FILLING, /* adding tracks to the buffer */
92 STATE_FULL, /* can't add any more tracks */
93 STATE_END_OF_PLAYLIST, /* all remaining tracks have been added */
94 STATE_FINISHED, /* all remaining tracks are fully buffered */
95 } filling;
97 /* As defined in plugins/lib/xxx2wav.h */
98 #define GUARD_BUFSIZE (32*1024)
100 bool audio_is_initialized = false;
101 static bool audio_thread_ready SHAREDBSS_ATTR = false;
103 /* Variables are commented with the threads that use them: *
104 * A=audio, C=codec, V=voice. A suffix of - indicates that *
105 * the variable is read but not updated on that thread. */
106 /* TBD: Split out "audio" and "playback" (ie. calling) threads */
108 /* Main state control */
109 static volatile bool playing SHAREDBSS_ATTR = false;/* Is audio playing? (A) */
110 static volatile bool paused SHAREDBSS_ATTR = false; /* Is audio paused? (A/C-) */
111 extern volatile bool audio_codec_loaded; /* Codec loaded? (C/A-) */
113 /* Ring buffer where compressed audio and codecs are loaded */
114 static unsigned char *filebuf = NULL; /* Start of buffer (A/C-) */
115 static unsigned char *malloc_buf = NULL; /* Start of malloc buffer (A/C-) */
116 static size_t filebuflen = 0; /* Size of buffer (A/C-) */
117 /* FIXME: make buf_ridx (C/A-) */
119 /* Possible arrangements of the buffer */
120 enum audio_buffer_state
122 AUDIOBUF_STATE_TRASHED = -1, /* trashed; must be reset */
123 AUDIOBUF_STATE_INITIALIZED = 0, /* voice+audio OR audio-only */
124 AUDIOBUF_STATE_VOICED_ONLY = 1, /* voice-only */
126 static int buffer_state = AUDIOBUF_STATE_TRASHED; /* Buffer state */
128 /* These are used to store the current and next (or prev if the current is the last)
129 * mp3entry's in a round-robin system. This guarentees that the pointer returned
130 * by audio_current/next_track will be valid for the full duration of the
131 * currently playing track */
132 static struct mp3entry mp3entry_buf[2];
133 struct mp3entry *thistrack_id3, /* the currently playing track */
134 *othertrack_id3; /* prev track during track-change-transition, or end of playlist,
135 * next track otherwise */
136 static struct mp3entry unbuffered_id3; /* the id3 for the first unbuffered track */
138 /* for cuesheet support */
139 static struct cuesheet *curr_cue = NULL;
142 #define MAX_MULTIPLE_AA SKINNABLE_SCREENS_COUNT
144 #ifdef HAVE_ALBUMART
146 static struct albumart_slot {
147 struct dim dim; /* holds width, height of the albumart */
148 int used; /* counter, increments if something uses it */
149 } albumart_slots[MAX_MULTIPLE_AA];
151 #define FOREACH_ALBUMART(i) for(i = 0;i < MAX_MULTIPLE_AA; i++)
152 #endif
155 #define MAX_TRACK 128
156 #define MAX_TRACK_MASK (MAX_TRACK-1)
158 /* Track info structure about songs in the file buffer (A/C-) */
159 static struct track_info {
160 int audio_hid; /* The ID for the track's buffer handle */
161 int id3_hid; /* The ID for the track's metadata handle */
162 int codec_hid; /* The ID for the track's codec handle */
163 #ifdef HAVE_ALBUMART
164 int aa_hid[MAX_MULTIPLE_AA];/* The ID for the track's album art handle */
165 #endif
166 int cuesheet_hid; /* The ID for the track's parsed cueesheet handle */
168 size_t filesize; /* File total length */
170 bool taginfo_ready; /* Is metadata read */
172 } tracks[MAX_TRACK];
174 static volatile int track_ridx = 0; /* Track being decoded (A/C-) */
175 static int track_widx = 0; /* Track being buffered (A) */
176 #define CUR_TI (&tracks[track_ridx]) /* Playing track info pointer (A/C-) */
178 static struct track_info *prev_ti = NULL; /* Pointer to the previously played
179 track */
181 /* Information used only for filling the buffer */
182 /* Playlist steps from playing track to next track to be buffered (A) */
183 static int last_peek_offset = 0;
185 /* Scrobbler support */
186 static unsigned long prev_track_elapsed = 0; /* Previous track elapsed time (C/A-)*/
188 /* Track change controls */
189 bool automatic_skip = false; /* Who initiated in-progress skip? (C/A-) */
190 extern bool track_transition; /* Are we in a track transition? */
191 static bool dir_skip = false; /* Is a directory skip pending? (A) */
192 static bool new_playlist = false; /* Are we starting a new playlist? (A) */
193 static int wps_offset = 0; /* Pending track change offset, to keep WPS responsive (A) */
194 static bool skipped_during_pause = false; /* Do we need to clear the PCM buffer when playback resumes (A) */
196 static bool start_play_g = false; /* Used by audio_load_track to notify
197 audio_finish_load_track about start_play */
199 /* True when a track load is in progress, i.e. audio_load_track() has returned
200 * but audio_finish_load_track() hasn't been called yet. Used to avoid allowing
201 * audio_load_track() to get called twice in a row, which would cause problems.
203 static bool track_load_started = false;
205 #ifdef HAVE_DISK_STORAGE
206 static size_t buffer_margin = 5; /* Buffer margin aka anti-skip buffer (A/C-) */
207 #endif
209 /* Event queues */
210 struct event_queue audio_queue SHAREDBSS_ATTR;
211 struct event_queue codec_queue SHAREDBSS_ATTR;
212 static struct event_queue pcmbuf_queue SHAREDBSS_ATTR;
214 extern struct codec_api ci;
215 extern unsigned int codec_thread_id;
217 /* Multiple threads */
218 /* Set the watermark to trigger buffer fill (A/C) */
219 static void set_filebuf_watermark(void);
221 /* Audio thread */
222 static struct queue_sender_list audio_queue_sender_list SHAREDBSS_ATTR;
223 static long audio_stack[(DEFAULT_STACK_SIZE + 0x1000)/sizeof(long)];
224 static const char audio_thread_name[] = "audio";
226 static void audio_thread(void);
227 static void audio_initiate_track_change(long direction);
228 static bool audio_have_tracks(void);
229 static void audio_reset_buffer(void);
230 static void audio_stop_playback(void);
232 /**************************************/
235 /** Pcmbuf callbacks */
237 /* Between the codec and PCM track change, we need to keep updating the
238 * "elapsed" value of the previous (to the codec, but current to the
239 * user/PCM/WPS) track, so that the progressbar reaches the end.
240 * During that transition, the WPS will display othertrack_id3. */
241 void audio_pcmbuf_position_callback(unsigned int time)
243 time += othertrack_id3->elapsed;
245 if (time >= othertrack_id3->length)
247 /* we just played the end of the track, so stop this callback */
248 track_transition = false;
249 othertrack_id3->elapsed = othertrack_id3->length;
251 else
252 othertrack_id3->elapsed = time;
255 /* Post message from pcmbuf that the end of the previous track
256 * has just been played. */
257 void audio_post_track_change(bool pcmbuf)
259 if (pcmbuf)
261 LOGFQUEUE("pcmbuf > pcmbuf Q_AUDIO_TRACK_CHANGED");
262 queue_post(&pcmbuf_queue, Q_AUDIO_TRACK_CHANGED, 0);
264 else
266 LOGFQUEUE("pcmbuf > audio Q_AUDIO_TRACK_CHANGED");
267 queue_post(&audio_queue, Q_AUDIO_TRACK_CHANGED, 0);
271 /* Scan the pcmbuf queue and return true if a message pulled */
272 static bool pcmbuf_queue_scan(struct queue_event *ev)
274 if (!queue_empty(&pcmbuf_queue))
276 /* Transfer message to audio queue */
277 pcm_play_lock();
278 /* Pull message - never, ever any blocking call! */
279 queue_wait_w_tmo(&pcmbuf_queue, ev, 0);
280 pcm_play_unlock();
281 return true;
284 return false;
288 /** Helper functions */
290 static struct mp3entry *bufgetid3(int handle_id)
292 if (handle_id < 0)
293 return NULL;
295 struct mp3entry *id3;
296 ssize_t ret = bufgetdata(handle_id, 0, (void *)&id3);
298 if (ret < 0 || ret != sizeof(struct mp3entry))
299 return NULL;
301 return id3;
304 static bool clear_track_info(struct track_info *track)
306 /* bufclose returns true if the handle is not found, or if it is closed
307 * successfully, so these checks are safe on non-existant handles */
308 if (!track)
309 return false;
311 if (track->codec_hid >= 0) {
312 if (bufclose(track->codec_hid))
313 track->codec_hid = -1;
314 else
315 return false;
318 if (track->id3_hid >= 0) {
319 if (bufclose(track->id3_hid))
320 track->id3_hid = -1;
321 else
322 return false;
325 if (track->audio_hid >= 0) {
326 if (bufclose(track->audio_hid))
327 track->audio_hid = -1;
328 else
329 return false;
332 #ifdef HAVE_ALBUMART
334 int i;
335 FOREACH_ALBUMART(i)
337 if (track->aa_hid[i] >= 0) {
338 if (bufclose(track->aa_hid[i]))
339 track->aa_hid[i] = -1;
340 else
341 return false;
345 #endif
347 if (track->cuesheet_hid >= 0) {
348 if (bufclose(track->cuesheet_hid))
349 track->cuesheet_hid = -1;
350 else
351 return false;
354 track->filesize = 0;
355 track->taginfo_ready = false;
357 return true;
360 /* --- External interfaces --- */
362 /* This sends a stop message and the audio thread will dump all it's
363 subsequenct messages */
364 void audio_hard_stop(void)
366 /* Stop playback */
367 LOGFQUEUE("audio >| audio Q_AUDIO_STOP: 1");
368 queue_send(&audio_queue, Q_AUDIO_STOP, 1);
369 #ifdef PLAYBACK_VOICE
370 voice_stop();
371 #endif
374 bool audio_restore_playback(int type)
376 switch (type)
378 case AUDIO_WANT_PLAYBACK:
379 if (buffer_state != AUDIOBUF_STATE_INITIALIZED)
380 audio_reset_buffer();
381 return true;
382 case AUDIO_WANT_VOICE:
383 if (buffer_state == AUDIOBUF_STATE_TRASHED)
384 audio_reset_buffer();
385 return true;
386 default:
387 return false;
391 unsigned char *audio_get_buffer(bool talk_buf, size_t *buffer_size)
393 unsigned char *buf, *end;
395 if (audio_is_initialized)
397 audio_hard_stop();
399 /* else buffer_state will be AUDIOBUF_STATE_TRASHED at this point */
401 /* Reset the buffering thread so that it doesn't try to use the data */
402 buffering_reset(filebuf, filebuflen);
404 if (buffer_size == NULL)
406 /* Special case for talk_init to use since it already knows it's
407 trashed */
408 buffer_state = AUDIOBUF_STATE_TRASHED;
409 return NULL;
412 if (talk_buf || buffer_state == AUDIOBUF_STATE_TRASHED
413 || !talk_voice_required())
415 logf("get buffer: talk, audio");
416 /* Ok to use everything from audiobuf to audiobufend - voice is loaded,
417 the talk buffer is not needed because voice isn't being used, or
418 could be AUDIOBUF_STATE_TRASHED already. If state is
419 AUDIOBUF_STATE_VOICED_ONLY, no problem as long as memory isn't written
420 without the caller knowing what's going on. Changing certain settings
421 may move it to a worse condition but the memory in use by something
422 else will remain undisturbed.
424 if (buffer_state != AUDIOBUF_STATE_TRASHED)
426 talk_buffer_steal();
427 buffer_state = AUDIOBUF_STATE_TRASHED;
430 buf = audiobuf;
431 end = audiobufend;
433 else
435 /* Safe to just return this if already AUDIOBUF_STATE_VOICED_ONLY or
436 still AUDIOBUF_STATE_INITIALIZED */
437 /* Skip talk buffer and move pcm buffer to end to maximize available
438 contiguous memory - no audio running means voice will not need the
439 swap space */
440 logf("get buffer: audio");
441 buf = audiobuf + talk_get_bufsize();
442 end = audiobufend - pcmbuf_init(audiobufend);
443 buffer_state = AUDIOBUF_STATE_VOICED_ONLY;
446 *buffer_size = end - buf;
448 return buf;
451 bool audio_buffer_state_trashed(void)
453 return buffer_state == AUDIOBUF_STATE_TRASHED;
456 #ifdef HAVE_RECORDING
457 unsigned char *audio_get_recording_buffer(size_t *buffer_size)
459 /* Stop audio, voice and obtain all available buffer space */
460 audio_hard_stop();
461 talk_buffer_steal();
463 unsigned char *end = audiobufend;
464 buffer_state = AUDIOBUF_STATE_TRASHED;
465 *buffer_size = end - audiobuf;
467 return (unsigned char *)audiobuf;
470 bool audio_load_encoder(int afmt)
472 #if (CONFIG_PLATFORM & PLATFORM_NATIVE)
473 const char *enc_fn = get_codec_filename(afmt | CODEC_TYPE_ENCODER);
474 if (!enc_fn)
475 return false;
477 audio_remove_encoder();
478 ci.enc_codec_loaded = 0; /* clear any previous error condition */
480 LOGFQUEUE("codec > Q_ENCODER_LOAD_DISK");
481 queue_post(&codec_queue, Q_ENCODER_LOAD_DISK, (intptr_t)enc_fn);
483 while (ci.enc_codec_loaded == 0)
484 yield();
486 logf("codec loaded: %d", ci.enc_codec_loaded);
488 return ci.enc_codec_loaded > 0;
489 #else
490 (void)afmt;
491 return true;
492 #endif
493 } /* audio_load_encoder */
495 void audio_remove_encoder(void)
497 #if (CONFIG_PLATFORM & PLATFORM_NATIVE)
498 /* force encoder codec unload (if currently loaded) */
499 if (ci.enc_codec_loaded <= 0)
500 return;
502 ci.stop_encoder = true;
503 while (ci.enc_codec_loaded > 0)
504 yield();
505 #endif
506 } /* audio_remove_encoder */
508 #endif /* HAVE_RECORDING */
511 struct mp3entry* audio_current_track(void)
513 const char *filename;
514 struct playlist_track_info trackinfo;
515 int cur_idx;
516 int offset = ci.new_track + wps_offset;
517 struct mp3entry *write_id3;
519 cur_idx = (track_ridx + offset) & MAX_TRACK_MASK;
521 if (cur_idx == track_ridx && *thistrack_id3->path)
523 /* The usual case */
524 if (tracks[cur_idx].cuesheet_hid >= 0 && !thistrack_id3->cuesheet)
526 bufread(tracks[cur_idx].cuesheet_hid, sizeof(struct cuesheet), curr_cue);
527 thistrack_id3->cuesheet = curr_cue;
529 return thistrack_id3;
531 else if (automatic_skip && offset == -1 && *othertrack_id3->path)
533 /* We're in a track transition. The codec has moved on to the next track,
534 but the audio being played is still the same (now previous) track.
535 othertrack_id3.elapsed is being updated in an ISR by
536 codec_pcmbuf_position_callback */
537 if (tracks[cur_idx].cuesheet_hid >= 0 && !thistrack_id3->cuesheet)
539 bufread(tracks[cur_idx].cuesheet_hid, sizeof(struct cuesheet), curr_cue);
540 othertrack_id3->cuesheet = curr_cue;
542 return othertrack_id3;
545 if (offset != 0)
547 /* Codec may be using thistrack_id3, so it must not be overwritten.
548 If this is a manual skip, othertrack_id3 will become
549 thistrack_id3 in audio_check_new_track().
550 FIXME: If this is an automatic skip, it probably means multiple
551 short tracks fit in the PCM buffer. Overwriting othertrack_id3
552 can lead to an incorrect value later.
553 Note that othertrack_id3 may also be used for next track.
555 write_id3 = othertrack_id3;
557 else
559 write_id3 = thistrack_id3;
562 if (tracks[cur_idx].id3_hid >= 0)
564 /* The current track's info has been buffered but not read yet, so get it */
565 if (bufread(tracks[cur_idx].id3_hid, sizeof(struct mp3entry), write_id3)
566 == sizeof(struct mp3entry))
567 return write_id3;
570 /* We didn't find the ID3 metadata, so we fill temp_id3 with the little info
571 we have and return that. */
573 memset(write_id3, 0, sizeof(struct mp3entry));
575 playlist_get_track_info(NULL, playlist_next(0)+wps_offset, &trackinfo);
576 filename = trackinfo.filename;
577 if (!filename)
578 filename = "No file!";
580 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
581 if (tagcache_fill_tags(write_id3, filename))
582 return write_id3;
583 #endif
585 strlcpy(write_id3->path, filename, sizeof(write_id3->path));
586 write_id3->title = strrchr(write_id3->path, '/');
587 if (!write_id3->title)
588 write_id3->title = &write_id3->path[0];
589 else
590 write_id3->title++;
592 return write_id3;
595 struct mp3entry* audio_next_track(void)
597 int next_idx;
598 int offset = ci.new_track + wps_offset;
600 if (!audio_have_tracks())
601 return NULL;
603 if (wps_offset == -1 && *thistrack_id3->path)
605 /* We're in a track transition. The next track for the WPS is the one
606 currently being decoded. */
607 return thistrack_id3;
610 next_idx = (track_ridx + offset + 1) & MAX_TRACK_MASK;
612 if (tracks[next_idx].id3_hid >= 0)
614 if (bufread(tracks[next_idx].id3_hid, sizeof(struct mp3entry), othertrack_id3)
615 == sizeof(struct mp3entry))
616 return othertrack_id3;
617 else
618 return NULL;
621 if (next_idx == track_widx)
623 /* The next track hasn't been buffered yet, so we return the static
624 version of its metadata. */
625 return &unbuffered_id3;
628 return NULL;
631 /* gets a pointer to the id3 data, Not thread safe!, DON'T yield()/sleep() */
632 bool audio_peek_track(struct mp3entry** id3, int offset)
634 int next_idx;
635 int new_offset = ci.new_track + wps_offset + offset;
637 if (!audio_have_tracks())
638 return false;
639 next_idx = (track_ridx + new_offset) & MAX_TRACK_MASK;
641 if (tracks[next_idx].id3_hid >= 0)
643 return bufgetdata(tracks[next_idx].id3_hid, 0, (void**)id3)
644 == sizeof(struct mp3entry);
646 return false;
649 #ifdef HAVE_ALBUMART
651 int playback_current_aa_hid(int slot)
653 if (slot < 0)
654 return -1;
655 int cur_idx;
656 int offset = ci.new_track + wps_offset;
658 cur_idx = track_ridx + offset;
659 cur_idx &= MAX_TRACK_MASK;
660 return tracks[cur_idx].aa_hid[slot];
663 int playback_claim_aa_slot(struct dim *dim)
665 int i;
667 /* first try to find a slot already having the size to reuse it
668 * since we don't want albumart of the same size buffered multiple times */
669 FOREACH_ALBUMART(i)
671 struct albumart_slot *slot = &albumart_slots[i];
672 if (slot->dim.width == dim->width
673 && slot->dim.height == dim->height)
675 slot->used++;
676 return i;
679 /* size is new, find a free slot */
680 FOREACH_ALBUMART(i)
682 if (!albumart_slots[i].used)
684 albumart_slots[i].used++;
685 albumart_slots[i].dim = *dim;
686 return i;
689 /* sorry, no free slot */
690 return -1;
693 void playback_release_aa_slot(int slot)
695 /* invalidate the albumart_slot */
696 struct albumart_slot *aa_slot = &albumart_slots[slot];
698 if (aa_slot->used > 0)
699 aa_slot->used--;
702 #endif
703 void audio_play(long offset)
705 logf("audio_play");
707 #ifdef PLAYBACK_VOICE
708 /* Truncate any existing voice output so we don't have spelling
709 * etc. over the first part of the played track */
710 talk_force_shutup();
711 #endif
713 /* Start playback */
714 LOGFQUEUE("audio >| audio Q_AUDIO_PLAY: %ld", offset);
715 /* Don't return until playback has actually started */
716 queue_send(&audio_queue, Q_AUDIO_PLAY, offset);
719 void audio_stop(void)
721 /* Stop playback */
722 LOGFQUEUE("audio >| audio Q_AUDIO_STOP");
723 /* Don't return until playback has actually stopped */
724 queue_send(&audio_queue, Q_AUDIO_STOP, 0);
727 void audio_pause(void)
729 LOGFQUEUE("audio >| audio Q_AUDIO_PAUSE");
730 /* Don't return until playback has actually paused */
731 queue_send(&audio_queue, Q_AUDIO_PAUSE, true);
734 void audio_resume(void)
736 LOGFQUEUE("audio >| audio Q_AUDIO_PAUSE resume");
737 /* Don't return until playback has actually resumed */
738 queue_send(&audio_queue, Q_AUDIO_PAUSE, false);
741 void audio_skip(int direction)
743 if (playlist_check(ci.new_track + wps_offset + direction))
745 if (global_settings.beep)
746 pcmbuf_beep(2000, 100, 2500*global_settings.beep);
748 LOGFQUEUE("audio > audio Q_AUDIO_SKIP %d", direction);
749 queue_post(&audio_queue, Q_AUDIO_SKIP, direction);
750 /* Update wps while our message travels inside deep playback queues. */
751 wps_offset += direction;
753 else
755 /* No more tracks. */
756 if (global_settings.beep)
757 pcmbuf_beep(1000, 100, 1500*global_settings.beep);
761 void audio_next(void)
763 audio_skip(1);
766 void audio_prev(void)
768 audio_skip(-1);
771 void audio_next_dir(void)
773 LOGFQUEUE("audio > audio Q_AUDIO_DIR_SKIP 1");
774 queue_post(&audio_queue, Q_AUDIO_DIR_SKIP, 1);
777 void audio_prev_dir(void)
779 LOGFQUEUE("audio > audio Q_AUDIO_DIR_SKIP -1");
780 queue_post(&audio_queue, Q_AUDIO_DIR_SKIP, -1);
783 void audio_pre_ff_rewind(void)
785 LOGFQUEUE("audio > audio Q_AUDIO_PRE_FF_REWIND");
786 queue_post(&audio_queue, Q_AUDIO_PRE_FF_REWIND, 0);
789 void audio_ff_rewind(long newpos)
791 LOGFQUEUE("audio > audio Q_AUDIO_FF_REWIND");
792 queue_post(&audio_queue, Q_AUDIO_FF_REWIND, newpos);
795 void audio_flush_and_reload_tracks(void)
797 LOGFQUEUE("audio > audio Q_AUDIO_FLUSH");
798 queue_post(&audio_queue, Q_AUDIO_FLUSH, 0);
801 void audio_error_clear(void)
803 #ifdef AUDIO_HAVE_RECORDING
804 pcm_rec_error_clear();
805 #endif
808 int audio_status(void)
810 int ret = 0;
812 if (playing)
813 ret |= AUDIO_STATUS_PLAY;
815 if (paused)
816 ret |= AUDIO_STATUS_PAUSE;
818 #ifdef HAVE_RECORDING
819 /* Do this here for constitency with mpeg.c version */
820 /* FIXME: pcm_rec_status() is deprecated */
821 ret |= pcm_rec_status();
822 #endif
824 return ret;
827 int audio_get_file_pos(void)
829 return 0;
832 #ifdef HAVE_DISK_STORAGE
833 void audio_set_buffer_margin(int setting)
835 static const unsigned short lookup[] = {5, 15, 30, 60, 120, 180, 300, 600};
836 buffer_margin = lookup[setting];
837 logf("buffer margin: %ld", (long)buffer_margin);
838 set_filebuf_watermark();
840 #endif
842 #ifdef HAVE_CROSSFADE
843 /* Take necessary steps to enable or disable the crossfade setting */
844 void audio_set_crossfade(int enable)
846 size_t offset;
847 bool was_playing;
848 size_t size;
850 /* Tell it the next setting to use */
851 pcmbuf_request_crossfade_enable(enable);
853 /* Return if size hasn't changed or this is too early to determine
854 which in the second case there's no way we could be playing
855 anything at all */
856 if (pcmbuf_is_same_size()) return;
858 offset = 0;
859 was_playing = playing;
861 /* Playback has to be stopped before changing the buffer size */
862 if (was_playing)
864 /* Store the track resume position */
865 offset = thistrack_id3->offset;
868 /* Blast it - audio buffer will have to be setup again next time
869 something plays */
870 audio_get_buffer(true, &size);
872 /* Restart playback if audio was running previously */
873 if (was_playing)
874 audio_play(offset);
876 #endif
878 /* --- Routines called from multiple threads --- */
880 static void set_filebuf_watermark(void)
882 if (!filebuf)
883 return; /* Audio buffers not yet set up */
885 #ifdef HAVE_DISK_STORAGE
886 int seconds;
887 int spinup = ata_spinup_time();
888 if (spinup)
889 seconds = (spinup / HZ) + 1;
890 else
891 seconds = 5;
893 seconds += buffer_margin;
894 #else
895 /* flash storage */
896 int seconds = 1;
897 #endif
899 /* bitrate of last track in buffer dictates watermark */
900 struct mp3entry* id3 = NULL;
901 if (tracks[track_widx].taginfo_ready)
902 id3 = bufgetid3(tracks[track_widx].id3_hid);
903 else
904 id3 = bufgetid3(tracks[track_widx-1].id3_hid);
905 if (!id3) {
906 logf("fwmark: No id3 for last track (r%d/w%d), aborting!", track_ridx, track_widx);
907 return;
909 size_t bytes = id3->bitrate * (1000/8) * seconds;
910 buf_set_watermark(bytes);
911 logf("fwmark: %d", bytes);
914 /* --- Buffering callbacks --- */
916 static void buffering_low_buffer_callback(void *data)
918 (void)data;
919 logf("low buffer callback");
921 if (filling == STATE_FULL || filling == STATE_END_OF_PLAYLIST) {
922 /* force a refill */
923 LOGFQUEUE("buffering > audio Q_AUDIO_FILL_BUFFER");
924 queue_post(&audio_queue, Q_AUDIO_FILL_BUFFER, 0);
928 static void buffering_handle_rebuffer_callback(void *data)
930 (void)data;
931 LOGFQUEUE("audio >| audio Q_AUDIO_FLUSH");
932 queue_post(&audio_queue, Q_AUDIO_FLUSH, 0);
935 static void buffering_handle_finished_callback(void *data)
937 logf("handle %d finished buffering", *(int*)data);
938 int hid = (*(int*)data);
940 if (hid == tracks[track_widx].id3_hid)
942 int offset = ci.new_track + wps_offset;
943 int next_idx = (track_ridx + offset + 1) & MAX_TRACK_MASK;
944 /* The metadata handle for the last loaded track has been buffered.
945 We can ask the audio thread to load the rest of the track's data. */
946 LOGFQUEUE("audio >| audio Q_AUDIO_FINISH_LOAD");
947 queue_post(&audio_queue, Q_AUDIO_FINISH_LOAD, 0);
948 if (tracks[next_idx].id3_hid == hid)
949 send_event(PLAYBACK_EVENT_NEXTTRACKID3_AVAILABLE, NULL);
951 else
953 /* This is most likely an audio handle, so we strip the useless
954 trailing tags that are left. */
955 strip_tags(hid);
957 if (hid == tracks[track_widx-1].audio_hid
958 && filling == STATE_END_OF_PLAYLIST)
960 /* This was the last track in the playlist.
961 We now have all the data we need. */
962 logf("last track finished buffering");
963 filling = STATE_FINISHED;
969 /* --- Audio thread --- */
971 static bool audio_have_tracks(void)
973 return (audio_track_count() != 0);
976 static int audio_free_track_count(void)
978 /* Used tracks + free tracks adds up to MAX_TRACK - 1 */
979 return MAX_TRACK - 1 - audio_track_count();
982 int audio_track_count(void)
984 /* Calculate difference from track_ridx to track_widx
985 * taking into account a possible wrap-around. */
986 return (MAX_TRACK + track_widx - track_ridx) & MAX_TRACK_MASK;
989 long audio_filebufused(void)
991 return (long) buf_used();
994 /* Update track info after successful a codec track change */
995 static void audio_update_trackinfo(void)
997 bool resume = false;
999 /* Load the curent track's metadata into curtrack_id3 */
1000 if (CUR_TI->id3_hid >= 0)
1001 copy_mp3entry(thistrack_id3, bufgetid3(CUR_TI->id3_hid));
1003 /* Reset current position */
1004 thistrack_id3->elapsed = 0;
1006 #ifdef HAVE_TAGCACHE
1007 /* Ignoring resume position for automatic track change if so configured */
1008 resume = global_settings.autoresume_enable &&
1009 (!automatic_skip /* Resume all manually selected tracks */
1010 || global_settings.autoresume_automatic == AUTORESUME_NEXTTRACK_ALWAYS
1011 || (global_settings.autoresume_automatic != AUTORESUME_NEXTTRACK_NEVER
1012 /* Not never resume? */
1013 && autoresumable(thistrack_id3))); /* Pass Resume filter? */
1014 #endif
1016 if (!resume)
1018 thistrack_id3->offset = 0;
1021 logf("audio_update_trackinfo: Set offset for %s to %lX\n",
1022 thistrack_id3->title, thistrack_id3->offset);
1024 /* Update the codec API */
1025 ci.filesize = CUR_TI->filesize;
1026 ci.id3 = thistrack_id3;
1027 ci.curpos = 0;
1028 ci.taginfo_ready = &CUR_TI->taginfo_ready;
1031 /* Clear tracks between write and read, non inclusive */
1032 static void audio_clear_track_entries(void)
1034 int cur_idx = track_widx;
1036 logf("Clearing tracks: r%d/w%d", track_ridx, track_widx);
1038 /* Loop over all tracks from write-to-read */
1039 while (1)
1041 cur_idx = (cur_idx + 1) & MAX_TRACK_MASK;
1043 if (cur_idx == track_ridx)
1044 break;
1046 clear_track_info(&tracks[cur_idx]);
1050 /* Clear all tracks */
1051 static bool audio_release_tracks(void)
1053 int i, cur_idx;
1055 logf("releasing all tracks");
1057 for(i = 0; i < MAX_TRACK; i++)
1059 cur_idx = (track_ridx + i) & MAX_TRACK_MASK;
1060 if (!clear_track_info(&tracks[cur_idx]))
1061 return false;
1064 return true;
1067 static bool audio_loadcodec(bool start_play)
1069 int prev_track, hid;
1070 char codec_path[MAX_PATH]; /* Full path to codec */
1071 const struct mp3entry *id3, *prev_id3;
1073 if (tracks[track_widx].id3_hid < 0) {
1074 return false;
1077 id3 = bufgetid3(tracks[track_widx].id3_hid);
1078 if (!id3)
1079 return false;
1081 const char *codec_fn = get_codec_filename(id3->codectype);
1082 if (codec_fn == NULL)
1083 return false;
1085 tracks[track_widx].codec_hid = -1;
1087 if (start_play)
1089 /* Load the codec directly from disk and save some memory. */
1090 track_ridx = track_widx;
1091 ci.filesize = CUR_TI->filesize;
1092 ci.id3 = thistrack_id3;
1093 ci.taginfo_ready = &CUR_TI->taginfo_ready;
1094 ci.curpos = 0;
1095 LOGFQUEUE("codec > codec Q_CODEC_LOAD_DISK");
1096 queue_post(&codec_queue, Q_CODEC_LOAD_DISK, (intptr_t)codec_fn);
1097 return true;
1099 else
1101 /* If we already have another track than this one buffered */
1102 if (track_widx != track_ridx)
1104 prev_track = (track_widx - 1) & MAX_TRACK_MASK;
1106 id3 = bufgetid3(tracks[track_widx].id3_hid);
1107 prev_id3 = bufgetid3(tracks[prev_track].id3_hid);
1109 /* If the previous codec is the same as this one, there is no need
1110 * to put another copy of it on the file buffer */
1111 if (id3 && prev_id3 &&
1112 get_codec_base_type(id3->codectype) ==
1113 get_codec_base_type(prev_id3->codectype)
1114 && audio_codec_loaded)
1116 logf("Reusing prev. codec");
1117 return true;
1122 codec_get_full_path(codec_path, codec_fn);
1124 hid = tracks[track_widx].codec_hid = bufopen(codec_path, 0, TYPE_CODEC, NULL);
1126 /* not an error if codec load it supported, will load it from disk
1127 * application builds don't support it
1129 if (hid < 0 && hid != ERR_UNSUPPORTED_TYPE)
1130 return false;
1132 if (hid > 0)
1133 logf("Loaded codec");
1134 else
1135 logf("Buffering codec unsupported, load later from disk");
1137 return true;
1140 /* Load metadata for the next track (with bufopen). The rest of the track
1141 loading will be handled by audio_finish_load_track once the metadata has been
1142 actually loaded by the buffering thread. */
1143 static bool audio_load_track(size_t offset, bool start_play)
1145 char name_buf[MAX_PATH + 1];
1146 const char *trackname;
1147 int fd = -1;
1149 if (track_load_started) {
1150 /* There is already a track load in progress, so track_widx hasn't been
1151 incremented yet. Loading another track would overwrite the one that
1152 hasn't finished loading. */
1153 logf("audio_load_track(): a track load is already in progress");
1154 return false;
1157 start_play_g = start_play; /* will be read by audio_finish_load_track */
1159 /* Stop buffer filling if there is no free track entries.
1160 Don't fill up the last track entry (we wan't to store next track
1161 metadata there). */
1162 if (!audio_free_track_count())
1164 logf("No free tracks");
1165 return false;
1168 last_peek_offset++;
1169 tracks[track_widx].taginfo_ready = false;
1171 logf("Buffering track: r%d/w%d", track_ridx, track_widx);
1172 /* Get track name from current playlist read position. */
1173 while ((trackname = playlist_peek(last_peek_offset, name_buf,
1174 sizeof(name_buf))) != NULL)
1176 /* Handle broken playlists. */
1177 fd = open(trackname, O_RDONLY);
1178 if (fd < 0)
1180 logf("Open failed");
1181 /* Skip invalid entry from playlist. */
1182 playlist_skip_entry(NULL, last_peek_offset);
1184 else
1185 break;
1188 if (!trackname)
1190 logf("End-of-playlist");
1191 memset(&unbuffered_id3, 0, sizeof(struct mp3entry));
1192 filling = STATE_END_OF_PLAYLIST;
1194 if (thistrack_id3->length == 0 && thistrack_id3->filesize == 0)
1196 /* Stop playback if no valid track was found. */
1197 audio_stop_playback();
1200 return false;
1203 tracks[track_widx].filesize = filesize(fd);
1205 if (offset > tracks[track_widx].filesize)
1206 offset = 0;
1208 /* Set default values */
1209 if (start_play)
1211 buf_set_watermark(filebuflen/2);
1212 dsp_configure(ci.dsp, DSP_RESET, 0);
1213 playlist_update_resume_info(audio_current_track());
1216 /* Get track metadata if we don't already have it. */
1217 if (tracks[track_widx].id3_hid < 0)
1219 tracks[track_widx].id3_hid = bufopen(trackname, 0, TYPE_ID3, NULL);
1221 if (tracks[track_widx].id3_hid < 0)
1223 /* Buffer is full. */
1224 get_metadata(&unbuffered_id3, fd, trackname);
1225 last_peek_offset--;
1226 close(fd);
1227 logf("buffer is full for now (get metadata)");
1228 filling = STATE_FULL;
1229 return false;
1232 if (track_widx == track_ridx)
1234 /* TODO: Superfluos buffering call? */
1235 buf_request_buffer_handle(tracks[track_widx].id3_hid);
1236 struct mp3entry *id3 = bufgetid3(tracks[track_widx].id3_hid);
1237 if (id3)
1239 copy_mp3entry(thistrack_id3, id3);
1240 thistrack_id3->offset = offset;
1241 logf("audio_load_track: set offset for %s to %lX\n",
1242 thistrack_id3->title,
1243 offset);
1245 else
1246 memset(thistrack_id3, 0, sizeof(struct mp3entry));
1249 if (start_play)
1251 playlist_update_resume_info(audio_current_track());
1255 close(fd);
1256 track_load_started = true; /* Remember that we've started loading a track */
1257 return true;
1260 /* Second part of the track loading: We now have the metadata available, so we
1261 can load the codec, the album art and finally the audio data.
1262 This is called on the audio thread after the buffering thread calls the
1263 buffering_handle_finished_callback callback. */
1264 static void audio_finish_load_track(void)
1266 size_t file_offset = 0;
1267 size_t offset = 0;
1268 bool start_play = start_play_g;
1270 track_load_started = false;
1272 if (tracks[track_widx].id3_hid < 0) {
1273 logf("No metadata");
1274 return;
1277 struct mp3entry *track_id3;
1279 if (track_widx == track_ridx)
1280 track_id3 = thistrack_id3;
1281 else
1282 track_id3 = bufgetid3(tracks[track_widx].id3_hid);
1284 if (track_id3->length == 0 && track_id3->filesize == 0)
1286 logf("audio_finish_load_track: invalid metadata");
1288 /* Invalid metadata */
1289 bufclose(tracks[track_widx].id3_hid);
1290 tracks[track_widx].id3_hid = -1;
1292 /* Skip invalid entry from playlist. */
1293 playlist_skip_entry(NULL, last_peek_offset--);
1295 /* load next track */
1296 LOGFQUEUE("audio > audio Q_AUDIO_FILL_BUFFER %d", (int)start_play);
1297 queue_post(&audio_queue, Q_AUDIO_FILL_BUFFER, start_play);
1299 return;
1301 /* Try to load a cuesheet for the track */
1302 if (curr_cue)
1304 char cuepath[MAX_PATH];
1305 if (look_for_cuesheet_file(track_id3->path, cuepath))
1307 void *temp;
1308 tracks[track_widx].cuesheet_hid =
1309 bufalloc(NULL, sizeof(struct cuesheet), TYPE_CUESHEET);
1310 if (tracks[track_widx].cuesheet_hid >= 0)
1312 bufgetdata(tracks[track_widx].cuesheet_hid,
1313 sizeof(struct cuesheet), &temp);
1314 struct cuesheet *cuesheet = (struct cuesheet*)temp;
1315 if (!parse_cuesheet(cuepath, cuesheet))
1317 bufclose(tracks[track_widx].cuesheet_hid);
1318 track_id3->cuesheet = NULL;
1323 #ifdef HAVE_ALBUMART
1325 int i;
1326 char aa_path[MAX_PATH];
1328 FOREACH_ALBUMART(i)
1330 /* albumart_slots may change during a yield of bufopen,
1331 * but that's no problem */
1332 if (tracks[track_widx].aa_hid[i] >= 0 || !albumart_slots[i].used)
1333 continue;
1335 /* we can only decode jpeg for embedded AA */
1336 bool embedded_albumart =
1337 track_id3->embed_albumart && track_id3->albumart.type == AA_TYPE_JPG;
1338 /* find_albumart will error out if the wps doesn't have AA */
1339 if (embedded_albumart || find_albumart(track_id3, aa_path,
1340 sizeof(aa_path), &(albumart_slots[i].dim)))
1342 int aa_hid;
1343 struct bufopen_bitmap_data user_data = {
1344 .dim = &(albumart_slots[i].dim),
1345 .embedded_albumart = NULL,
1347 if (embedded_albumart)
1349 user_data.embedded_albumart = &(track_id3->albumart);
1350 aa_hid = bufopen(track_id3->path, 0,
1351 TYPE_BITMAP, &user_data);
1353 else
1355 aa_hid = bufopen(aa_path, 0, TYPE_BITMAP,
1356 &user_data);
1358 if(aa_hid == ERR_BUFFER_FULL)
1360 filling = STATE_FULL;
1361 logf("buffer is full for now (get album art)");
1362 return; /* No space for track's album art, not an error */
1364 else if (aa_hid < 0)
1366 /* another error, ignore AlbumArt */
1367 logf("Album art loading failed");
1369 tracks[track_widx].aa_hid[i] = aa_hid;
1373 #endif
1375 /* Load the codec. */
1376 if (!audio_loadcodec(start_play))
1378 if (tracks[track_widx].codec_hid == ERR_BUFFER_FULL)
1380 /* No space for codec on buffer, not an error */
1381 filling = STATE_FULL;
1382 return;
1385 /* This is an error condition, either no codec was found, or reading
1386 * the codec file failed part way through, either way, skip the track */
1387 /* FIXME: We should not use splashf from audio thread! */
1388 splashf(HZ*2, "No codec for: %s", track_id3->path);
1389 /* Skip invalid entry from playlist. */
1390 playlist_skip_entry(NULL, last_peek_offset);
1391 return;
1394 track_id3->elapsed = 0;
1395 offset = track_id3->offset;
1396 size_t resume_rewind = (global_settings.resume_rewind *
1397 track_id3->bitrate * 1000) / 8;
1399 if (offset < resume_rewind)
1401 offset = 0;
1403 else
1405 offset -= resume_rewind;
1408 enum data_type type = TYPE_PACKET_AUDIO;
1410 switch (track_id3->codectype) {
1411 case AFMT_MPA_L1:
1412 case AFMT_MPA_L2:
1413 case AFMT_MPA_L3:
1414 if (offset > 0) {
1415 file_offset = offset;
1417 break;
1419 case AFMT_WAVPACK:
1420 if (offset > 0) {
1421 file_offset = offset;
1422 track_id3->elapsed = track_id3->length / 2;
1424 break;
1426 case AFMT_NSF:
1427 case AFMT_SPC:
1428 case AFMT_SID:
1429 logf("Loading atomic %d",track_id3->codectype);
1430 type = TYPE_ATOMIC_AUDIO;
1431 break;
1433 default:
1434 /* no special treatment needed */
1435 break;
1438 track_id3->offset = offset;
1440 logf("load track: %s", track_id3->path);
1442 if (file_offset > AUDIO_REBUFFER_GUESS_SIZE)
1443 file_offset -= AUDIO_REBUFFER_GUESS_SIZE;
1444 else if (track_id3->first_frame_offset)
1445 file_offset = track_id3->first_frame_offset;
1446 else
1447 file_offset = 0;
1449 tracks[track_widx].audio_hid = bufopen(track_id3->path, file_offset, type,
1450 NULL);
1452 /* No space left, not an error */
1453 if (tracks[track_widx].audio_hid == ERR_BUFFER_FULL)
1455 filling = STATE_FULL;
1456 logf("buffer is full for now (load audio)");
1457 return;
1459 else if (tracks[track_widx].audio_hid < 0)
1461 /* another error, do not continue either */
1462 logf("Could not add audio data handle");
1463 return;
1466 /* All required data is now available for the codec -- unless the
1467 autoresume feature is in effect. In the latter case, the codec
1468 must wait until after PLAYBACK_EVENT_TRACK_BUFFER, which may
1469 generate a resume position. */
1470 #ifdef HAVE_TAGCACHE
1471 if (! global_settings.autoresume_enable)
1472 #endif
1473 tracks[track_widx].taginfo_ready = true;
1475 if (start_play)
1477 ci.curpos=file_offset;
1478 buf_request_buffer_handle(tracks[track_widx].audio_hid);
1481 send_event(PLAYBACK_EVENT_TRACK_BUFFER, track_id3);
1483 #ifdef HAVE_TAGCACHE
1484 /* In case the autoresume feature has been enabled, finally all
1485 required data is available for the codec. */
1486 if (global_settings.autoresume_enable)
1487 tracks[track_widx].taginfo_ready = true;
1488 #endif
1490 track_widx = (track_widx + 1) & MAX_TRACK_MASK;
1492 /* load next track */
1493 LOGFQUEUE("audio > audio Q_AUDIO_FILL_BUFFER");
1494 queue_post(&audio_queue, Q_AUDIO_FILL_BUFFER, 0);
1496 return;
1499 static void audio_fill_file_buffer(bool start_play, size_t offset)
1501 trigger_cpu_boost();
1503 /* No need to rebuffer if there are track skips pending,
1504 * however don't cancel buffering on skipping while filling. */
1505 if (ci.new_track != 0 && filling != STATE_FILLING)
1506 return;
1507 filling = STATE_FILLING;
1509 /* Must reset the buffer before use if trashed or voice only - voice
1510 file size shouldn't have changed so we can go straight from
1511 AUDIOBUF_STATE_VOICED_ONLY to AUDIOBUF_STATE_INITIALIZED */
1512 if (buffer_state != AUDIOBUF_STATE_INITIALIZED)
1513 audio_reset_buffer();
1515 logf("Starting buffer fill");
1517 if (!start_play)
1518 audio_clear_track_entries();
1520 /* Save the current resume position once. */
1521 playlist_update_resume_info(audio_current_track());
1523 audio_load_track(offset, start_play);
1526 static void audio_rebuffer(void)
1528 logf("Forcing rebuffer");
1530 clear_track_info(CUR_TI);
1532 /* Reset track pointers */
1533 track_widx = track_ridx;
1534 audio_clear_track_entries();
1536 /* Reset a possibly interrupted track load */
1537 track_load_started = false;
1539 /* Fill the buffer */
1540 last_peek_offset = -1;
1541 ci.curpos = 0;
1543 if (!CUR_TI->taginfo_ready)
1544 memset(thistrack_id3, 0, sizeof(struct mp3entry));
1546 audio_fill_file_buffer(false, 0);
1549 /* Called on request from the codec to get a new track. This is the codec part
1550 of the track transition. */
1551 static int audio_check_new_track(void)
1553 int track_count = audio_track_count();
1554 int old_track_ridx = track_ridx;
1555 int i, idx;
1556 bool forward;
1557 struct mp3entry *temp = thistrack_id3;
1559 /* Now it's good time to send track finish events. */
1560 send_event(PLAYBACK_EVENT_TRACK_FINISH, thistrack_id3);
1561 /* swap the mp3entry pointers */
1562 thistrack_id3 = othertrack_id3;
1563 othertrack_id3 = temp;
1564 ci.id3 = thistrack_id3;
1565 memset(thistrack_id3, 0, sizeof(struct mp3entry));
1567 if (dir_skip)
1569 dir_skip = false;
1570 /* regardless of the return value we need to rebuffer.
1571 if it fails the old playlist will resume, else the
1572 next dir will start playing */
1573 playlist_next_dir(ci.new_track);
1574 ci.new_track = 0;
1575 audio_rebuffer();
1576 goto skip_done;
1579 if (new_playlist)
1580 ci.new_track = 0;
1582 /* If the playlist isn't that big */
1583 if (automatic_skip)
1585 while (!playlist_check(ci.new_track))
1587 if (ci.new_track >= 0)
1589 LOGFQUEUE("audio >|= codec Q_CODEC_REQUEST_FAILED");
1590 return Q_CODEC_REQUEST_FAILED;
1592 ci.new_track++;
1596 /* Update the playlist */
1597 last_peek_offset -= ci.new_track;
1599 if (playlist_next(ci.new_track) < 0)
1601 LOGFQUEUE("audio >|= codec Q_CODEC_REQUEST_FAILED");
1602 return Q_CODEC_REQUEST_FAILED;
1605 if (new_playlist)
1607 ci.new_track = 1;
1608 new_playlist = false;
1611 /* Save a pointer to the old track to allow later clearing */
1612 prev_ti = CUR_TI;
1614 for (i = 0; i < ci.new_track; i++)
1616 idx = (track_ridx + i) & MAX_TRACK_MASK;
1617 struct mp3entry *id3 = bufgetid3(tracks[idx].id3_hid);
1618 ssize_t offset = buf_handle_offset(tracks[idx].audio_hid);
1619 if (!id3 || offset < 0 || (unsigned)offset > id3->first_frame_offset)
1621 /* We don't have all the audio data for that track, so clear it,
1622 but keep the metadata. */
1623 if (tracks[idx].audio_hid >= 0 && bufclose(tracks[idx].audio_hid))
1625 tracks[idx].audio_hid = -1;
1626 tracks[idx].filesize = 0;
1631 /* Move to the new track */
1632 track_ridx = (track_ridx + ci.new_track) & MAX_TRACK_MASK;
1633 buf_set_base_handle(CUR_TI->audio_hid);
1636 if (automatic_skip)
1638 wps_offset = -ci.new_track;
1641 /* If it is not safe to even skip this many track entries */
1642 if (ci.new_track >= track_count || ci.new_track <= track_count - MAX_TRACK)
1644 ci.new_track = 0;
1645 audio_rebuffer();
1646 goto skip_done;
1649 forward = ci.new_track > 0;
1650 ci.new_track = 0;
1652 /* If the target track is clearly not in memory */
1653 if (CUR_TI->filesize == 0 || !CUR_TI->taginfo_ready)
1655 audio_rebuffer();
1656 goto skip_done;
1659 /* When skipping backwards, it is possible that we've found a track that's
1660 * buffered, but which is around the track-wrap and therefore not the track
1661 * we are looking for */
1662 if (!forward)
1664 int cur_idx = track_ridx;
1665 bool taginfo_ready = true;
1666 /* We've wrapped the buffer backwards if new > old */
1667 bool wrap = track_ridx > old_track_ridx;
1669 while (1)
1671 cur_idx = (cur_idx + 1) & MAX_TRACK_MASK;
1673 /* if we've advanced past the wrap when cur_idx is zeroed */
1674 if (!cur_idx)
1675 wrap = false;
1677 /* if we aren't still on the wrap and we've caught the old track */
1678 if (!(wrap || cur_idx < old_track_ridx))
1679 break;
1681 /* If we hit a track in between without valid tag info, bail */
1682 if (!tracks[cur_idx].taginfo_ready)
1684 taginfo_ready = false;
1685 break;
1688 if (!taginfo_ready)
1690 audio_rebuffer();
1694 skip_done:
1695 audio_update_trackinfo();
1696 LOGFQUEUE("audio >|= codec Q_CODEC_REQUEST_COMPLETE");
1697 return Q_CODEC_REQUEST_COMPLETE;
1700 unsigned long audio_prev_elapsed(void)
1702 return prev_track_elapsed;
1705 void audio_set_prev_elapsed(unsigned long setting)
1707 prev_track_elapsed = setting;
1710 static void audio_stop_codec_flush(void)
1712 ci.stop_codec = true;
1713 pcmbuf_pause(true);
1715 while (audio_codec_loaded)
1716 yield();
1718 /* If the audio codec is not loaded any more, and the audio is still
1719 * playing, it is now and _only_ now safe to call this function from the
1720 * audio thread */
1721 if (pcm_is_playing())
1723 pcmbuf_play_stop();
1724 pcm_play_lock();
1725 queue_clear(&pcmbuf_queue);
1726 pcm_play_unlock();
1728 pcmbuf_pause(paused);
1731 static void audio_stop_playback(void)
1733 if (playing)
1735 /* If we were playing, save resume information */
1736 struct mp3entry *id3 = NULL;
1738 if (!ci.stop_codec)
1740 /* Set this early, the outside code yields and may allow the codec
1741 to try to wait for a reply on a buffer wait */
1742 ci.stop_codec = true;
1743 id3 = audio_current_track();
1746 /* Save the current playing spot, or NULL if the playlist has ended */
1747 playlist_update_resume_info(id3);
1749 /* Now it's good time to send track finish events. Do this
1750 only if this hasn't been done already as part of a track
1751 switch. */
1752 if (id3 == thistrack_id3)
1753 send_event(PLAYBACK_EVENT_TRACK_FINISH, thistrack_id3);
1755 /* TODO: Create auto bookmark too? */
1757 prev_track_elapsed = othertrack_id3->elapsed;
1759 remove_event(BUFFER_EVENT_BUFFER_LOW, buffering_low_buffer_callback);
1762 audio_stop_codec_flush();
1763 paused = false;
1764 playing = false;
1765 track_load_started = false;
1767 filling = STATE_IDLE;
1769 /* Mark all entries null. */
1770 audio_clear_track_entries();
1772 /* Close all tracks */
1773 audio_release_tracks();
1776 static void audio_play_start(size_t offset)
1778 int i;
1780 send_event(PLAYBACK_EVENT_START_PLAYBACK, NULL);
1781 #if INPUT_SRC_CAPS != 0
1782 audio_set_input_source(AUDIO_SRC_PLAYBACK, SRCF_PLAYBACK);
1783 audio_set_output_source(AUDIO_SRC_PLAYBACK);
1784 #endif
1786 /* Wait for any previously playing audio to flush - TODO: Not necessary? */
1787 paused = false;
1788 audio_stop_codec_flush();
1790 playing = true;
1791 track_load_started = false;
1793 ci.new_track = 0;
1794 ci.seek_time = 0;
1795 wps_offset = 0;
1797 sound_set_volume(global_settings.volume);
1798 track_widx = track_ridx = 0;
1799 buf_set_base_handle(-1);
1801 /* Clear all track entries. */
1802 for (i = 0; i < MAX_TRACK; i++) {
1803 clear_track_info(&tracks[i]);
1806 last_peek_offset = -1;
1808 /* Officially playing */
1809 queue_reply(&audio_queue, 1);
1811 audio_fill_file_buffer(true, offset);
1813 add_event(BUFFER_EVENT_BUFFER_LOW, false, buffering_low_buffer_callback);
1815 LOGFQUEUE("audio > audio Q_AUDIO_TRACK_CHANGED");
1816 queue_post(&audio_queue, Q_AUDIO_TRACK_CHANGED, 0);
1820 /* Invalidates all but currently playing track. */
1821 static void audio_invalidate_tracks(void)
1823 if (audio_have_tracks())
1825 last_peek_offset = 0;
1826 track_widx = track_ridx;
1828 /* Mark all other entries null (also buffered wrong metadata). */
1829 audio_clear_track_entries();
1831 track_widx = (track_widx + 1) & MAX_TRACK_MASK;
1833 audio_fill_file_buffer(false, 0);
1834 send_event(PLAYBACK_EVENT_TRACK_CHANGE, thistrack_id3);
1838 static void audio_new_playlist(void)
1840 /* Prepare to start a new fill from the beginning of the playlist */
1841 last_peek_offset = -1;
1842 if (audio_have_tracks())
1844 if (paused)
1845 skipped_during_pause = true;
1846 track_widx = track_ridx;
1847 audio_clear_track_entries();
1849 track_widx = (track_widx + 1) & MAX_TRACK_MASK;
1851 /* Mark the current track as invalid to prevent skipping back to it */
1852 CUR_TI->taginfo_ready = false;
1855 /* Signal the codec to initiate a track change forward */
1856 new_playlist = true;
1857 ci.new_track = 1;
1859 /* Officially playing */
1860 queue_reply(&audio_queue, 1);
1862 audio_fill_file_buffer(false, 0);
1865 /* Called on manual track skip */
1866 static void audio_initiate_track_change(long direction)
1868 logf("audio_initiate_track_change(%ld)", direction);
1870 ci.new_track += direction;
1871 wps_offset -= direction;
1872 if (paused)
1873 skipped_during_pause = true;
1876 /* Called on manual dir skip */
1877 static void audio_initiate_dir_change(long direction)
1879 dir_skip = true;
1880 ci.new_track = direction;
1881 if (paused)
1882 skipped_during_pause = true;
1885 /* Called when PCM track change is complete */
1886 static void audio_finalise_track_change(void)
1888 logf("audio_finalise_track_change");
1890 if (automatic_skip)
1892 wps_offset = 0;
1893 automatic_skip = false;
1895 /* Invalidate prevtrack_id3 */
1896 memset(othertrack_id3, 0, sizeof(struct mp3entry));
1898 if (prev_ti && prev_ti->audio_hid < 0)
1900 /* No audio left so we clear all the track info. */
1901 clear_track_info(prev_ti);
1904 send_event(PLAYBACK_EVENT_TRACK_CHANGE, thistrack_id3);
1905 playlist_update_resume_info(audio_current_track());
1909 * Layout audio buffer as follows - iram buffer depends on target:
1910 * [|SWAP:iram][|TALK]|FILE|GUARD|PCM|[SWAP:dram[|iram]|]
1912 static void audio_reset_buffer(void)
1914 /* see audio_get_recording_buffer if this is modified */
1915 logf("audio_reset_buffer");
1917 /* If the setup of anything allocated before the file buffer is
1918 changed, do check the adjustments after the buffer_alloc call
1919 as it will likely be affected and need sliding over */
1921 /* Initially set up file buffer as all space available */
1922 malloc_buf = audiobuf + talk_get_bufsize();
1924 /* Align the malloc buf to line size.
1925 * Especially important to cf targets that do line reads/writes.
1926 * Also for targets which need aligned DMA storage buffers */
1927 malloc_buf = (unsigned char *)(((uintptr_t)malloc_buf + (CACHEALIGN_SIZE - 1)) & ~(CACHEALIGN_SIZE - 1));
1928 filebuf = malloc_buf; /* filebuf line align implied */
1929 filebuflen = (audiobufend - filebuf) & ~(CACHEALIGN_SIZE - 1);
1931 /* Subtract whatever the pcm buffer says it used plus the guard buffer */
1932 const size_t pcmbuf_size = pcmbuf_init(filebuf + filebuflen) +GUARD_BUFSIZE;
1933 if(pcmbuf_size > filebuflen)
1934 panicf("%s(): EOM (%zu > %zu)", __func__, pcmbuf_size, filebuflen);
1936 filebuflen -= pcmbuf_size;
1938 /* Make sure filebuflen is a longword multiple after adjustment - filebuf
1939 will already be line aligned */
1940 filebuflen &= ~3;
1942 buffering_reset(filebuf, filebuflen);
1944 /* Clear any references to the file buffer */
1945 buffer_state = AUDIOBUF_STATE_INITIALIZED;
1947 #if defined(ROCKBOX_HAS_LOGF) && defined(LOGF_ENABLE)
1948 /* Make sure everything adds up - yes, some info is a bit redundant but
1949 aids viewing and the sumation of certain variables should add up to
1950 the location of others. */
1952 size_t pcmbufsize;
1953 const unsigned char *pcmbuf = pcmbuf_get_meminfo(&pcmbufsize);
1954 logf("mabuf: %08X", (unsigned)malloc_buf);
1955 logf("fbuf: %08X", (unsigned)filebuf);
1956 logf("fbufe: %08X", (unsigned)(filebuf + filebuflen));
1957 logf("gbuf: %08X", (unsigned)(filebuf + filebuflen));
1958 logf("gbufe: %08X", (unsigned)(filebuf + filebuflen + GUARD_BUFSIZE));
1959 logf("pcmb: %08X", (unsigned)pcmbuf);
1960 logf("pcmbe: %08X", (unsigned)(pcmbuf + pcmbufsize));
1962 #endif
1965 static void audio_thread(void)
1967 struct queue_event ev;
1969 pcm_postinit();
1971 audio_thread_ready = true;
1973 while (1)
1975 if (filling != STATE_FILLING && filling != STATE_IDLE) {
1976 /* End of buffering, let's calculate the watermark and unboost */
1977 set_filebuf_watermark();
1978 cancel_cpu_boost();
1981 if (!pcmbuf_queue_scan(&ev))
1982 queue_wait_w_tmo(&audio_queue, &ev, HZ/2);
1984 switch (ev.id) {
1986 case Q_AUDIO_FILL_BUFFER:
1987 LOGFQUEUE("audio < Q_AUDIO_FILL_BUFFER %d", (int)ev.data);
1988 audio_fill_file_buffer((bool)ev.data, 0);
1989 break;
1991 case Q_AUDIO_FINISH_LOAD:
1992 LOGFQUEUE("audio < Q_AUDIO_FINISH_LOAD");
1993 audio_finish_load_track();
1994 buf_set_base_handle(CUR_TI->audio_hid);
1995 break;
1997 case Q_AUDIO_PLAY:
1998 LOGFQUEUE("audio < Q_AUDIO_PLAY");
1999 if (playing && ev.data <= 0)
2000 audio_new_playlist();
2001 else
2003 audio_stop_playback();
2004 audio_play_start((size_t)ev.data);
2006 break;
2008 case Q_AUDIO_STOP:
2009 LOGFQUEUE("audio < Q_AUDIO_STOP");
2010 if (playing)
2011 audio_stop_playback();
2012 if (ev.data != 0)
2013 queue_clear(&audio_queue);
2014 break;
2016 case Q_AUDIO_PAUSE:
2017 LOGFQUEUE("audio < Q_AUDIO_PAUSE");
2018 if (!(bool) ev.data && skipped_during_pause
2019 #ifdef HAVE_CROSSFADE
2020 && !pcmbuf_is_crossfade_active()
2021 #endif
2023 pcmbuf_play_stop(); /* Flush old track on resume after skip */
2024 skipped_during_pause = false;
2025 if (!playing)
2026 break;
2027 pcmbuf_pause((bool)ev.data);
2028 paused = (bool)ev.data;
2029 break;
2031 case Q_AUDIO_SKIP:
2032 LOGFQUEUE("audio < Q_AUDIO_SKIP");
2033 audio_initiate_track_change((long)ev.data);
2034 break;
2036 case Q_AUDIO_PRE_FF_REWIND:
2037 LOGFQUEUE("audio < Q_AUDIO_PRE_FF_REWIND");
2038 if (!playing)
2039 break;
2040 pcmbuf_pause(true);
2041 break;
2043 case Q_AUDIO_FF_REWIND:
2044 LOGFQUEUE("audio < Q_AUDIO_FF_REWIND");
2045 if (!playing)
2046 break;
2048 if ((long)ev.data == 0)
2050 /* About to restart the track - send track finish
2051 events if not already done. */
2052 if (thistrack_id3 == audio_current_track())
2053 send_event(PLAYBACK_EVENT_TRACK_FINISH, thistrack_id3);
2056 if (automatic_skip)
2058 /* An automatic track skip is in progress. Finalize it,
2059 then go back to the previous track */
2060 audio_finalise_track_change();
2061 ci.new_track = -1;
2063 ci.seek_time = (long)ev.data+1;
2064 break;
2066 case Q_AUDIO_CHECK_NEW_TRACK:
2067 LOGFQUEUE("audio < Q_AUDIO_CHECK_NEW_TRACK");
2068 queue_reply(&audio_queue, audio_check_new_track());
2069 break;
2071 case Q_AUDIO_DIR_SKIP:
2072 LOGFQUEUE("audio < Q_AUDIO_DIR_SKIP");
2073 audio_initiate_dir_change(ev.data);
2074 break;
2076 case Q_AUDIO_FLUSH:
2077 LOGFQUEUE("audio < Q_AUDIO_FLUSH");
2078 audio_invalidate_tracks();
2079 break;
2081 case Q_AUDIO_TRACK_CHANGED:
2082 /* PCM track change done */
2083 LOGFQUEUE("audio < Q_AUDIO_TRACK_CHANGED");
2084 audio_finalise_track_change();
2085 break;
2086 #if (CONFIG_PLATFORM & PLATFORM_NATIVE)
2087 case SYS_USB_CONNECTED:
2088 LOGFQUEUE("audio < SYS_USB_CONNECTED");
2089 if (playing)
2090 audio_stop_playback();
2091 #ifdef PLAYBACK_VOICE
2092 voice_stop();
2093 #endif
2094 usb_acknowledge(SYS_USB_CONNECTED_ACK);
2095 usb_wait_for_disconnect(&audio_queue);
2097 /* Mark all entries null. */
2098 audio_clear_track_entries();
2100 /* release tracks to make sure all handles are closed */
2101 audio_release_tracks();
2102 break;
2103 #endif
2105 case SYS_TIMEOUT:
2106 LOGFQUEUE_SYS_TIMEOUT("audio < SYS_TIMEOUT");
2107 break;
2109 default:
2110 /* LOGFQUEUE("audio < default : %08lX", ev.id); */
2111 break;
2112 } /* end switch */
2113 } /* end while */
2116 /* Initialize the audio system - called from init() in main.c.
2117 * Last function because of all the references to internal symbols
2119 void audio_init(void)
2121 unsigned int audio_thread_id;
2123 /* Can never do this twice */
2124 if (audio_is_initialized)
2126 logf("audio: already initialized");
2127 return;
2130 logf("audio: initializing");
2132 /* Initialize queues before giving control elsewhere in case it likes
2133 to send messages. Thread creation will be delayed however so nothing
2134 starts running until ready if something yields such as talk_init. */
2135 queue_init(&audio_queue, true);
2136 queue_init(&codec_queue, false);
2137 queue_init(&pcmbuf_queue, false);
2139 pcm_init();
2141 codec_init_codec_api();
2143 thistrack_id3 = &mp3entry_buf[0];
2144 othertrack_id3 = &mp3entry_buf[1];
2146 /* cuesheet support */
2147 if (global_settings.cuesheet)
2148 curr_cue = (struct cuesheet*)buffer_alloc(sizeof(struct cuesheet));
2150 /* initialize the buffer */
2151 filebuf = audiobuf;
2153 /* audio_reset_buffer must to know the size of voice buffer so init
2154 talk first */
2155 talk_init();
2157 make_codec_thread();
2159 audio_thread_id = create_thread(audio_thread, audio_stack,
2160 sizeof(audio_stack), CREATE_THREAD_FROZEN,
2161 audio_thread_name IF_PRIO(, PRIORITY_USER_INTERFACE)
2162 IF_COP(, CPU));
2164 queue_enable_queue_send(&audio_queue, &audio_queue_sender_list,
2165 audio_thread_id);
2167 #ifdef PLAYBACK_VOICE
2168 voice_thread_init();
2169 #endif
2171 #ifdef HAVE_CROSSFADE
2172 /* Set crossfade setting for next buffer init which should be about... */
2173 pcmbuf_request_crossfade_enable(global_settings.crossfade);
2174 #endif
2176 /* initialize the buffering system */
2178 buffering_init();
2179 /* ...now! Set up the buffers */
2180 audio_reset_buffer();
2182 int i;
2183 for(i = 0; i < MAX_TRACK; i++)
2185 tracks[i].audio_hid = -1;
2186 tracks[i].id3_hid = -1;
2187 tracks[i].codec_hid = -1;
2188 tracks[i].cuesheet_hid = -1;
2190 #ifdef HAVE_ALBUMART
2191 FOREACH_ALBUMART(i)
2193 int j;
2194 for (j = 0; j < MAX_TRACK; j++)
2196 tracks[j].aa_hid[i] = -1;
2199 #endif
2201 add_event(BUFFER_EVENT_REBUFFER, false, buffering_handle_rebuffer_callback);
2202 add_event(BUFFER_EVENT_FINISHED, false, buffering_handle_finished_callback);
2204 /* Probably safe to say */
2205 audio_is_initialized = true;
2207 sound_settings_apply();
2208 #ifdef HAVE_DISK_STORAGE
2209 audio_set_buffer_margin(global_settings.buffer_margin);
2210 #endif
2212 /* it's safe to let the threads run now */
2213 #ifdef PLAYBACK_VOICE
2214 voice_thread_resume();
2215 #endif
2216 thread_thaw(codec_thread_id);
2217 thread_thaw(audio_thread_id);
2219 } /* audio_init */
2221 bool audio_is_thread_ready(void)
2223 return audio_thread_ready;
2226 size_t audio_get_filebuflen(void)
2228 return filebuflen;
2231 int get_audio_hid()
2233 return CUR_TI->audio_hid;
2236 int *get_codec_hid()
2238 return &tracks[track_ridx].codec_hid;