Index: apps/playback.c
===================================================================
--- apps/playback.c	(revision 29752)
+++ apps/playback.c	(working copy)
@@ -9,6 +9,7 @@
  *
  * Copyright (C) 2005-2007 Miika Pekkarinen
  * Copyright (C) 2007-2008 Nicolas Pennequin
+ * Copyright (C) 2011      Michael Sevakis
  *
  * This program is free software; you can redistribute it and/or
  * modify it under the terms of the GNU General Public License
@@ -19,53 +20,61 @@
  * KIND, either express or implied.
  *
  ****************************************************************************/
-
-/* TODO: Pause should be handled in here, rather than PCMBUF so that voice can
- * play whilst audio is paused */
 #include "config.h"
 #include "system.h"
-#include <string.h>
-#include "playback.h"
-#include "codec_thread.h"
 #include "kernel.h"
+#include "panic.h"
+#include "buffer.h"
+#include "sound.h"
+#include "ata.h"
+#include "usb.h"
 #include "codecs.h"
+#include "codec_thread.h"
+#include "voice_thread.h"
+#include "metadata.h"
+#include "cuesheet.h"
 #include "buffering.h"
-#include "voice_thread.h"
-#include "usb.h"
-#include "ata.h"
+#include "talk.h"
 #include "playlist.h"
+#include "abrepeat.h"
 #include "pcmbuf.h"
-#include "buffer.h"
-#include "cuesheet.h"
+#include "playback.h"
+
 #ifdef HAVE_TAGCACHE
 #include "tagcache.h"
 #endif
+
+#ifdef AUDIO_HAVE_RECORDING
+#include "pcm_record.h"
+#endif
+
 #ifdef HAVE_LCD_BITMAP
 #ifdef HAVE_ALBUMART
 #include "albumart.h"
 #endif
 #endif
-#include "sound.h"
-#include "metadata.h"
-#include "splash.h"
-#include "talk.h"
-#include "panic.h"
 
-#ifdef HAVE_RECORDING
-#include "pcm_record.h"
-#endif
+/* TODO: The audio thread really is doing multitasking of acting like a
+         consumer and producer of tracks. It may be advantageous to better
+         logically separate the two functions. I won't go that far just yet. */
 
+/* Internal support for voice playback */
 #define PLAYBACK_VOICE
 
-/* amount of guess-space to allow for codecs that must hunt and peck
- * for their correct seeek target, 32k seems a good size */
+#if CONFIG_PLATFORM & PLATFORM_NATIVE
+/* Application builds don't support direct code loading */
+#define HAVE_CODEC_BUFFERING
+#endif
+
+/* Amount of guess-space to allow for codecs that must hunt and peck
+ * for their correct seek target, 32k seems a good size */
 #define AUDIO_REBUFFER_GUESS_SIZE    (1024*32)
 
 /* Define LOGF_ENABLE to enable logf output in this file */
-/*#define LOGF_ENABLE*/
+/* #define LOGF_ENABLE */
 #include "logf.h"
 
-/* macros to enable logf for queues
+/* Macros to enable logf for queues
    logging on SYS_TIMEOUT can be disabled */
 #ifdef SIMULATOR
 /* Define this for logf output of all queuing except SYS_TIMEOUT */
@@ -86,202 +95,279 @@
 #define LOGFQUEUE_SYS_TIMEOUT(...)
 #endif
 
+/* Variables are commented with the threads that use them:
+ * A=audio, C=codec, O=other. A suffix of "-" indicates that the variable is
+ * read but not updated on that thread. Audio is the only user unless otherwise
+ * specified.
+ */
 
-static enum filling_state {
-    STATE_IDLE,     /* audio is stopped: nothing to do */
-    STATE_FILLING,  /* adding tracks to the buffer */
-    STATE_FULL,     /* can't add any more tracks */
-    STATE_END_OF_PLAYLIST, /* all remaining tracks have been added */
-    STATE_FINISHED, /* all remaining tracks are fully buffered */
-    STATE_ENDING,   /* audio playback is ending */
-#if (CONFIG_PLATFORM & PLATFORM_NATIVE)
-    STATE_USB,      /* USB mode, ignore most messages */
-#endif
-} filling;
+/** Miscellaneous **/
+bool audio_is_initialized = false; /* (A,O-) */
+extern struct codec_api ci;        /* (A,C) */
 
-/* As defined in plugins/lib/xxx2wav.h */
-#define GUARD_BUFSIZE  (32*1024)
+/** Possible arrangements of the main buffer **/
+static enum audio_buffer_state
+{
+    AUDIOBUF_STATE_TRASHED     = -1,     /* trashed; must be reset */
+    AUDIOBUF_STATE_INITIALIZED =  0,     /* voice+audio OR audio-only */
+    AUDIOBUF_STATE_VOICED_ONLY =  1,     /* voice-only */
+} buffer_state = AUDIOBUF_STATE_TRASHED; /* (A,O) */
 
-bool audio_is_initialized = false;
-static bool audio_thread_ready SHAREDBSS_ATTR = false;
+/** Main state control **/
+static bool ff_rw_mode SHAREDBSS_ATTR = false; /* Pre-ff-rewind mode (A,O-) */
 
-/* Variables are commented with the threads that use them: *
- * A=audio, C=codec, V=voice. A suffix of - indicates that *
- * the variable is read but not updated on that thread.    */
-/* TBD: Split out "audio" and "playback" (ie. calling) threads */
+enum play_status
+{
+    PLAY_STOPPED = 0,
+    PLAY_PLAYING = AUDIO_STATUS_PLAY,
+    PLAY_PAUSED  = AUDIO_STATUS_PLAY | AUDIO_STATUS_PAUSE,
+} play_status = PLAY_STOPPED;
 
-/* Main state control */
-static volatile bool playing SHAREDBSS_ATTR = false;/* Is audio playing? (A) */
-static volatile bool paused SHAREDBSS_ATTR = false; /* Is audio paused? (A/C-) */
+/* Sizeable things that only need exist during playback and not when stopped */
+static struct audio_scratch_memory
+{
+    struct mp3entry codec_id3; /* (A,C) */
+    struct mp3entry unbuffered_id3;
+    struct cuesheet *curr_cue; /* Will follow this structure */
+} * audio_scratch_memory = NULL;
 
-/* Ring buffer where compressed audio and codecs are loaded */
-static unsigned char *filebuf = NULL;       /* Start of buffer (A/C-) */
-static size_t filebuflen = 0;               /* Size of buffer (A/C-) */
-/* FIXME: make buf_ridx (C/A-) */
-
-/* Possible arrangements of the buffer */
-enum audio_buffer_state
+/* These are used to store the current, next and optionally the peek-ahead
+ * mp3entry's - this guarentees that the pointer returned by audio_current/
+ * next_track will be valid for the full duration of the currently playing
+ * track */
+enum audio_id3_types
 {
-    AUDIOBUF_STATE_TRASHED = -1,    /* trashed; must be reset */
-    AUDIOBUF_STATE_INITIALIZED = 0, /* voice+audio OR audio-only */
-    AUDIOBUF_STATE_VOICED_ONLY = 1, /* voice-only */
+    /* These are allocated statically */
+    PLAYING_ID3 = 0,
+    NEXTTRACK_ID3,
+#ifdef AUDIO_FAST_SKIP_PREVIEW
+    /* The real playing metadata must has to be protected since it contains
+       critical info for other features */
+    PLAYING_PEEK_ID3,
+#endif
+    ID3_TYPE_NUM_STATIC,
+    /* These go in the scratch memory */
+    UNBUFFERED_ID3 = ID3_TYPE_NUM_STATIC,
+    CODEC_ID3,
 };
-static int buffer_state = AUDIOBUF_STATE_TRASHED; /* Buffer state */
+static struct mp3entry static_id3_entries[ID3_TYPE_NUM_STATIC]; /* (A,O) */
 
-/* These are used to store the current and next (or prev if the current is the last)
- * mp3entry's in a round-robin system. This guarentees that the pointer returned
- * by audio_current/next_track will be valid for the full duration of the
- * currently playing track */
-static struct mp3entry mp3entry_buf[2];
-struct mp3entry *thistrack_id3,  /* the currently playing track */
-                *othertrack_id3; /* prev track during track-change-transition, or end of playlist,
-                                  * next track otherwise */
-static struct mp3entry unbuffered_id3; /* the id3 for the first unbuffered track */
+/* Peeking functions can yield and mess us up */
+static struct mutex id3_mutex SHAREDBSS_ATTR; /* (A,0)*/
 
-/* for cuesheet support */
-static struct cuesheet *curr_cue = NULL;
 
+/** For Scrobbler support **/
 
+/* Previous track elapsed time */
+static unsigned long prev_track_elapsed = 0; /* (A,O-) */
+
+
+/** For album art support **/
 #define MAX_MULTIPLE_AA SKINNABLE_SCREENS_COUNT
-
 #ifdef HAVE_ALBUMART
 
-static struct albumart_slot {
-    struct dim dim;     /* holds width, height of the albumart */
-    int used;           /* counter, increments if something uses it */
-} albumart_slots[MAX_MULTIPLE_AA];
+static struct albumart_slot
+{
+    struct dim dim;     /* Holds width, height of the albumart */
+    int used;           /* Counter; increments if something uses it */
+} albumart_slots[MAX_MULTIPLE_AA]; /* (A,O) */
 
 #define FOREACH_ALBUMART(i) for(i = 0;i < MAX_MULTIPLE_AA; i++)
-#endif
+#endif /* HAVE_ALBUMART */
 
 
-#define MAX_TRACK       128
-#define MAX_TRACK_MASK  (MAX_TRACK-1)
+/** Information used for tracking buffer fills **/
 
-/* Track info structure about songs in the file buffer (A/C-) */
-static struct track_info {
-    int audio_hid;             /* The ID for the track's buffer handle */
-    int id3_hid;               /* The ID for the track's metadata handle */
-    int codec_hid;             /* The ID for the track's codec handle */
+/* Buffer and thread state tracking */
+static enum filling_state
+{
+    STATE_BOOT = 0, /* audio thread is not ready yet */
+    STATE_IDLE,     /* audio is stopped: nothing to do */
+    STATE_FILLING,  /* adding tracks to the buffer */
+    STATE_FULL,     /* can't add any more tracks */
+    STATE_END_OF_PLAYLIST, /* all remaining tracks have been added */
+    STATE_FINISHED, /* all remaining tracks are fully buffered */
+    STATE_ENDING,   /* audio playback is ending */
+    STATE_ENDED,    /* audio playback is done */
+#if (CONFIG_PLATFORM & PLATFORM_NATIVE)
+    STATE_USB,      /* USB mode, ignore most messages */
+#endif
+} filling = STATE_BOOT;
+
+/* Track info - holds information about each track in the buffer */
+struct track_info
+{
+    /* In per-track allocated order: */
+    int id3_hid;                /* Metadata handle ID */
+    int cuesheet_hid;           /* Parsed cueesheet handle ID */
 #ifdef HAVE_ALBUMART
-    int aa_hid[MAX_MULTIPLE_AA];/* The ID for the track's album art handle */
+    int aa_hid[MAX_MULTIPLE_AA];/* Album art handle IDs */
 #endif
-    int cuesheet_hid;          /* The ID for the track's parsed cueesheet handle */
+#ifdef HAVE_CODEC_BUFFERING
+    int codec_hid;              /* Buffered codec handle ID */
+#endif
+    int audio_hid;              /* Main audio data handle ID */
+    size_t filesize;            /* File total length on disk
+                                   TODO: This should be stored
+                                         in the handle or the
+                                         id3 and would use less
+                                         ram */
+};
 
-    size_t filesize;           /* File total length */
+/* Track list - holds info about all buffered tracks */
+#if MEMORYSIZE >= 32
+#define TRACK_LIST_LEN  128 /* Must be 2^int(+n) */
+#elif MEMORYSIZE >= 16
+#define TRACK_LIST_LEN   64
+#elif MEMORYSIZE >= 8
+#define TRACK_LIST_LEN   32
+#else
+#define TRACK_LIST_LEN   16
+#endif
 
-    bool taginfo_ready;        /* Is metadata read */
-    
-} tracks[MAX_TRACK];
+#define TRACK_LIST_MASK (TRACK_LIST_LEN-1)
 
-static volatile int track_ridx = 0;  /* Track being decoded (A/C-) */
-static int track_widx = 0;           /* Track being buffered (A) */
-#define CUR_TI (&tracks[track_ridx]) /* Playing track info pointer (A/C-) */
+static struct
+{
+    /* read, write and current are maintained unwrapped, limited only by the
+       unsigned int range and wrap-safe comparisons are used */
 
-static struct track_info *prev_ti = NULL;  /* Pointer to the previously played
-                                              track */
+    /* NOTE: there appears to be a bug in arm-elf-eabi-gcc 4.4.4 for ARMv4 where
+       if 'end' follows 'start' in this structure, track_list_count performs
+       'start - end' rather than 'end - start', giving negative count values...
+       so leave it this way for now! */
+    unsigned int end;           /* Next open position */
+    unsigned int start;         /* First track in list */
+    unsigned int current;       /* Currently decoding track */
+    struct track_info tracks[TRACK_LIST_LEN]; /* Buffered track information */
+} track_list; /* (A, O-) */
 
-/* Information used only for filling the buffer */
-/* Playlist steps from playing track to next track to be buffered (A) */
-static int last_peek_offset = 0;
 
-/* Scrobbler support */
-static unsigned long prev_track_elapsed = 0; /* Previous track elapsed time (C/A-)*/
+/* Playlist steps from playlist position to next track to be buffered */
+static int playlist_peek_offset = 0;
 
-/* Track change controls */
-static bool automatic_skip = false; /* Who initiated in-progress skip? (A) */
-extern bool track_transition;       /* Are we in a track transition? */
-static bool dir_skip = false;       /* Is a directory skip pending? (A) */
-static bool new_playlist = false;   /* Are we starting a new playlist? (A) */
-static int wps_offset = 0;          /* Pending track change offset, to keep WPS responsive (A) */
-static bool skipped_during_pause = false; /* Do we need to clear the PCM buffer when playback resumes (A) */
+/* Metadata handle of track load in progress (meaning all handles have not
+   yet been opened for the track, id3 always exists or the track does not)
 
-static bool start_play_g = false; /* Used by audio_load_track to notify
-                                     audio_finish_load_track about start_play */
+   Tracks are keyed by their metadata handles if track list pointers are
+   insufficient to make comparisons */
+static int in_progress_id3_hid = ERR_HANDLE_NOT_FOUND;
 
-/* True when a track load is in progress, i.e. audio_load_track() has returned
- * but audio_finish_load_track() hasn't been called yet. Used to avoid allowing
- * audio_load_track() to get called twice in a row, which would cause problems.
- */
-static bool track_load_started = false;
-
 #ifdef HAVE_DISK_STORAGE
-static size_t buffer_margin  = 5; /* Buffer margin aka anti-skip buffer (A/C-) */
+/* Buffer margin A.K.A. anti-skip buffer (in seconds) */
+static size_t buffer_margin = 5;
 #endif
 
-/* Event queues */
-struct event_queue audio_queue SHAREDBSS_ATTR;
-static struct event_queue pcmbuf_queue SHAREDBSS_ATTR;
+/* Values returned for track loading */
+enum track_load_status
+{
+    LOAD_TRACK_ERR_START_CODEC   = -6,
+    LOAD_TRACK_ERR_FINISH_FAILED = -5,
+    LOAD_TRACK_ERR_FINISH_FULL   = -4,
+    LOAD_TRACK_ERR_BUSY          = -3,
+    LOAD_TRACK_ERR_NO_MORE       = -2,
+    LOAD_TRACK_ERR_FAILED        = -1,
+    LOAD_TRACK_OK                =  0,
+    LOAD_TRACK_READY             =  1,
+};
 
-extern struct codec_api ci;
-extern unsigned int codec_thread_id;
+/** Track change controls **/
 
-/* Multiple threads */
-/* Set the watermark to trigger buffer fill (A/C) */
-static void set_filebuf_watermark(void);
+/* What sort of skip is pending globally? */
+enum track_skip_type
+{
+    /* Relative to what user is intended to see: */
+    /* Codec: +0, Track List: +0, Playlist: +0 */
+    TRACK_SKIP_NONE = 0,          /* no track skip */
+    /* Codec: +1, Track List: +1, Playlist: +0 */
+    TRACK_SKIP_AUTO,              /* codec-initiated skip */
+    /* Codec: +1, Track List: +1, Playlist: +1 */
+    TRACK_SKIP_AUTO_NEW_PLAYLIST, /* codec-initiated skip is new playlist */
+    /* Codec: xx, Track List: +0, Playlist: +0 */
+    TRACK_SKIP_AUTO_END_PLAYLIST, /* codec-initiated end of playlist */
+    /* Manual skip: Never pends */
+    TRACK_SKIP_MANUAL,            /* manual track skip */
+    /* Manual skip: Never pends */
+    TRACK_SKIP_DIR_CHANGE,        /* manual directory skip */
+} skip_pending = TRACK_SKIP_NONE;
 
+/* Note about TRACK_SKIP_AUTO_NEW_PLAYLIST:
+   Fixing playlist code to be able to peek into the first song of
+   the next playlist would fix any issues and this wouldn't need
+   to be a special case since pre-advancing the playlist would be
+   unneeded - it could be much more like TRACK_SKIP_AUTO and all
+   actions that require reversal during an in-progress transition
+   would work as expected */
+
+/* Used to indicate status for the events. Must be separate to satisfy all
+   clients so the correct metadata is read when sending the change events
+   and also so that it is read correctly outside the events. */
+static bool automatic_skip = false; /* (A, O-) */
+
+/* Pending manual track skip offset */
+static int skip_offset = 0; /* (A, O) */
+
+/* Track change notification */
+static struct
+{
+    unsigned int in;  /* Number of pcmbuf posts (audio isr) */
+    unsigned int out; /* Number of times audio has read the difference */
+} track_change = { 0, 0 };
+
+/** Codec status **/
+/* Did the codec notify us it finished while we were paused?
+   It is necessary to defer a codec-initiated skip until resuming or else
+   the track will move forward while not playing audio! If it is forgotten,
+   it will be missed altogether and playback will just sit there looking
+   stupid and comatose until the user does something */
+static bool codec_skip_pending = false;
+static bool codec_seeking = false;          /* Codec seeking ack expected? */
+
+
+/* Event queues */
+static struct event_queue audio_queue SHAREDBSS_ATTR;
+
 /* Audio thread */
 static struct queue_sender_list audio_queue_sender_list SHAREDBSS_ATTR;
 static long audio_stack[(DEFAULT_STACK_SIZE + 0x1000)/sizeof(long)];
 static const char audio_thread_name[] = "audio";
+static unsigned int audio_thread_id = 0;
 
-static void audio_thread(void);
-static void audio_initiate_track_change(long direction);
-static bool audio_have_tracks(void);
-static void audio_reset_buffer(void);
+/* Forward declarations */
+static void audio_start_playback(size_t offset, bool restart, bool invalid);
 static void audio_stop_playback(void);
+static void buffer_event_buffer_low_callback(void *data);
+static void buffer_event_rebuffer_callback(void *data);
+static void buffer_event_finished_callback(void *data);
 
+
 /**************************************/
 
-/** Pcmbuf callbacks */
+/** --- audio_queue helpers --- **/
 
-/* Between the codec and PCM track change, we need to keep updating the
- * "elapsed" value of the previous (to the codec, but current to the
- * user/PCM/WPS) track, so that the progressbar reaches the end.
- * During that transition, the WPS will display othertrack_id3. */
-void audio_pcmbuf_position_callback(unsigned int time)
+/* codec thread needs access */
+void audio_queue_post(long id, intptr_t data)
 {
-    time += othertrack_id3->elapsed;
-    othertrack_id3->elapsed = (time >= othertrack_id3->length)
-        ? othertrack_id3->length : time;
+    queue_post(&audio_queue, id, data);
 }
 
-/* Post message from pcmbuf that the end of the previous track
- * has just been played. */
-void audio_post_track_change(bool pcmbuf)
+static intptr_t audio_queue_send(long id, intptr_t data)
 {
-    if (pcmbuf)
-    {
-        LOGFQUEUE("pcmbuf > pcmbuf Q_AUDIO_TRACK_CHANGED");
-        queue_post(&pcmbuf_queue, Q_AUDIO_TRACK_CHANGED, 0);
-    }
-    else
-    {
-        LOGFQUEUE("pcmbuf > audio Q_AUDIO_TRACK_CHANGED");
-        queue_post(&audio_queue, Q_AUDIO_TRACK_CHANGED, 0);
-    }
+    return queue_send(&audio_queue, id, data);
 }
 
-/* Scan the pcmbuf queue and return true if a message pulled */
-static bool pcmbuf_queue_scan(struct queue_event *ev)
+
+/** --- MP3Entry --- **/
+
+/* Does the mp3entry have enough info for us to use it? */
+static struct mp3entry * valid_mp3entry(const struct mp3entry *id3)
 {
-    if (!queue_empty(&pcmbuf_queue))
-    {
-        /* Transfer message to audio queue */
-        pcm_play_lock();
-        /* Pull message - never, ever any blocking call! */
-        queue_wait_w_tmo(&pcmbuf_queue, ev, 0);
-        pcm_play_unlock();
-        return true;
-    }
-
-    return false;
+    return id3 && (id3->length != 0 || id3->filesize != 0) &&
+           id3->codectype != AFMT_UNKNOWN ? (struct mp3entry *)id3 : NULL;
 }
 
-
-/** Helper functions */
-
-static struct mp3entry *bufgetid3(int handle_id)
+/* Return a pointer to an mp3entry on the buffer, as it is */
+static struct mp3entry * bufgetid3(int handle_id)
 {
     if (handle_id < 0)
         return NULL;
@@ -295,6 +381,7 @@
     return id3;
 }
 
+/* Read an mp3entry from the buffer, adjusted */
 static bool bufreadid3(int handle_id, struct mp3entry *id3out)
 {
     struct mp3entry *id3 = bufgetid3(handle_id);
@@ -308,1201 +395,1403 @@
     return false;
 }
 
-static bool clear_track_info(struct track_info *track)
+/* Lock the id3 mutex */
+static void id3_mutex_lock(void)
 {
-    /* bufclose returns true if the handle is not found, or if it is closed
-     * successfully, so these checks are safe on non-existant handles */
-    if (!track)
-        return false;
-
-    if (track->codec_hid >= 0) {
-        if (bufclose(track->codec_hid))
-            track->codec_hid = -1;
-        else
-            return false;
-    }
-
-    if (track->id3_hid >= 0) {
-        if (bufclose(track->id3_hid))
-            track->id3_hid = -1;
-        else
-            return false;
-    }
-
-    if (track->audio_hid >= 0) {
-        if (bufclose(track->audio_hid))
-            track->audio_hid = -1;
-        else
-            return false;
-    }
-
-#ifdef HAVE_ALBUMART
-    {
-        int i;
-        FOREACH_ALBUMART(i)
-        {
-            if (track->aa_hid[i] >= 0) {
-                if (bufclose(track->aa_hid[i]))
-                    track->aa_hid[i] = -1;
-                else
-                    return false;
-            }   
-        }
-    }
-#endif
-
-    if (track->cuesheet_hid >= 0) {
-        if (bufclose(track->cuesheet_hid))
-            track->cuesheet_hid = -1;
-        else
-            return false;
-    }
-
-    track->filesize = 0;
-    track->taginfo_ready = false;
-
-    return true;
+    mutex_lock(&id3_mutex);
 }
 
-/* --- External interfaces --- */
-
-/* This sends a stop message and the audio thread will dump all it's
-   subsequenct messages */
-void audio_hard_stop(void)
+/* Unlock the id3 mutex */
+static void id3_mutex_unlock(void)
 {
-    /* Stop playback */
-    LOGFQUEUE("audio >| audio Q_AUDIO_STOP: 1");
-    queue_send(&audio_queue, Q_AUDIO_STOP, 1);
-#ifdef PLAYBACK_VOICE
-    voice_stop();
-#endif
+    mutex_unlock(&id3_mutex);
 }
 
-bool audio_restore_playback(int type)
+/* Return one of the collection of mp3entry pointers - collect them all here */
+static inline struct mp3entry * id3_get(enum audio_id3_types id3_num)
 {
-    switch (type)
+    switch (id3_num)
     {
-    case AUDIO_WANT_PLAYBACK:
-        if (buffer_state != AUDIOBUF_STATE_INITIALIZED)
-            audio_reset_buffer();
-        return true;
-    case AUDIO_WANT_VOICE:
-        if (buffer_state == AUDIOBUF_STATE_TRASHED)
-            audio_reset_buffer();
-        return true;
+    case UNBUFFERED_ID3:
+        return &audio_scratch_memory->unbuffered_id3;
+    case CODEC_ID3:
+        return &audio_scratch_memory->codec_id3;
     default:
-        return false;
+        return &static_id3_entries[id3_num];
     }
 }
 
-unsigned char *audio_get_buffer(bool talk_buf, size_t *buffer_size)
+/* Copy an mp3entry into one of the mp3 entries */
+static void id3_write(enum audio_id3_types id3_num,
+                      const struct mp3entry *id3_src)
 {
-    unsigned char *buf, *end;
+    struct mp3entry *dest_id3 = id3_get(id3_num);
 
-    if (audio_is_initialized)
-    {
-        audio_hard_stop();
-    }
-    /* else buffer_state will be AUDIOBUF_STATE_TRASHED at this point */
-
-    /* Reset the buffering thread so that it doesn't try to use the data */
-    buffering_reset(filebuf, filebuflen);
-
-    if (buffer_size == NULL)
-    {
-        /* Special case for talk_init to use since it already knows it's
-           trashed */
-        buffer_state = AUDIOBUF_STATE_TRASHED;
-        return NULL;
-    }
-
-    if (talk_buf || buffer_state == AUDIOBUF_STATE_TRASHED
-           || !talk_voice_required())
-    {
-        logf("get buffer: talk, audio");
-        /* Ok to use everything from audiobuf to audiobufend - voice is loaded,
-           the talk buffer is not needed because voice isn't being used, or
-           could be AUDIOBUF_STATE_TRASHED already. If state is
-           AUDIOBUF_STATE_VOICED_ONLY, no problem as long as memory isn't written
-           without the caller knowing what's going on. Changing certain settings
-           may move it to a worse condition but the memory in use by something
-           else will remain undisturbed.
-         */
-        if (buffer_state != AUDIOBUF_STATE_TRASHED)
-        {
-            talk_buffer_steal();
-            buffer_state = AUDIOBUF_STATE_TRASHED;
-        }
-
-        buf = audiobuf;
-        end = audiobufend;
-    }
+    if (id3_src)
+        copy_mp3entry(dest_id3, id3_src);
     else
-    {
-        /* Safe to just return this if already AUDIOBUF_STATE_VOICED_ONLY or
-           still AUDIOBUF_STATE_INITIALIZED */
-        /* Skip talk buffer and move pcm buffer to end to maximize available
-           contiguous memory - no audio running means voice will not need the
-           swap space */
-        logf("get buffer: audio");
-        buf = audiobuf + talk_get_bufsize();
-        end = audiobufend - pcmbuf_init(audiobufend);
-        buffer_state = AUDIOBUF_STATE_VOICED_ONLY;
-    }
-
-    *buffer_size = end - buf;
-
-    return buf;
+        wipe_mp3entry(dest_id3);
 }
 
-bool audio_buffer_state_trashed(void)
+/* Call id3_write "safely" because peek aheads can yield, even if the fast
+   preview isn't enabled */
+static void id3_write_locked(enum audio_id3_types id3_num,
+                             const struct mp3entry *id3_src)
 {
-    return buffer_state == AUDIOBUF_STATE_TRASHED;
+    id3_mutex_lock();
+    id3_write(id3_num, id3_src);
+    id3_mutex_unlock();
 }
 
-#ifdef HAVE_RECORDING
-unsigned char *audio_get_recording_buffer(size_t *buffer_size)
+
+/** --- Track info --- **/
+
+/* Close a handle and mark it invalid */
+static void track_info_close_handle(int *hid_p)
 {
-    /* Stop audio, voice and obtain all available buffer space */
-    audio_hard_stop();
-    talk_buffer_steal();
+    int hid = *hid_p;
 
-    unsigned char *end = audiobufend;
-    buffer_state = AUDIOBUF_STATE_TRASHED;
-    *buffer_size = end - audiobuf;
+    /* bufclose returns true if the handle is not found, or if it is closed
+     * successfully, so these checks are safe on non-existant handles */
+    if (hid >= 0)
+        bufclose(hid);
 
-    return (unsigned char *)audiobuf;
+    /* Always reset to "no handle" in case it was something else */
+    *hid_p = ERR_HANDLE_NOT_FOUND;
 }
 
-bool audio_load_encoder(int afmt)
+/* Close all handles in a struct track_info and clear it */
+static void track_info_close(struct track_info *info)
 {
-#if (CONFIG_PLATFORM & PLATFORM_NATIVE)
-    LOGFQUEUE("audio >| Q_AUDIO_LOAD_ENCODER: %d", afmt);
-    return queue_send(&audio_queue, Q_AUDIO_LOAD_ENCODER, afmt) > 0;
-#else
-    (void)afmt;
-    return true;
+    /* Close them in the order they are allocated on the buffer to speed up
+       the handle searching */
+    track_info_close_handle(&info->id3_hid);
+    track_info_close_handle(&info->cuesheet_hid);
+#ifdef HAVE_ALBUMART
+    int i;
+    FOREACH_ALBUMART(i)
+        track_info_close_handle(&info->aa_hid[i]);
 #endif
-} /* audio_load_encoder */
+#ifdef HAVE_CODEC_BUFFERING
+    track_info_close_handle(&info->codec_hid);
+#endif
+    track_info_close_handle(&info->audio_hid);
+    info->filesize = 0;
+}
 
-void audio_remove_encoder(void)
+/* Invalidate all members to initial values - does not close handles */
+static void track_info_wipe(struct track_info * info)
 {
-#if (CONFIG_PLATFORM & PLATFORM_NATIVE)
-    LOGFQUEUE("audio >| Q_AUDIO_LOAD_ENCODER: NULL");
-    queue_send(&audio_queue, Q_AUDIO_LOAD_ENCODER, AFMT_UNKNOWN);
+    info->id3_hid = ERR_HANDLE_NOT_FOUND;
+    info->cuesheet_hid = ERR_HANDLE_NOT_FOUND;
+#ifdef HAVE_ALBUMART
+    int i;
+    FOREACH_ALBUMART(i)
+        info->aa_hid[i] = ERR_HANDLE_NOT_FOUND;
 #endif
-} /* audio_remove_encoder */
+#ifdef HAVE_CODEC_BUFFERING
+    info->codec_hid = ERR_HANDLE_NOT_FOUND;
+#endif
+    info->audio_hid = ERR_HANDLE_NOT_FOUND;
+    info->filesize = 0;
+}
 
-#endif /* HAVE_RECORDING */
 
+/** --- Track list --- **/
 
-struct mp3entry* audio_current_track(void)
+/* Initialize the track list */
+static void track_list_init(void)
 {
-    const char *filename;
-    struct playlist_track_info trackinfo;
-    int cur_idx;
-    int offset = ci.new_track + wps_offset;
-    struct mp3entry *write_id3;
+    int i;
+    for (i = 0; i < TRACK_LIST_LEN; i++)
+        track_info_wipe(&track_list.tracks[i]);
 
-    cur_idx = (track_ridx + offset) & MAX_TRACK_MASK;
+    track_list.start = track_list.end = track_list.current;
+}
 
-    if (cur_idx == track_ridx && *thistrack_id3->path)
-    {
-        /* The usual case */
-        if (tracks[cur_idx].cuesheet_hid >= 0 && !thistrack_id3->cuesheet)
-        {
-            bufread(tracks[cur_idx].cuesheet_hid, sizeof(struct cuesheet), curr_cue);
-            thistrack_id3->cuesheet = curr_cue;
-        }
-        return thistrack_id3;
-    }
-    else if (automatic_skip && offset == -1 && *othertrack_id3->path)
-    {
-        /* We're in a track transition. The codec has moved on to the next track,
-             but the audio being played is still the same (now previous) track.
-             othertrack_id3.elapsed is being updated in an ISR by
-             codec_pcmbuf_position_callback */
-        if (tracks[cur_idx].cuesheet_hid >= 0 && !thistrack_id3->cuesheet)
-        {
-            bufread(tracks[cur_idx].cuesheet_hid, sizeof(struct cuesheet), curr_cue);
-            othertrack_id3->cuesheet = curr_cue;
-        }
-        return othertrack_id3;
-    }
+/* Return number of items allocated in the list */
+static unsigned int track_list_count(void)
+{
+    return track_list.end - track_list.start;
+}
 
-    if (offset != 0)
-    {
-        /* Codec may be using thistrack_id3, so it must not be overwritten.
-             If this is a manual skip, othertrack_id3 will become 
-             thistrack_id3 in audio_check_new_track().
-           FIXME: If this is an automatic skip, it probably means multiple 
-             short tracks fit in the PCM buffer.  Overwriting othertrack_id3
-             can lead to an incorrect value later.
-           Note that othertrack_id3 may also be used for next track.
-          */
-        write_id3 = othertrack_id3;
-    }
-    else 
-    {
-        write_id3 = thistrack_id3;
-    }
+/* Return true if the list is empty */
+static inline bool track_list_empty(void)
+{
+    return track_list.end == track_list.start;
+}
 
-    if (tracks[cur_idx].id3_hid >= 0)
-    {
-        /* The current track's info has been buffered but not read yet, so get it */
-        if (bufreadid3(tracks[cur_idx].id3_hid, write_id3))
-            return write_id3;
-    }
+/* Returns true if the list is holding the maximum number of items */
+static bool track_list_full(void)
+{
+    return track_list.end - track_list.start >= TRACK_LIST_LEN;
+}
 
-    /* We didn't find the ID3 metadata, so we fill temp_id3 with the little info
-       we have and return that. */
+/* Test if the index is within the allocated range */
+static bool track_list_in_range(int pos)
+{
+    return (int)(pos - track_list.start) >= 0 &&
+           (int)(pos - track_list.end) < 0;
+}
 
-    memset(write_id3, 0, sizeof(struct mp3entry));
+static struct track_info * track_list_entry(int pos)
+{
+    return &track_list.tracks[pos & TRACK_LIST_MASK];
+}
 
-    playlist_get_track_info(NULL, playlist_next(0)+wps_offset, &trackinfo);
-    filename = trackinfo.filename;
-    if (!filename)
-        filename = "No file!";
+/* Return the info of the last allocation plus an offset, NULL if result is
+   out of bounds */
+static struct track_info * track_list_last(int offset)
+{
+    /* Last is before the end since the end isn't inclusive */
+    unsigned int pos = track_list.end + offset - 1;
 
-#if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
-    if (tagcache_fill_tags(write_id3, filename))
-        return write_id3;
-#endif
+    if (!track_list_in_range(pos))
+        return NULL;
 
-    strlcpy(write_id3->path, filename, sizeof(write_id3->path));
-    write_id3->title = strrchr(write_id3->path, '/');
-    if (!write_id3->title)
-        write_id3->title = &write_id3->path[0];
-    else
-        write_id3->title++;
-
-    return write_id3;
+    return track_list_entry(pos);
 }
 
-struct mp3entry* audio_next_track(void)
+/* Allocate space at the end for another track if not full */
+static struct track_info * track_list_alloc_track(void)
 {
-    int next_idx;
-    int offset = ci.new_track + wps_offset;
-
-    if (!audio_have_tracks())
+    if (track_list_full())
         return NULL;
 
-    if (wps_offset == -1 && *thistrack_id3->path)
-    {
-        /* We're in a track transition. The next track for the WPS is the one
-           currently being decoded. */
-        return thistrack_id3;
-    }
+    return track_list_entry(track_list.end++);
+}
 
-    next_idx = (track_ridx + offset + 1) & MAX_TRACK_MASK;
+/* Remove the last track entry allocated in order to support backing out
+   of a track load */
+static void track_list_unalloc_track(void)
+{
+    if (track_list_empty())
+        return;
 
-    if (tracks[next_idx].id3_hid >= 0)
-    {
-        if (bufreadid3(tracks[next_idx].id3_hid, othertrack_id3))
-            return othertrack_id3;
-        else
-            return NULL;
-    }
+    track_list.end--;
 
-    if (next_idx == track_widx)
+    if (track_list.current == track_list.end &&
+        track_list.current != track_list.start)
     {
-        /* The next track hasn't been buffered yet, so we return the static
-           version of its metadata. */
-        return &unbuffered_id3;
+        /* Current _must_ remain within bounds */
+        track_list.current--;
     }
-
-    return NULL;
 }
 
-/* gets a copy of the id3 data */
-bool audio_peek_track(struct mp3entry* id3, int offset)
+/* Return current track plus an offset, NULL if result is out of bounds */
+static struct track_info * track_list_current(int offset)
 {
-    int next_idx;
-    int new_offset = ci.new_track + wps_offset + offset;
+    unsigned int pos = track_list.current + offset;
 
-    if (!audio_have_tracks())
-        return false;
-    next_idx = (track_ridx + new_offset) & MAX_TRACK_MASK;
+    if (!track_list_in_range(pos))
+        return NULL;
 
-    if (tracks[next_idx].id3_hid >= 0)
-        return bufreadid3(tracks[next_idx].id3_hid, id3);
-
-    return false;
+    return track_list_entry(pos);
 }
 
-#ifdef HAVE_ALBUMART
-
-int playback_current_aa_hid(int slot)
+/* Return current based upon what's intended that the user sees - not
+   necessarily where decoding is taking place */
+static struct track_info * track_list_user_current(int offset)
 {
-    if (slot < 0)
-        return -1;
-    int cur_idx;
-    int offset = ci.new_track + wps_offset;
+    if (skip_pending == TRACK_SKIP_AUTO ||
+        skip_pending == TRACK_SKIP_AUTO_NEW_PLAYLIST)
+    {
+        offset--;
+    }
 
-    cur_idx = track_ridx + offset;
-    cur_idx &= MAX_TRACK_MASK;
-    return tracks[cur_idx].aa_hid[slot];
+    return track_list_current(offset);
 }
 
-int playback_claim_aa_slot(struct dim *dim)
+/* Advance current track by an offset, return false if result is out of
+   bounds */
+static struct track_info * track_list_advance_current(int offset)
 {
-    int i;
+    unsigned int pos = track_list.current + offset;
 
-    /* first try to find a slot already having the size to reuse it
-     * since we don't want albumart of the same size buffered multiple times */
-    FOREACH_ALBUMART(i)
-    {
-        struct albumart_slot *slot = &albumart_slots[i];
-        if (slot->dim.width == dim->width
-                && slot->dim.height == dim->height)
-        {
-            slot->used++;
-            return i;
-        }
-    }
-    /* size is new, find a free slot */
-    FOREACH_ALBUMART(i)
-    {
-        if (!albumart_slots[i].used)
-        {
-            albumart_slots[i].used++;
-            albumart_slots[i].dim = *dim;
-            return i;
-        }
-    }
-    /* sorry, no free slot */
-    return -1;
+    if (!track_list_in_range(pos))
+        return NULL;
+
+    track_list.current = pos;
+    return track_list_entry(pos);
 }
 
-void playback_release_aa_slot(int slot)
+/* Clear tracks in the list, optionally preserving the current track -
+   returns 'false' if the operation was changed */
+enum track_clear_action
 {
-    /* invalidate the albumart_slot */
-    struct albumart_slot *aa_slot = &albumart_slots[slot];
+    TRACK_LIST_CLEAR_ALL = 0, /* Clear all tracks */
+    TRACK_LIST_KEEP_CURRENT,  /* Keep current only; clear before + after */
+    TRACK_LIST_KEEP_NEW       /* Keep current and those that follow */
+};
 
-    if (aa_slot->used > 0)
-        aa_slot->used--;
-}
-
-#endif
-void audio_play(long offset)
+static void track_list_clear(enum track_clear_action action)
 {
-    logf("audio_play");
+    logf("%s(%d)", __func__, (int)action);
 
-#ifdef PLAYBACK_VOICE
-    /* Truncate any existing voice output so we don't have spelling
-     * etc. over the first part of the played track */
-    talk_force_shutup();
-#endif
+    /* Don't care now since rebuffering is imminent */
+    buf_set_watermark(0);
 
-    /* Start playback */
-    LOGFQUEUE("audio >| audio Q_AUDIO_PLAY: %ld", offset);
-    /* Don't return until playback has actually started */
-    queue_send(&audio_queue, Q_AUDIO_PLAY, offset);
-}
+    if (action != TRACK_LIST_CLEAR_ALL)
+    {
+        struct track_info *cur = track_list_current(0);
 
-void audio_stop(void)
-{
-    /* Stop playback */
-    LOGFQUEUE("audio >| audio Q_AUDIO_STOP");
-    /* Don't return until playback has actually stopped */
-    queue_send(&audio_queue, Q_AUDIO_STOP, 0);
-}
+        if (!cur || cur->id3_hid < 0)
+            action = TRACK_LIST_CLEAR_ALL; /* Nothing worthwhile keeping */
+    }
 
-void audio_pause(void)
-{
-    LOGFQUEUE("audio >| audio Q_AUDIO_PAUSE");
-    /* Don't return until playback has actually paused */
-    queue_send(&audio_queue, Q_AUDIO_PAUSE, true);
-}
+    /* Noone should see this progressing */
+    int start = track_list.start;
+    int current = track_list.current;
+    int end = track_list.end;
 
-void audio_resume(void)
-{
-    LOGFQUEUE("audio >| audio Q_AUDIO_PAUSE resume");
-    /* Don't return until playback has actually resumed */
-    queue_send(&audio_queue, Q_AUDIO_PAUSE, false);
-}
+    track_list.start = current;
 
-void audio_skip(int direction)
-{
-    if (playlist_check(ci.new_track + wps_offset + direction))
+    switch (action)
     {
-        if (global_settings.beep)
-            pcmbuf_beep(2000, 100, 2500*global_settings.beep);
+    case TRACK_LIST_CLEAR_ALL:
+        /* Result: .start = .current, .end = .current */
+        track_list.end = current;
+        break;
 
-        LOGFQUEUE("audio > audio Q_AUDIO_SKIP %d", direction);
-        queue_post(&audio_queue, Q_AUDIO_SKIP, direction);
-        /* Update wps while our message travels inside deep playback queues. */
-        wps_offset += direction;
+    case TRACK_LIST_KEEP_CURRENT:
+        /* Result: .start = .current, .end = .current + 1 */
+        track_list.end = current + 1;
+        break;
+
+    case TRACK_LIST_KEEP_NEW:
+        /* Result: .start = .current, .end = .end */
+        end = current;
+        break;
     }
-    else
+
+    /* Close all open handles in the range except the for the current track
+       if preserving that */
+    while (start != end)
     {
-        /* No more tracks. */
-        if (global_settings.beep)
-            pcmbuf_beep(1000, 100, 1500*global_settings.beep);
+        if (action != TRACK_LIST_KEEP_CURRENT || start != current)
+        {
+            struct track_info *info =
+                &track_list.tracks[start & TRACK_LIST_MASK];
+
+            /* If this is the in-progress load, abort it */
+            if (in_progress_id3_hid >= 0 &&
+                info->id3_hid == in_progress_id3_hid)
+            {
+                in_progress_id3_hid = ERR_HANDLE_NOT_FOUND;
+            }
+
+            track_info_close(info);
+        }
+
+        start++;
     }
 }
 
-void audio_next(void)
-{
-    audio_skip(1);
-}
 
-void audio_prev(void)
-{
-    audio_skip(-1);
-}
+/** --- Audio buffer -- **/
 
-void audio_next_dir(void)
+/* What size is needed for the scratch buffer? */
+static size_t scratch_mem_size(void)
 {
-    LOGFQUEUE("audio > audio Q_AUDIO_DIR_SKIP 1");
-    queue_post(&audio_queue, Q_AUDIO_DIR_SKIP, 1);
-}
+    size_t size = sizeof (struct audio_scratch_memory);
 
-void audio_prev_dir(void)
-{
-    LOGFQUEUE("audio > audio Q_AUDIO_DIR_SKIP -1");
-    queue_post(&audio_queue, Q_AUDIO_DIR_SKIP, -1);
-}
+    if (global_settings.cuesheet)
+        size += sizeof (struct cuesheet);
 
-void audio_pre_ff_rewind(void)
-{
-    LOGFQUEUE("audio > audio Q_AUDIO_PRE_FF_REWIND");
-    queue_post(&audio_queue, Q_AUDIO_PRE_FF_REWIND, 0);
+    return size;
 }
 
-void audio_ff_rewind(long newpos)
+/* Initialize the memory area where data is stored that is only used when
+   playing audio and anything depending upon it */
+static void scratch_mem_init(void *mem)
 {
-    LOGFQUEUE("audio > audio Q_AUDIO_FF_REWIND");
-    queue_post(&audio_queue, Q_AUDIO_FF_REWIND, newpos);
-}
+    audio_scratch_memory = (struct audio_scratch_memory *)mem;
+    id3_write_locked(UNBUFFERED_ID3, NULL);
+    id3_write(CODEC_ID3, NULL);
+    ci.id3 = id3_get(CODEC_ID3);
+    audio_scratch_memory->curr_cue = NULL;
 
-void audio_flush_and_reload_tracks(void)
-{
-    LOGFQUEUE("audio > audio Q_AUDIO_FLUSH");
-    queue_post(&audio_queue, Q_AUDIO_FLUSH, 0);
+    if (global_settings.cuesheet)
+    {
+        audio_scratch_memory->curr_cue =
+            SKIPBYTES((struct cuesheet *)audio_scratch_memory,
+                      sizeof (struct audio_scratch_memory));
+    }
 }
 
-void audio_error_clear(void)
+/* Set up the audio buffer for playback */
+static void audio_reset_buffer(void)
 {
-#ifdef AUDIO_HAVE_RECORDING
-    pcm_rec_error_clear();
-#endif
-}
+    /*
+     * Layout audio buffer as follows:
+     * [[|TALK]|SCRATCH|BUFFERING|PCM|]
+     */
 
-int audio_status(void)
-{
-    int ret = 0;
+    /* see audio_get_recording_buffer if this is modified */
+    logf("%s()", __func__);
 
-    if (playing)
-        ret |= AUDIO_STATUS_PLAY;
+    /* If the setup of anything allocated before the file buffer is
+       changed, do check the adjustments after the buffer_alloc call
+       as it will likely be affected and need sliding over */
 
-    if (paused)
-        ret |= AUDIO_STATUS_PAUSE;
+    /* Initially set up file buffer as all space available */
+    unsigned char *filebuf = audiobuf + talk_get_bufsize();
+    size_t filebuflen = audiobufend - filebuf;
+    size_t allocsize;
 
-#ifdef HAVE_RECORDING
-    /* Do this here for constitency with mpeg.c version */
-    /* FIXME: pcm_rec_status() is deprecated */
-    ret |= pcm_rec_status();
-#endif
+    ALIGN_BUFFER(filebuf, filebuflen, sizeof (intptr_t));
 
-    return ret;
-}
+    /* Subtract whatever the pcm buffer says it used plus the guard buffer */
+    allocsize = pcmbuf_init(filebuf + filebuflen);
 
-bool audio_automatic_skip(void)
-{
-    return automatic_skip;
-}
+    /* Make sure filebuflen is a pointer sized multiple after adjustment */
+    allocsize = ALIGN_UP(allocsize, sizeof (intptr_t));
+    if (allocsize > filebuflen)
+        goto bufpanic;
 
-int audio_get_file_pos(void)
-{
-    return 0;
-}
+    filebuflen -= allocsize;
 
-#ifdef HAVE_DISK_STORAGE
-void audio_set_buffer_margin(int setting)
-{
-    static const unsigned short lookup[] = {5, 15, 30, 60, 120, 180, 300, 600};
-    buffer_margin = lookup[setting];
-    logf("buffer margin: %ld", (long)buffer_margin);
-    set_filebuf_watermark();
-}
-#endif
+    /* Scratch memory */
+    allocsize = scratch_mem_size();
+    if (allocsize > filebuflen)
+        goto bufpanic;
 
-#ifdef HAVE_CROSSFADE
-/* Take necessary steps to enable or disable the crossfade setting */
-void audio_set_crossfade(int enable)
-{
-    size_t offset;
-    bool was_playing;
-    size_t size;
+    scratch_mem_init(filebuf);
+    filebuf += allocsize;
+    filebuflen -= allocsize;
 
-    /* Tell it the next setting to use */
-    pcmbuf_request_crossfade_enable(enable);
+    buffering_reset(filebuf, filebuflen);
 
-    /* Return if size hasn't changed or this is too early to determine
-       which in the second case there's no way we could be playing
-       anything at all */
-    if (pcmbuf_is_same_size()) return;
+    /* Clear any references to the file buffer */
+    buffer_state = AUDIOBUF_STATE_INITIALIZED;
 
-    offset = 0;
-    was_playing = playing;
-
-    /* Playback has to be stopped before changing the buffer size */
-    if (was_playing)
+#if defined(ROCKBOX_HAS_LOGF) && defined(LOGF_ENABLE)
+    /* Make sure everything adds up - yes, some info is a bit redundant but
+       aids viewing and the sumation of certain variables should add up to
+       the location of others. */
     {
-        /* Store the track resume position */
-        offset = thistrack_id3->offset;
+        size_t pcmbufsize;
+        const unsigned char *pcmbuf = pcmbuf_get_meminfo(&pcmbufsize);
+        logf("fbuf:   %08X", (unsigned)filebuf);
+        logf("fbufe:  %08X", (unsigned)(filebuf + filebuflen));
+        logf("sbuf:   %08X", (unsigned)audio_scratch_memory);
+        logf("sbufe:  %08X", (unsigned)(audio_scratch_memory + allocsize));
+        logf("pcmb:   %08X", (unsigned)pcmbuf);
+        logf("pcmbe:  %08X", (unsigned)(pcmbuf + pcmbufsize));
     }
+#endif
 
-    /* Blast it - audio buffer will have to be setup again next time
-       something plays */
-    audio_get_buffer(true, &size);
+    return;
 
-    /* Restart playback if audio was running previously */
-    if (was_playing)
-        audio_play(offset);
+bufpanic:
+    panicf("%s(): EOM (%zu > %zu)", __func__, allocsize, filebuflen);
 }
-#endif
 
-/* --- Routines called from multiple threads --- */
-
-static void set_filebuf_watermark(void)
+/* Set the buffer margin to begin rebuffering when 'seconds' from empty */
+static void audio_update_filebuf_watermark(int seconds)
 {
-    if (!filebuf)
-        return;     /* Audio buffers not yet set up */
+    size_t bytes = 0;
 
 #ifdef HAVE_DISK_STORAGE
-    int seconds;
     int spinup = ata_spinup_time();
+
+    if (seconds == 0)
+    {
+        /* By current setting */
+        seconds = buffer_margin;
+    }
+    else
+    {
+        /* New setting */
+        buffer_margin = seconds;
+
+        if (buf_get_watermark() == 0)
+        {
+            /* Write a watermark only if the audio thread already did so for
+               itself or it will fail to set the event and the watermark - if
+               it hasn't yet, it will use the new setting when it does */
+            return;
+        }
+    }
+
     if (spinup)
-        seconds = (spinup / HZ) + 1;
+        seconds += (spinup / HZ) + 1;
     else
-        seconds = 5;
+        seconds += 5;
 
     seconds += buffer_margin;
 #else
     /* flash storage */
-    int seconds = 1;
+    seconds = 1;
 #endif
 
-    /* bitrate of last track in buffer dictates watermark */
-    struct mp3entry* id3 = NULL;
-    if (tracks[track_widx].taginfo_ready)
-        id3 = bufgetid3(tracks[track_widx].id3_hid);
+    /* Watermark is a function of the bitrate of the last track in the buffer */
+    struct mp3entry *id3 = NULL;   
+    struct track_info *info = track_list_last(0);
+
+    if (info)
+        id3 = valid_mp3entry(bufgetid3(info->id3_hid));
+
+    if (id3)
+    {
+        if (get_audio_base_data_type(id3->codectype) == TYPE_PACKET_AUDIO)
+        {
+            bytes = id3->bitrate * (1000/8) * seconds;
+        }
+        else
+        {
+            /* Bitrate has no meaning to buffering margin for atomic audio -
+               rebuffer when it's the only track left unless it's the only 
+               track that fits, in which case we should avoid constant buffer
+               low events */
+            if (track_list_count() > 1)
+                bytes = info->filesize + 1;
+        }
+    }
     else
-        id3 = bufgetid3(tracks[track_widx-1].id3_hid);
-    if (!id3) {
-        logf("fwmark: No id3 for last track (r%d/w%d), aborting!", track_ridx, track_widx);
-        return;
+    {
+        /* Then set the minimum - this should not occur anyway */
+        logf("fwmark: No id3 for last track (s%u/c%u/e%u)",
+             track_list.start, track_list.current, track_list.end);
     }
-    size_t bytes = id3->bitrate * (1000/8) * seconds;
-    buf_set_watermark(bytes);
-    logf("fwmark: %d", bytes);
+
+    /* Actually setting zero disables the notification and we use that
+       to detect that it has been reset */
+    buf_set_watermark(MAX(bytes, 1));
+    logf("fwmark: %lu", (unsigned long)bytes);
 }
 
-/* --- Buffering callbacks --- */
 
-static void buffering_low_buffer_callback(void *data)
+/** -- Track change notification -- **/
+
+/* Check the pcmbuf track changes and return write the message into the event
+   if there are any */
+static inline bool audio_pcmbuf_track_change_scan(void)
 {
-    (void)data;
-    logf("low buffer callback");
+    if (track_change.out != track_change.in)
+    {
+        track_change.out++;
+        return true;
+    }
 
-    if (filling == STATE_FULL || filling == STATE_END_OF_PLAYLIST) {
-        /* force a refill */
-        LOGFQUEUE("buffering > audio Q_AUDIO_FILL_BUFFER");
-        queue_post(&audio_queue, Q_AUDIO_FILL_BUFFER, 0);
+    return false;
+}
+
+/* Clear outstanding track change posts */
+static inline void audio_pcmbuf_track_change_clear(void)
+{
+    track_change.out = track_change.in;
+}
+
+/* Post a track change notification - called by audio ISR */
+static inline void audio_pcmbuf_track_change_post(void)
+{
+    track_change.in++;
+}
+
+
+/** --- Helper functions --- **/
+
+/* Removes messages that might end up in the queue before or while processing
+   a manual track change. Responding to them would be harmful since they
+   belong to a previous track's playback period. Anything that would generate
+   the stale messages must first be put into a state where it will not do so.
+ */
+static void audio_clear_track_notifications(void)
+{
+    static const long filter_list[][2] =
+    {
+        /* codec messages */
+        { Q_AUDIO_CODEC_SEEK_COMPLETE, Q_AUDIO_CODEC_COMPLETE },
+        /* track change messages */
+        { Q_AUDIO_TRACK_CHANGED, Q_AUDIO_TRACK_CHANGED },
+    };
+
+    const int filter_count = ARRAYLEN(filter_list) - 1;
+
+    /* Remove any pcmbuf notifications */
+    pcmbuf_monitor_track_change(false);
+    audio_pcmbuf_track_change_clear();
+
+    /* Scrub the audio queue of the old mold */
+    while (queue_peek_ex(&audio_queue, NULL,
+                         filter_count | QPEEK_REMOVE_EVENTS,
+                         filter_list))
+    {
+        yield(); /* Not strictly needed, per se, ad infinitum, ra, ra */
     }
 }
 
-static void buffering_handle_rebuffer_callback(void *data)
+/* Takes actions based upon track load status codes */
+static void audio_handle_track_load_status(enum track_load_status trackstat)
 {
-    (void)data;
-    LOGFQUEUE("audio >| audio Q_AUDIO_FLUSH");
-    queue_post(&audio_queue, Q_AUDIO_FLUSH, 0);
+    switch (trackstat)
+    {
+    case LOAD_TRACK_ERR_NO_MORE:
+        if (track_list_count() > 0)
+            break;
+
+    case LOAD_TRACK_ERR_START_CODEC:
+        audio_queue_post(Q_AUDIO_CODEC_COMPLETE, CODEC_ERROR);
+        break;
+
+    default:
+        break;
+    }
 }
 
-static void buffering_handle_finished_callback(void *data)
+/* Announce the end of playing the current track */
+static void audio_playlist_track_finish(void)
 {
-    logf("handle %d finished buffering", *(int*)data);
-    int hid = (*(int*)data);
+    struct mp3entry *id3 = valid_mp3entry(id3_get(PLAYING_ID3));
 
-    if (hid == tracks[track_widx].id3_hid)
+    playlist_update_resume_info(filling == STATE_ENDED ? NULL : id3);
+
+    if (id3)
     {
-        int offset = ci.new_track + wps_offset;
-        int next_idx = (track_ridx + offset + 1) & MAX_TRACK_MASK;
-        /* The metadata handle for the last loaded track has been buffered.
-           We can ask the audio thread to load the rest of the track's data. */
-        LOGFQUEUE("audio > audio Q_AUDIO_FINISH_LOAD");
-        queue_post(&audio_queue, Q_AUDIO_FINISH_LOAD, 0);
-        if (tracks[next_idx].id3_hid == hid)
-            send_event(PLAYBACK_EVENT_NEXTTRACKID3_AVAILABLE, NULL);
+        send_event(PLAYBACK_EVENT_TRACK_FINISH, id3);
+        prev_track_elapsed = id3->elapsed;
     }
     else
     {
-        /* This is most likely an audio handle, so we strip the useless
-           trailing tags that are left. */
-        strip_tags(hid);
-
-        if (hid == tracks[track_widx-1].audio_hid
-            && filling == STATE_END_OF_PLAYLIST)
-        {
-            /* This was the last track in the playlist.
-               We now have all the data we need. */
-            logf("last track finished buffering");
-            filling = STATE_FINISHED;
-        }
+        prev_track_elapsed = 0;
     }
 }
 
+/* Announce the beginning of the new track */
+static void audio_playlist_track_change(void)
+{
+    struct mp3entry *id3 = valid_mp3entry(id3_get(PLAYING_ID3));
 
-/* --- Audio thread --- */
+    if (id3)
+        send_event(PLAYBACK_EVENT_TRACK_CHANGE, id3);
 
-static bool audio_have_tracks(void)
-{
-    return (audio_track_count() != 0);
+    playlist_update_resume_info(id3);
 }
 
-static int audio_free_track_count(void)
+/* Change the data for the next track and send the event */
+static void audio_update_and_announce_next_track(const struct mp3entry *id3_next)
 {
-    /* Used tracks + free tracks adds up to MAX_TRACK - 1 */
-    return MAX_TRACK - 1 - audio_track_count();
+    id3_write_locked(NEXTTRACK_ID3, id3_next);
+    send_event(PLAYBACK_EVENT_NEXTTRACKID3_AVAILABLE,
+               id3_get(NEXTTRACK_ID3));
 }
 
-int audio_track_count(void)
+/* Wipe-out track metadata - current is optional */
+static void wipe_track_metadata(bool current)
 {
-    /* Calculate difference from track_ridx to track_widx
-     * taking into account a possible wrap-around. */
-    return (MAX_TRACK + track_widx - track_ridx) & MAX_TRACK_MASK;
+    id3_mutex_lock();
+    if (current)
+        id3_write(PLAYING_ID3, NULL);
+    id3_write(NEXTTRACK_ID3, NULL);
+    id3_write(UNBUFFERED_ID3, NULL);
+    id3_mutex_unlock();
 }
 
-long audio_filebufused(void)
+/* Called when buffering is completed on the last track handle */
+static void filling_is_finished(void)
 {
-    return (long) buf_used();
+    logf("last track finished buffering");
+
+    /* There's no more to load or watch for */
+    buf_set_watermark(0);
+    filling = STATE_FINISHED;
 }
 
-/* Update track info after successful a codec track change */
-static void audio_update_trackinfo(void)
+/* Stop the codec decoding or waiting for its data to be ready - returns
+   'false' if the codec ended up stopped */
+static bool halt_decoding_track(bool stop)
 {
-    bool resume = false;
+    /* If it was waiting for us to clear the buffer to make a rebuffer
+       happen, it should cease otherwise codec_stop could deadlock waiting
+       for the codec to go to its main loop - codec's request will now
+       force-fail */
+    bool retval = false;
 
-    /* Load the curent track's metadata into curtrack_id3 */
-    if (CUR_TI->id3_hid >= 0)
-        bufreadid3(CUR_TI->id3_hid, thistrack_id3);
+    buf_signal_handle(ci.audio_hid, true);
 
-    /* Reset current position */
-    thistrack_id3->elapsed = 0;
+    if (stop)
+        codec_stop();
+    else
+        retval = codec_pause();
 
-#ifdef HAVE_TAGCACHE
-    /* Ignoring resume position for automatic track change if so configured */
-    resume = global_settings.autoresume_enable &&
-        (!automatic_skip     /* Resume all manually selected tracks */
-         || global_settings.autoresume_automatic == AUTORESUME_NEXTTRACK_ALWAYS
-         || (global_settings.autoresume_automatic != AUTORESUME_NEXTTRACK_NEVER
-                                                /* Not never resume? */
-             && autoresumable(thistrack_id3))); /* Pass Resume filter? */
-#endif
+    audio_clear_track_notifications();
 
-    if (!resume)
-    {
-        thistrack_id3->offset = 0;
-    }
+    /* We now know it's idle and not waiting for buffered data */
+    buf_signal_handle(ci.audio_hid, false);
 
-    logf("audio_update_trackinfo: Set offset for %s to %lX\n",
-         thistrack_id3->title, thistrack_id3->offset);
+    codec_skip_pending = false;
+    codec_seeking = false;
 
-    /* Update the codec API */
-    ci.filesize = CUR_TI->filesize;
-    ci.id3 = thistrack_id3;
-    ci.curpos = 0;
-    ci.taginfo_ready = &CUR_TI->taginfo_ready;
+    return retval;
 }
 
-/* Clear tracks between write and read, non inclusive */
-static void audio_clear_track_entries(void)
+/* Clear the PCM on a manual skip */
+static void audio_clear_paused_pcm(void)
 {
-    int cur_idx = track_widx;
+    if (play_status == PLAY_PAUSED && !pcmbuf_is_crossfade_active())
+        pcmbuf_play_stop();
+}
 
-    logf("Clearing tracks: r%d/w%d", track_ridx, track_widx);
-
-    /* Loop over all tracks from write-to-read */
-    while (1)
+/* End the ff/rw mode */
+static void audio_ff_rewind_end(void)
+{
+    /* A seamless seek (not calling audio_pre_ff_rewind) skips this
+       section */
+    if (ff_rw_mode)
     {
-        cur_idx = (cur_idx + 1) & MAX_TRACK_MASK;
+        ff_rw_mode = false;
 
-        if (cur_idx == track_ridx)
-            break;
+        if (codec_seeking)
+        {
+            /* Clear the buffer */
+            pcmbuf_play_stop();
+        }
 
-        clear_track_info(&tracks[cur_idx]);
+        if (play_status != PLAY_PAUSED)
+        {
+            /* Seeking-while-playing, resume PCM playback */
+            pcmbuf_pause(false);
+        }
     }
 }
 
-/* Clear all tracks */
-static bool audio_release_tracks(void)
+/* Complete the codec seek */
+static void audio_complete_codec_seek(void)
 {
-    int i, cur_idx;
-
-    logf("releasing all tracks");
-
-    for(i = 0; i < MAX_TRACK; i++)
+    /* If a seek completed while paused, 'paused' is true.
+     * If seeking from seek mode, 'ff_rw_mode' is true. */
+    if (codec_seeking)
     {
-        cur_idx = (track_ridx + i) & MAX_TRACK_MASK;
-        if (!clear_track_info(&tracks[cur_idx]))
-            return false;
+        audio_ff_rewind_end();
+        codec_seeking = false; /* set _after_ the call! */
     }
+    /* else it's waiting and we must repond */
+}
 
-    return true;
+/* Get the current cuesheet pointer */
+static inline struct cuesheet * get_current_cuesheet(void)
+{
+    return audio_scratch_memory->curr_cue;
 }
 
-static bool audio_loadcodec(bool start_play)
+/* Read the cuesheet from the buffer */
+static void buf_read_cuesheet(int handle_id)
 {
-    int prev_track, hid;
-    char codec_path[MAX_PATH]; /* Full path to codec */
-    const struct mp3entry *id3, *prev_id3;
+    struct cuesheet *cue = get_current_cuesheet();
 
-    if (tracks[track_widx].id3_hid < 0) {
-        return false;
-    }
+    if (!cue || handle_id < 0)
+        return;
 
-    id3 = bufgetid3(tracks[track_widx].id3_hid);
-    if (!id3)
-        return false;
+    bufread(handle_id, sizeof (struct cuesheet), cue);
+}
 
-    const char *codec_fn = get_codec_filename(id3->codectype);
-    if (codec_fn == NULL)
+/* Backend to peek/current/next track metadata interface functions -
+   fill in the mp3entry with as much information as we may obtain about
+   the track at the specified offset from the user current track -
+   returns false if no information exists with us */
+static bool audio_get_track_metadata(int offset, struct mp3entry *id3)
+{
+    if (play_status == PLAY_STOPPED)
         return false;
 
-    tracks[track_widx].codec_hid = -1;
+    if (id3->path[0] != '\0')
+        return true; /* Already filled */
 
-    if (start_play)
+    struct track_info *info = track_list_user_current(offset);
+
+    if (!info)
     {
-        /* Load the codec directly from disk and save some memory. */
-        track_ridx = track_widx;
-        ci.filesize = CUR_TI->filesize;
-        ci.id3 = thistrack_id3;
-        ci.taginfo_ready = &CUR_TI->taginfo_ready;
-        ci.curpos = 0;
-        return codec_load(-1, id3->codectype);
+        struct mp3entry *ub_id3 = id3_get(UNBUFFERED_ID3);
+
+        if (offset > 0 && track_list_user_current(offset - 1))
+        {
+            /* Try the unbuffered id3 since we're moving forward */
+            if (ub_id3->path[0] != '\0')
+            {
+                copy_mp3entry(id3, ub_id3);
+                return true;
+            }
+        }
     }
-    else
+    else if (bufreadid3(info->id3_hid, id3))
     {
-        /* If we already have another track than this one buffered */
-        if (track_widx != track_ridx)
-        {
-            prev_track = (track_widx - 1) & MAX_TRACK_MASK;
+        return true;
+    }
 
-            id3 = bufgetid3(tracks[track_widx].id3_hid);
-            prev_id3 = bufgetid3(tracks[prev_track].id3_hid);
+    /* We didn't find the ID3 metadata, so we fill it with the little info we
+       have and return that */
 
-            /* If the previous codec is the same as this one and the current
-             * one is the correct one, there is no need to put another copy of
-             * it on the file buffer */
-            if (id3 && prev_id3)
-            {
-                int codt = get_codec_base_type(id3->codectype);
-                int prev_codt = get_codec_base_type(prev_id3->codectype);
-                int cod_loaded = get_codec_base_type(codec_loaded());
+    char path[MAX_PATH+1];
+    if (playlist_peek(offset, path, sizeof (path)))
+    {
+#if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
+        /* Try to get it from the database */
+        if (!tagcache_fill_tags(id3, path))
+#endif
+        {
+            /* By now, filename is the only source of info */
+            fill_metadata_from_path(id3, path);
+        }
 
-                if (codt == prev_codt && codt == cod_loaded)
-                {
-                    logf("Reusing prev. codec");
-                    return true;
-                }
-            }
-        }
+        return true;
     }
 
-    codec_get_full_path(codec_path, codec_fn);
+    wipe_mp3entry(id3);
 
-    hid = tracks[track_widx].codec_hid = bufopen(codec_path, 0, TYPE_CODEC, NULL);
+    return false;
+}
 
-    /* not an error if codec load it supported, will load it from disk
-     * application builds don't support it
-     */
-    if (hid < 0 && hid != ERR_UNSUPPORTED_TYPE)
-        return false;
+/* Get a resume rewind adjusted offset from the ID3 */
+unsigned long resume_rewind_adjusted_offset(const struct mp3entry *id3)
+{
+    unsigned long offset = id3->offset;
+    size_t resume_rewind = global_settings.resume_rewind *
+                           id3->bitrate * (1000/8);
 
-    if (hid >= 0)
-        logf("Loaded codec");
+    if (offset < resume_rewind)
+        offset = 0;
     else
-        logf("Buffering codec unsupported, load later from disk");
+        offset -= resume_rewind;
 
-    return true;
+    return offset;
 }
 
-/* Load metadata for the next track (with bufopen). The rest of the track
-   loading will be handled by audio_finish_load_track once the metadata has been
-   actually loaded by the buffering thread. */
-static bool audio_load_track(size_t offset, bool start_play)
+/* Get the codec into ram and initialize it - keep it if it's ready */
+static bool audio_init_codec(struct track_info *track_info,
+                             struct mp3entry *track_id3)
 {
-    char name_buf[MAX_PATH + 1];
-    const char *trackname;
-    int fd = -1;
+    int codt_loaded = get_audio_base_codec_type(codec_loaded());
+    int hid = ERR_HANDLE_NOT_FOUND;
 
-    if (track_load_started) {
-        /* There is already a track load in progress, so track_widx hasn't been
-           incremented yet. Loading another track would overwrite the one that
-           hasn't finished loading. */
-        logf("audio_load_track(): a track load is already in progress");
-        return false;
+    if (codt_loaded != AFMT_UNKNOWN)
+    {
+        int codt = get_audio_base_codec_type(track_id3->codectype);
+
+        if (codt == codt_loaded)
+        {
+            /* Codec is the same base type */
+            logf("Reusing prev. codec: %d", track_id3->codectype);
+#ifdef HAVE_CODEC_BUFFERING
+            /* Close any buffered codec (we could have skipped directly to a
+               format transistion that is the same format as the current track
+               and the buffered one is no longer needed) */
+            track_info_close_handle(&track_info->codec_hid);
+#endif
+            return true;
+        }
+        else
+        {
+            /* New codec - first make sure the old one's gone */
+            logf("Removing prev. codec: %d", codt_loaded);
+            codec_unload();
+        }
     }
 
-    start_play_g = start_play;  /* will be read by audio_finish_load_track */
+    logf("New codec: %d/%d", track_id3->codectype, codec_loaded());
 
-    /* Stop buffer filling if there is no free track entries.
-       Don't fill up the last track entry (we wan't to store next track
-       metadata there). */
-    if (!audio_free_track_count())
-    {
-        logf("No free tracks");
+#ifdef HAVE_CODEC_BUFFERING
+    /* Codec thread will close the handle even if it fails and will load from
+       storage if hid is not valid or the buffer load fails */
+    hid = track_info->codec_hid;
+    track_info->codec_hid = ERR_HANDLE_NOT_FOUND;
+#endif
+
+    return codec_load(hid, track_id3->codectype);
+}
+
+/* Start the codec for the current track scheduled to be decoded */
+static bool audio_start_codec(void)
+{
+    struct track_info *info = track_list_current(0);
+    struct mp3entry *cur_id3 = valid_mp3entry(bufgetid3(info->id3_hid));
+
+    if (!cur_id3)
         return false;
-    }
 
-    last_peek_offset++;
-    tracks[track_widx].taginfo_ready = false;
+    buf_pin_handle(info->id3_hid, true);
 
-    logf("Buffering track: r%d/w%d", track_ridx, track_widx);
-    /* Get track name from current playlist read position. */
-    while ((trackname = playlist_peek(last_peek_offset, name_buf,
-        sizeof(name_buf))) != NULL)
+    if (!audio_init_codec(info, cur_id3))
     {
-        /* Handle broken playlists. */
-        fd = open(trackname, O_RDONLY);
-        if (fd < 0)
-        {
-            logf("Open failed");
-            /* Skip invalid entry from playlist. */
-            playlist_skip_entry(NULL, last_peek_offset);
-        }
-        else
-            break;
+        buf_pin_handle(info->id3_hid, false);
+        return false;
     }
 
-    if (!trackname)
+#ifdef HAVE_TAGCACHE
+    bool autoresume_enable = global_settings.autoresume_enable;
+    bool autoresume_automatic = global_settings.autoresume_automatic;
+
+    if (autoresume_enable && !cur_id3->offset)
     {
-        logf("End-of-playlist");
-        memset(&unbuffered_id3, 0, sizeof(struct mp3entry));
-        filling = STATE_END_OF_PLAYLIST;
+        bool resume;
 
-        if (thistrack_id3->length == 0 && thistrack_id3->filesize == 0)
-        {
-            /* Stop playback if no valid track was found. */
-            audio_stop_playback();
-        }
+        /* Send the "buffer" event to obtain the resume position for the codec */
+        send_event(PLAYBACK_EVENT_TRACK_BUFFER, cur_id3);
 
-        return false;
+        /* Ignore resume position for automatic track change if so configured */
+        resume = (!automatic_skip /* Resume all manually selected tracks */
+                  || autoresume_automatic == AUTORESUME_NEXTTRACK_ALWAYS
+                  || (autoresume_automatic != AUTORESUME_NEXTTRACK_NEVER
+                                                      /* Not never resume? */
+                       && autoresumable(cur_id3))); /* Pass Resume filter? */
+
+        if (!resume)
+            cur_id3->offset = 0;
+
+        logf("%s: Set offset for %s to %lX\n", __func__,
+             cur_id3->title, cur_id3->offset);
     }
+#endif /* HAVE_TAGCACHE */
 
-    tracks[track_widx].filesize = filesize(fd);
+    /* Rewind the required amount - if an autoresume was done, this also rewinds
+       that by the setting's amount
 
-    if (offset > tracks[track_widx].filesize)
-        offset = 0;
+       It would be best to have bookkeeping about whether or not the track
+       sounded or not since skipping to it or else skipping to it while paused
+       and back again will cause accumulation of silent rewinds - that's not
+       our job to track directly nor could it be in any reasonable way
+     */
+    cur_id3->offset = resume_rewind_adjusted_offset(cur_id3);
 
-    /* Set default values */
-    if (start_play)
+    /* Update the codec API with the metadata and track info */
+    id3_write(CODEC_ID3, cur_id3);
+
+    ci.audio_hid = info->audio_hid;
+    ci.filesize = info->filesize;
+    buf_set_base_handle(info->audio_hid);
+
+    /* All required data is now available for the codec */
+    codec_go();
+
+#ifdef HAVE_TAGCACHE
+    if (!autoresume_enable || cur_id3->offset)
+#endif
     {
-        buf_set_watermark(filebuflen/2);
-        dsp_configure(ci.dsp, DSP_RESET, 0);
-        playlist_update_resume_info(audio_current_track());
+        /* Send the "buffer" event now */
+        send_event(PLAYBACK_EVENT_TRACK_BUFFER, cur_id3);
     }
 
-    /* Get track metadata if we don't already have it. */
-    if (tracks[track_widx].id3_hid < 0)
+    /* Be sure all tagtree info is syncronized; it will be needed for the
+       track finish event - the sync will happen when finalizing a track
+       change otherwise */
+    if (info == track_list_user_current(0))
+        id3_write_locked(PLAYING_ID3, cur_id3);
+
+    /* So autoresume works again later on the same buffered track and so that
+       skipping back to the same without autoresume starts at the beginning */
+    cur_id3->offset = 0;
+
+    buf_pin_handle(info->id3_hid, false);
+    return true;
+}
+
+
+/** --- Audio thread --- **/
+
+/* Load and parse a cuesheet for the file - returns false if the buffer
+   is full */
+static bool audio_load_cuesheet(struct track_info *info,
+                                struct mp3entry *track_id3)
+{
+    struct cuesheet *cue = get_current_cuesheet();
+    track_id3->cuesheet = NULL;
+
+    if (cue && info->cuesheet_hid == ERR_HANDLE_NOT_FOUND)
     {
-        tracks[track_widx].id3_hid = bufopen(trackname, 0, TYPE_ID3, NULL);
+        /* If error other than a full buffer, then mark it "unsupported" to
+           avoid reloading attempt */
+        int hid = ERR_UNSUPPORTED_TYPE;
+        char cuepath[MAX_PATH];
 
-        if (tracks[track_widx].id3_hid < 0)
+#ifdef HAVE_IO_PRIORITY
+        buf_back_off_storage(true);
+#endif
+        if (look_for_cuesheet_file(track_id3->path, cuepath))
         {
-            /* Buffer is full. */
-            get_metadata(&unbuffered_id3, fd, trackname);
-            last_peek_offset--;
-            close(fd);
-            logf("buffer is full for now (get metadata)");
-            filling = STATE_FULL;
-            return false;
-        }
+            hid = bufalloc(NULL, sizeof (struct cuesheet), TYPE_CUESHEET);
 
-        if (track_widx == track_ridx)
-        {
-            /* TODO: Superfluos buffering call? */
-            buf_request_buffer_handle(tracks[track_widx].id3_hid);
-            if (bufreadid3(tracks[track_widx].id3_hid, thistrack_id3))
-            {    
-                thistrack_id3->offset = offset;
-                logf("audio_load_track: set offset for %s to %lX\n",
-                     thistrack_id3->title,
-                     offset);
+            if (hid >= 0)
+            {
+                void *cuesheet = NULL;
+                bufgetdata(hid, sizeof (struct cuesheet), &cuesheet);
+
+                if (parse_cuesheet(cuepath, (struct cuesheet *)cuesheet))
+                {
+                    /* Indicate cuesheet is present (while track remains
+                       buffered) */
+                    track_id3->cuesheet = cue;
+                }
+                else
+                {
+                    bufclose(hid);
+                    hid = ERR_UNSUPPORTED_TYPE;
+                }
             }
-            else
-                memset(thistrack_id3, 0, sizeof(struct mp3entry));
         }
 
-        if (start_play)
+#ifdef HAVE_IO_PRIORITY
+        buf_back_off_storage(false);
+#endif
+        if (hid == ERR_BUFFER_FULL)
         {
-            playlist_update_resume_info(audio_current_track());
+            logf("buffer is full for now (%s)", __func__);
+            return false;
         }
+        else
+        {
+            if (hid < 0)
+                logf("Cuesheet loading failed");
+
+            info->cuesheet_hid = hid;
+        }
     }
 
-    close(fd);
-    track_load_started = true; /* Remember that we've started loading a track */
     return true;
 }
 
 #ifdef HAVE_ALBUMART
-/* Load any album art for the file */
-static void audio_load_albumart(struct mp3entry *track_id3)
+/* Load any album art for the file - returns false if the buffer is full */
+static bool audio_load_albumart(struct track_info *info,
+                                struct mp3entry *track_id3)
 {
     int i;
-
     FOREACH_ALBUMART(i)
     {
         struct bufopen_bitmap_data user_data;
-        int hid = ERR_HANDLE_NOT_FOUND;
+        int *aa_hid = &info->aa_hid[i];
+        int hid = ERR_UNSUPPORTED_TYPE;
 
         /* albumart_slots may change during a yield of bufopen,
          * but that's no problem */
-        if (tracks[track_widx].aa_hid[i] >= 0 || !albumart_slots[i].used)
+        if (*aa_hid >= 0 || *aa_hid == ERR_UNSUPPORTED_TYPE ||
+            !albumart_slots[i].used)
             continue;
 
         memset(&user_data, 0, sizeof(user_data));
-        user_data.dim = &(albumart_slots[i].dim);
+        user_data.dim = &albumart_slots[i].dim;
 
-        /* we can only decode jpeg for embedded AA */
+#ifdef HAVE_IO_PRIORITY
+        buf_back_off_storage(true);
+#endif
+
+        /* We can only decode jpeg for embedded AA */
         if (track_id3->embed_albumart && track_id3->albumart.type == AA_TYPE_JPG)
         {
-            user_data.embedded_albumart = &(track_id3->albumart);
+            user_data.embedded_albumart = &track_id3->albumart;
             hid = bufopen(track_id3->path, 0, TYPE_BITMAP, &user_data);
         }
 
         if (hid < 0 && hid != ERR_BUFFER_FULL)
         {
-            /* no embedded AA or it couldn't be loaded, try other sources */
+            /* No embedded AA or it couldn't be loaded - try other sources */
             char path[MAX_PATH];
 
             if (find_albumart(track_id3, path, sizeof(path),
-                &(albumart_slots[i].dim)))
+                              &albumart_slots[i].dim))
             {
                 user_data.embedded_albumart = NULL;
                 hid = bufopen(path, 0, TYPE_BITMAP, &user_data);
             }
         }
 
+#ifdef HAVE_IO_PRIORITY
+        buf_back_off_storage(false);
+#endif
         if (hid == ERR_BUFFER_FULL)
         {
-            filling = STATE_FULL;
-            logf("buffer is full for now (get album art)");
+            logf("buffer is full for now (%s)", __func__);
+            return false;
         }
-        else if (hid < 0)
+        else
         {
-            logf("Album art loading failed");
+            /* If error other than a full buffer, then mark it "unsupported"
+               to avoid reloading attempt */
+            if (hid < 0)
+            {
+                logf("Album art loading failed");
+                hid = ERR_UNSUPPORTED_TYPE;
+            }
+
+            *aa_hid = hid;
         }
+    }
 
-        tracks[track_widx].aa_hid[i] = hid;
-    }
+    return true;
 }
-#endif
+#endif /* HAVE_ALBUMART */
 
-/* Second part of the track loading: We now have the metadata available, so we
-   can load the codec, the album art and finally the audio data.
-   This is called on the audio thread after the buffering thread calls the
-   buffering_handle_finished_callback callback. */
-static void audio_finish_load_track(void)
+#ifdef HAVE_CODEC_BUFFERING
+/* Load a codec for the file onto the buffer - assumed we're working from the
+   currently loading track - not called for the current track */
+static bool audio_buffer_codec(struct track_info *track_info,                             
+                               struct mp3entry *track_id3)
 {
-    size_t file_offset = 0;
-    size_t offset = 0;
-    bool start_play = start_play_g;
+    /* This will not be the current track -> it cannot be the first and the
+       current track cannot be ahead of buffering -> there is a previous
+       track entry which is either current or ahead of the current */
+    struct track_info *prev_info = track_list_last(-1);
+    struct mp3entry *prev_id3 = bufgetid3(prev_info->id3_hid);
 
-    track_load_started = false;
+    /* If the previous codec is the same as this one, there is no need to
+       put another copy of it on the file buffer (in other words, only
+       buffer codecs at format transitions) */
+    if (prev_id3)
+    {
+        int codt = get_audio_base_codec_type(track_id3->codectype);
+        int prev_codt = get_audio_base_codec_type(prev_id3->codectype);
 
-    if (tracks[track_widx].id3_hid < 0) {
-        logf("No metadata");
-        return;
+        if (codt == prev_codt)
+        {
+            logf("Reusing prev. codec: %d", prev_id3->codectype);
+            return true;
+        }
     }
+    /* else just load it (harmless) */
 
-    struct mp3entry *track_id3;
+    /* Load the codec onto the buffer if possible */
+    const char *codec_fn = get_codec_filename(track_id3->codectype);
+    if (!codec_fn)
+        return false;
 
-    if (track_widx == track_ridx)
-        track_id3 = thistrack_id3;
-    else
-        track_id3 = bufgetid3(tracks[track_widx].id3_hid);
+    char codec_path[MAX_PATH+1]; /* Full path to codec */
+    codec_get_full_path(codec_path, codec_fn);
 
-    if (track_id3->length == 0 && track_id3->filesize == 0)
+    track_info->codec_hid = bufopen(codec_path, 0, TYPE_CODEC, NULL);
+
+    if (track_info->codec_hid >= 0)
     {
-        logf("audio_finish_load_track: invalid metadata");
+        logf("Buffered codec: %d", afmt);
+        return true;
+    }
 
-        /* Invalid metadata */
-        bufclose(tracks[track_widx].id3_hid);
-        tracks[track_widx].id3_hid = -1;
+    return false;
+}
+#endif /* HAVE_CODEC_BUFFERING */
 
-        /* Skip invalid entry from playlist. */
-        playlist_skip_entry(NULL, last_peek_offset--);
+/* Load metadata for the next track (with bufopen). The rest of the track
+   loading will be handled by audio_finish_load_track once the metadata has
+   been actually loaded by the buffering thread.
 
-        /* load next track */
-        LOGFQUEUE("audio > audio Q_AUDIO_FILL_BUFFER %d", (int)start_play);
-        queue_post(&audio_queue, Q_AUDIO_FILL_BUFFER, start_play);
+   Each track is arranged in the buffer as follows:
+        <id3|[cuesheet|][album art|][codec|]audio>
 
-        return;
-    }
-    /* Try to load a cuesheet for the track */
-    if (curr_cue)
+   The next will not be loaded until the previous succeeds if the buffer was
+   full at the time. To put any metadata after audio would make those handles
+   unmovable.
+*/
+static enum track_load_status audio_load_track(void)
+{
+    if (in_progress_id3_hid >= 0)
     {
-        char cuepath[MAX_PATH];
-        if (look_for_cuesheet_file(track_id3->path, cuepath))
+        /* There must be an info pointer if the in-progress id3 is even there */
+        struct track_info *info = track_list_last(0);
+
+        if (info->id3_hid == in_progress_id3_hid)
         {
-            void *temp;
-            tracks[track_widx].cuesheet_hid = 
-                        bufalloc(NULL, sizeof(struct cuesheet), TYPE_CUESHEET);
-            if (tracks[track_widx].cuesheet_hid >= 0)
+            if (filling == STATE_FILLING)
             {
-                bufgetdata(tracks[track_widx].cuesheet_hid,
-                           sizeof(struct cuesheet), &temp);
-                struct cuesheet *cuesheet = (struct cuesheet*)temp;
-                if (!parse_cuesheet(cuepath, cuesheet))
-                {
-                    bufclose(tracks[track_widx].cuesheet_hid);
-                    track_id3->cuesheet = NULL;
-                }
+                /* Haven't finished the metadata but the notification is
+                   anticipated to come soon */
+                logf("%s(): in progress ok: %d". __func__, info->id3_hid);
+                return LOAD_TRACK_OK;
             }
+            else if (filling == STATE_FULL)
+            {
+                /* Buffer was full trying to complete the load after the
+                   metadata finished, so attempt to continue - older handles
+                   should have been cleared already */
+                logf("%s(): finishing load: %d". __func__, info->id3_hid);
+                filling = STATE_FILLING;
+                buffer_event_finished_callback(&info->id3_hid);
+                return LOAD_TRACK_OK;
+            }
         }
+
+        /* Some old, stray buffering message */
+        logf("%s(): already in progress: %d". __func__, info->id3_hid);
+        return LOAD_TRACK_ERR_BUSY;
     }
 
-#ifdef HAVE_ALBUMART
-    audio_load_albumart(track_id3);
-#endif
+    filling = STATE_FILLING;
 
-    /* Load the codec. */
-    if (!audio_loadcodec(start_play))
+    struct track_info *info = track_list_alloc_track();
+    if (info == NULL)
     {
-        if (tracks[track_widx].codec_hid == ERR_BUFFER_FULL)
+        /* List is full so stop buffering tracks - however, attempt to obtain
+           metadata as the unbuffered id3 */
+        logf("No free tracks");
+        filling = STATE_FULL;
+    }
+
+    playlist_peek_offset++;
+
+    logf("Buffering track: s%u/c%u/e%u/p%d",
+         track_list.start, track_list.current, track_list.end,
+         playlist_peek_offset);
+
+    /* Get track name from current playlist read position */
+    int fd = -1;
+    char name_buf[MAX_PATH + 1];
+    const char *trackname;
+
+    while (1)
+    {
+
+        trackname = playlist_peek(playlist_peek_offset, name_buf,
+                                  sizeof (name_buf));
+
+        if (!trackname)
+            break;
+
+        /* Test for broken playlists by probing for the files */
+        fd = open(trackname, O_RDONLY);
+        if (fd >= 0)
+            break;
+
+        logf("Open failed");
+        /* Skip invalid entry from playlist */
+        playlist_skip_entry(NULL, playlist_peek_offset);
+
+        /* Sync the playlist if it isn't finished */
+        if (playlist_peek(playlist_peek_offset, NULL, 0))
+            playlist_next(0);
+    }
+
+    if (!trackname)
+    {
+        /* No track - exhausted the playlist entries */
+        logf("End-of-playlist");
+        id3_write_locked(UNBUFFERED_ID3, NULL);
+
+        if (filling != STATE_FULL)
+            track_list_unalloc_track(); /* Free this entry */
+
+        playlist_peek_offset--;         /* Maintain at last index */
+
+        /* We can end up here after the real last track signals its completion
+           and miss the transition to STATE_FINISHED esp. if dropping the last
+           songs of a playlist late in their load (2nd stage) */
+        info = track_list_last(0);
+
+        if (info && buf_handle_remaining(info->audio_hid) == 0)
+            filling_is_finished();
+        else
+            filling = STATE_END_OF_PLAYLIST;
+
+        return LOAD_TRACK_ERR_NO_MORE;
+    }
+
+    /* Successfully opened the file - get track metadata */
+    if (filling == STATE_FULL ||
+        (info->id3_hid = bufopen(trackname, 0, TYPE_ID3, NULL)) < 0)
+    {
+        /* Buffer or track list is full */
+        struct mp3entry *ub_id3;
+
+        playlist_peek_offset--;
+
+        /* Load the metadata for the first unbuffered track */
+        ub_id3 = id3_get(UNBUFFERED_ID3);
+        id3_mutex_lock();
+        get_metadata(ub_id3, fd, trackname);
+        id3_mutex_unlock();
+
+        if (filling != STATE_FULL)
         {
-            /* No space for codec on buffer, not an error */
+            track_list_unalloc_track();
             filling = STATE_FULL;
-            return;
         }
 
-        /* This is an error condition, either no codec was found, or reading
-         * the codec file failed part way through, either way, skip the track */
-        /* FIXME: We should not use splashf from audio thread! */
-        splashf(HZ*2, "No codec for: %s", track_id3->path);
-        /* Skip invalid entry from playlist. */
-        playlist_skip_entry(NULL, last_peek_offset);
-        return;
+        logf("%s: buffer is full for now (%u tracks)", __func__,
+             track_list_count());
     }
+    else
+    {
+        /* Successful load initiation */
+        info->filesize = filesize(fd);
+        in_progress_id3_hid = info->id3_hid; /* Remember what's in-progress */
+    }
 
-    track_id3->elapsed = 0;
-    offset = track_id3->offset;
-    size_t resume_rewind = (global_settings.resume_rewind *
-                            track_id3->bitrate * 1000) / 8;
+    close(fd);
+    return LOAD_TRACK_OK;
+}
 
-    if (offset < resume_rewind)
+/* Second part of the track loading: We now have the metadata available, so we
+   can load the codec, the album art and finally the audio data.
+   This is called on the audio thread after the buffering thread calls the
+   buffering_handle_finished_callback callback. */
+static enum track_load_status audio_finish_load_track(struct track_info *info)
+{
+    enum track_load_status trackstat = LOAD_TRACK_OK;
+
+    if (info->id3_hid != in_progress_id3_hid)
     {
-        offset = 0;
+        /* We must not be here if not! */
+        logf("%s: wrong track %d/%d", __func__, info->id3_hid,
+             in_progress_id3_hid);
+        return LOAD_TRACK_ERR_BUSY;
     }
-    else
+
+    /* The current track for decoding (there is always one if the list is
+       populated) */
+    struct track_info *cur_info = track_list_current(0);
+    struct mp3entry *track_id3 = valid_mp3entry(bufgetid3(info->id3_hid));
+
+    if (!track_id3)
     {
-        offset -= resume_rewind;
+        /* This is an error condition. Track cannot be played without valid
+           metadata; skip the track. */
+        logf("No metadata for: %s", track_id3->path);
+        trackstat = LOAD_TRACK_ERR_FINISH_FAILED;
+        goto audio_finish_load_track_exit;
     }
 
-    enum data_type type = TYPE_PACKET_AUDIO;
+    /* Try to load a cuesheet for the track */
+    if (!audio_load_cuesheet(info, track_id3))
+    {
+        /* No space for cuesheet on buffer, not an error */
+        filling = STATE_FULL;
+        goto audio_finish_load_track_exit;
+    }
 
-    switch (track_id3->codectype) {
-    case AFMT_MPA_L1:
-    case AFMT_MPA_L2:
-    case AFMT_MPA_L3:
-        if (offset > 0) {
-            file_offset = offset;
-        }
-        break;
+#ifdef HAVE_ALBUMART
+    /* Try to load album art for the track */
+    if (!audio_load_albumart(info, track_id3))
+    {
+        /* No space for album art on buffer, not an error */
+        filling = STATE_FULL;
+        goto audio_finish_load_track_exit;
+    }
+#endif
 
-    case AFMT_WAVPACK:
-        if (offset > 0) {
-            file_offset = offset;
-            track_id3->elapsed = track_id3->length / 2;
+#ifdef HAVE_CODEC_BUFFERING
+    /* Try to buffer a codec for the track */
+    if (info != cur_info && !audio_buffer_codec(info, track_id3))
+    {
+        if (info->codec_hid == ERR_BUFFER_FULL)
+        {
+            /* No space for codec on buffer, not an error */
+            filling = STATE_FULL;
+            logf("buffer is full for now (%s)", __func__);
         }
-        break;
+        else
+        {
+            /* This is an error condition, either no codec was found, or
+               reading the codec file failed part way through, either way,
+               skip the track */
+            logf("No codec for: %s", track_id3->path);
+            trackstat = LOAD_TRACK_ERR_FINISH_FAILED;
+        }
 
-    case AFMT_NSF:
-    case AFMT_SPC:
-    case AFMT_SID:
-        logf("Loading atomic %d",track_id3->codectype);
-        type = TYPE_ATOMIC_AUDIO;
-        break;
-    
-    default:
-        /* no special treatment needed */
-        break;
+        goto audio_finish_load_track_exit;
     }
+#endif /* HAVE_CODEC_BUFFERING */
 
-    track_id3->offset = offset;
+    /** Finally, load the audio **/
+    size_t file_offset = 0;
+    track_id3->elapsed = 0;
 
+    if (track_id3->offset >= info->filesize)
+        track_id3->offset = 0;
+
+    logf("%s: set offset for %s to %lu\n", __func__,
+         id3->title, (unsigned long)offset);
+
+    /* Adjust for resume rewind so we know what to buffer - starting the codec
+       calls it again, so we don't save it (and they shouldn't accumulate) */
+    size_t offset = resume_rewind_adjusted_offset(track_id3);
+
+    enum data_type audiotype = get_audio_base_data_type(track_id3->codectype);
+
+    if (audiotype == TYPE_ATOMIC_AUDIO)
+        logf("Loading atomic %d", track_id3->codectype);
+
+    if (format_buffers_with_offset(track_id3->codectype))
+    {
+        /* This format can begin buffering from any point */
+        file_offset = offset;
+    }
+
     logf("load track: %s", track_id3->path);
 
     if (file_offset > AUDIO_REBUFFER_GUESS_SIZE)
+    {
+        /* We can buffer later in the file, adjust the hunt-and-peck margin */
         file_offset -= AUDIO_REBUFFER_GUESS_SIZE;
-    else if (track_id3->first_frame_offset)
+    }
+    else
+    {
+        /* No offset given or it is very minimal - begin at the first frame
+           according to the metadata */
         file_offset = track_id3->first_frame_offset;
-    else
-        file_offset = 0;
+    }
 
-    tracks[track_widx].audio_hid = bufopen(track_id3->path, file_offset, type,
-                                            NULL);
+    int hid = bufopen(track_id3->path, file_offset, audiotype, NULL);
 
-    /* No space left, not an error */
-    if (tracks[track_widx].audio_hid == ERR_BUFFER_FULL)
+    if (hid >= 0)
     {
-        filling = STATE_FULL;
-        logf("buffer is full for now (load audio)");
-        return;
+        info->audio_hid = hid;
+
+        if (info == cur_info)
+        {
+            /* This is the current track to decode - should be started now */
+            trackstat = LOAD_TRACK_READY;
+        }
     }
-    else if (tracks[track_widx].audio_hid < 0)
+    else
     {
-        /* another error, do not continue either */
-        logf("Could not add audio data handle");
-        return;
+        /* Buffer could be full but not properly so if this is the only
+           track! */
+        if (hid == ERR_BUFFER_FULL && audio_track_count() > 1)
+        {
+            filling = STATE_FULL;
+            logf("Buffer is full for now (%s)", __func__);
+        }
+        else
+        {
+            /* Nothing to play if no audio handle - skip this */
+            logf("Could not add audio data handle");
+            trackstat = LOAD_TRACK_ERR_FINISH_FAILED;
+        }
     }
 
-    /* All required data is now available for the codec -- unless the
-       autoresume feature is in effect.  In the latter case, the codec
-       must wait until after PLAYBACK_EVENT_TRACK_BUFFER, which may
-       generate a resume position.  */
-#ifdef HAVE_TAGCACHE
-    if (!global_settings.autoresume_enable || offset)
-#endif
-        tracks[track_widx].taginfo_ready = true;
-
-    if (start_play)
+audio_finish_load_track_exit:
+    if (trackstat < LOAD_TRACK_OK)
     {
-        ci.curpos=file_offset;
-        buf_request_buffer_handle(tracks[track_widx].audio_hid);
-    }
+        playlist_skip_entry(NULL, playlist_peek_offset);
+        track_info_close(info);
+        track_list_unalloc_track();
 
-    send_event(PLAYBACK_EVENT_TRACK_BUFFER, track_id3);
+        if (playlist_peek(playlist_peek_offset, NULL, 0))
+            playlist_next(0);
 
-#ifdef HAVE_TAGCACHE
-    /* In case the autoresume feature has been enabled, finally all
-       required data is available for the codec. */
-    if (global_settings.autoresume_enable && !offset)
-        tracks[track_widx].taginfo_ready = true;
-#endif
+        playlist_peek_offset--;
+    }
 
-    track_widx = (track_widx + 1) & MAX_TRACK_MASK;
+    if (filling != STATE_FULL)
+    {
+        /* Load next track - error or not */
+        in_progress_id3_hid = ERR_HANDLE_NOT_FOUND;
+        LOGFQUEUE("audio > audio Q_AUDIO_FILL_BUFFER");
+        audio_queue_post(Q_AUDIO_FILL_BUFFER, 0);
+    }
+    else
+    {
+        /* Full */
+        trackstat = LOAD_TRACK_ERR_FINISH_FULL;
+    }
 
-    /* load next track */
-    LOGFQUEUE("audio > audio Q_AUDIO_FILL_BUFFER");
-    queue_post(&audio_queue, Q_AUDIO_FILL_BUFFER, 0);
-
-    return;
+    return trackstat;
 }
 
-static void audio_fill_file_buffer(bool start_play, size_t offset)
+/* Start a new track load */
+static enum track_load_status audio_fill_file_buffer(void)
 {
+    if (play_status == PLAY_STOPPED)
+        return LOAD_TRACK_ERR_FAILED;
+
     trigger_cpu_boost();
 
-    /* No need to rebuffer if there are track skips pending,
-     * however don't cancel buffering on skipping while filling. */
-    if (ci.new_track != 0 && filling != STATE_FILLING)
-        return;
-    filling = STATE_FILLING;
-
     /* Must reset the buffer before use if trashed or voice only - voice
        file size shouldn't have changed so we can go straight from
        AUDIOBUF_STATE_VOICED_ONLY to AUDIOBUF_STATE_INITIALIZED */
@@ -1511,772 +1800,1839 @@
 
     logf("Starting buffer fill");
 
-    if (!start_play)
-        audio_clear_track_entries();
+    enum track_load_status trackstat = audio_load_track();
 
-    /* Save the current resume position once. */
-    playlist_update_resume_info(audio_current_track());
+    if (trackstat >= LOAD_TRACK_OK)
+    {
+        if (track_list_current(0) == track_list_user_current(0))
+            playlist_next(0);
 
-    audio_load_track(offset, start_play);
+        if (filling == STATE_FULL && !track_list_user_current(1))
+        {
+            /* There are no user tracks on the buffer after this therefore
+               this is the next track */
+            audio_update_and_announce_next_track(id3_get(UNBUFFERED_ID3));
+        }
+    }
+
+    return trackstat;
 }
 
-static void audio_rebuffer(void)
+/* Discard unwanted tracks and start refill from after the specified playlist
+   offset */
+static enum track_load_status audio_reset_and_rebuffer(
+    enum track_clear_action action, int peek_offset)
 {
-    logf("Forcing rebuffer");
+    logf("Forcing rebuffer: 0x%X, %d", flags, peek_offset);
 
-    clear_track_info(CUR_TI);
+    id3_write_locked(UNBUFFERED_ID3, NULL);
 
-    /* Reset track pointers */
-    track_widx = track_ridx;
-    audio_clear_track_entries();
+    /* Remove unwanted tracks - caller must have ensured codec isn't using
+       any */
+    track_list_clear(action);
 
-    /* Reset a possibly interrupted track load */
-    track_load_started = false;
+    /* Refill at specified position (-1 starts at index offset 0) */
+    playlist_peek_offset = peek_offset;
 
     /* Fill the buffer */
-    last_peek_offset = -1;
-    ci.curpos = 0;
+    return audio_fill_file_buffer();
+}
 
-    if (!CUR_TI->taginfo_ready)
-        memset(thistrack_id3, 0, sizeof(struct mp3entry));
+/* Handle buffering events
+   (Q_AUDIO_BUFFERING) */
+static void audio_on_buffering(int event)
+{
+    enum track_clear_action action;
+    int peek_offset;
 
-    audio_fill_file_buffer(false, 0);
+    if (track_list_empty())
+        return;
+    
+    switch (event)
+    {
+    case BUFFER_EVENT_BUFFER_LOW:
+        if (filling != STATE_FULL && filling != STATE_END_OF_PLAYLIST)
+            return; /* Should be nothing left to fill */
+
+        /* Clear old tracks and continue buffering where it left off */
+        action = TRACK_LIST_KEEP_NEW;
+        peek_offset = playlist_peek_offset;
+        break;
+
+    case BUFFER_EVENT_REBUFFER:
+        /* Remove all but the currently decoding track and redo buffering
+           after that */
+        action = TRACK_LIST_KEEP_CURRENT;
+        peek_offset = (skip_pending == TRACK_SKIP_AUTO) ? 1 : 0;
+        break;
+
+    default:
+        return;
+    }
+
+    switch (skip_pending)
+    {
+    case TRACK_SKIP_NONE:
+    case TRACK_SKIP_AUTO:
+    case TRACK_SKIP_AUTO_NEW_PLAYLIST:
+        audio_reset_and_rebuffer(action, peek_offset);
+        break;
+
+    case TRACK_SKIP_AUTO_END_PLAYLIST:
+        /* Already finished */
+        break;
+
+    default:
+        /* Invalid */
+        logf("Buffering call, inv. state: %d", (int)skip_pending);
+    }
 }
 
-/* Called on request from the codec to get a new track. This is the codec part
-   of the track transition. */
-static void audio_last_track(bool automatic)
+/* Handle starting the next track load
+   (Q_AUDIO_FILL_BUFFER) */
+static void audio_on_fill_buffer(void)
 {
-    if (automatic)
+    audio_handle_track_load_status(audio_fill_file_buffer());
+}
+
+/* Handle posted load track finish event
+   (Q_AUDIO_FINISH_LOAD_TRACK) */
+static void audio_on_finish_load_track(int id3_hid)
+{
+    struct track_info *info = track_list_last(0);
+
+    if (!info || !buf_is_handle(id3_hid))
+        return;
+
+    if (info == track_list_user_current(1))
     {
-        ci.new_track = 0;
-        automatic_skip = false;
+        /* Just loaded the metadata right after the current position */
+        audio_update_and_announce_next_track(bufgetid3(info->id3_hid));
+    }
 
-        if (filling != STATE_ENDING)
+    enum track_load_status trackstat = audio_finish_load_track(info);
+
+    if (trackstat >= LOAD_TRACK_OK)
+    {
+        struct track_info *cur_info = track_list_user_current(0);
+
+        if (info == cur_info)
         {
-            /* Monitor remaining PCM before stopping */
-            filling = STATE_ENDING;
-            pcmbuf_monitor_track_change(true);
+            /* Copy cuesheet */
+            buf_read_cuesheet(cur_info->cuesheet_hid);
+
+            if (!valid_mp3entry(id3_get(PLAYING_ID3)))
+            {
+                /* This is the currently playing track - get metadata, stat */
+                struct mp3entry *id3 = bufgetid3(info->id3_hid);
+
+                id3->offset = 0;
+
+                id3_write_locked(PLAYING_ID3, id3); /* pointer safe - only item */
+
+                /* Track load initiation was successful */
+                audio_playlist_track_change();
+            }
         }
 
-        codec_stop();
+        if (trackstat == LOAD_TRACK_READY && !audio_start_codec())
+            audio_handle_track_load_status(LOAD_TRACK_ERR_START_CODEC);
     }
-    else
+}
+
+/* Called when handles other than metadata handles have finished buffering
+   (Q_AUDIO_HANDLE_FINISHED) */
+static void audio_on_handle_finished(int hid)
+{
+    /* Right now, only audio handles should end up calling this */
+    if (filling == STATE_END_OF_PLAYLIST)
     {
+        struct track_info *info = track_list_last(0);
+
+        /* Really we don't know which order the handles will actually complete
+           to zero bytes remaining since another thread is doing it - be sure
+           it's the right one */
+        if (info && info->audio_hid == hid)
+        {
+            /* This was the last track in the playlist and we now have all the
+               data we need */
+            filling_is_finished();
+        }
+    }
+}
+
+/* Called to make an outstanding track skip the current track and to send the
+   transition events */
+static void audio_finalise_track_change(bool delayed)
+{
+    switch (skip_pending)
+    {
+    case TRACK_SKIP_AUTO:
+        audio_playlist_track_finish();
+
+        if (!playlist_peek(1, NULL, 0))
+        {
+            /* Track ended up rejected - push things ahead like the codec blew
+               it (because it was never started and now we're here where it
+               should have been decoding the next track by now) - next, a
+               directory change or end of playback will most likely happen */
+            skip_pending = TRACK_SKIP_NONE;
+            audio_handle_track_load_status(LOAD_TRACK_ERR_START_CODEC);
+            return;
+        }
+
+        playlist_peek_offset--;
+        if (playlist_next(1) >= 0)
+            break;
+
+        /* What!? Disappear? Hopeless bleak despair. */
+    case TRACK_SKIP_AUTO_END_PLAYLIST:
+    default:                            /* Invalid - just stop */
+        filling = STATE_ENDED;
         audio_stop_playback();
+        return;
+
+    case TRACK_SKIP_AUTO_NEW_PLAYLIST:
+        audio_playlist_track_finish();
+
+        if (!playlist_peek(0, NULL, 0))
+        {
+            skip_pending = TRACK_SKIP_NONE;
+            audio_handle_track_load_status(LOAD_TRACK_ERR_START_CODEC);
+            return;
+        }
+        break;
+
+    case TRACK_SKIP_NONE:               /* A manual track change */
+        break;
     }
+
+    struct track_info *info = track_list_current(0);
+
+    /* Update the current cuesheet if any and enabled */
+    id3_mutex_lock();
+
+    buf_read_cuesheet(info->cuesheet_hid);
+
+    id3_write(PLAYING_ID3, info ? bufgetid3(info->id3_hid) : NULL);
+
+    if (delayed)
+    {
+        struct mp3entry *ci_id3 = id3_get(CODEC_ID3);
+        struct mp3entry *ply_id3 = id3_get(PLAYING_ID3);
+        ply_id3->elapsed = ci_id3->elapsed;
+        ply_id3->offset = ci_id3->offset;
+    }
+
+    /* The skip is technically over */
+    skip_pending = TRACK_SKIP_NONE;
+
+    /* Sync the next track information */
+    info = track_list_current(1);
+
+    id3_write(NEXTTRACK_ID3,
+              info ? bufgetid3(info->id3_hid) : id3_get(UNBUFFERED_ID3));
+
+    id3_mutex_unlock();
+
+    audio_playlist_track_change();
 }
 
-static void audio_check_new_track(void)
+/* Actually begin a transition and take care of the codec change - may complete
+   it now or ask pcmbuf for notification depending on the type and what pcmbuf
+   has to say */
+static void audio_begin_track_change(enum track_load_status trackstat,
+                                     bool automatic)
 {
-    int track_count;
-    int old_track_ridx;
-    int i, idx;
-    bool forward;
-    struct mp3entry *temp;
+    /* Even if the new track is bad, the old track must be finished off */
+    if (pcmbuf_start_track_change(automatic))
+    {
+        /* pcmbuf says that the transition happens now - complete it */
+        audio_finalise_track_change(false);
 
-    if (ci.new_track == 0)
+        if (play_status == PLAY_STOPPED)
+            return; /* Stopped us */
+    }
+
+    if (!automatic)
+        audio_clear_paused_pcm();
+
+    if (trackstat >= LOAD_TRACK_OK)
     {
-        ci.new_track++;
-        automatic_skip = true;
+        struct track_info *info = track_list_current(0);
+
+        if (valid_mp3entry(bufgetid3(info->id3_hid)))
+        {
+            /* If everything needed for the codec is ready - start it */
+            if (info->audio_hid < 0 || audio_start_codec())
+                return;
+
+            trackstat = LOAD_TRACK_ERR_START_CODEC;
+        }
     }
 
-    track_count = audio_track_count();
-    old_track_ridx = track_ridx;
+    audio_handle_track_load_status(trackstat);
+}
 
-    /* Now it's good time to send track finish events. */
-    send_event(PLAYBACK_EVENT_TRACK_FINISH, thistrack_id3);
-    /* swap the mp3entry pointers */
-    temp = thistrack_id3;
-    thistrack_id3 = othertrack_id3;
-    othertrack_id3 = temp;
-    ci.id3 = thistrack_id3;
-    memset(thistrack_id3, 0, sizeof(struct mp3entry));
+/* Transition to end-of-playlist state */
+static void audio_monitor_end_of_playlist(void)
+{
+    skip_pending = TRACK_SKIP_AUTO_END_PLAYLIST;
+    filling = STATE_ENDING;
+    pcmbuf_monitor_track_change(true);
+}
 
-    if (dir_skip)
+/* Called when codec completes seek operation
+   (usually Q_AUDIO_CODEC_SEEK_COMPLETE) */
+static void audio_on_codec_seek_complete(void)
+{
+    logf("%s()", __func__);
+    audio_complete_codec_seek();
+    codec_go();
+}
+
+/* Codec has completed decoding the track
+   (usually Q_AUDIO_CODEC_COMPLETE) */
+static void audio_on_codec_complete(int status)
+{
+    logf("%s(%d)", __func__, status);
+
+    if (play_status == PLAY_STOPPED)
+        return;
+
+    /* If it didn't notify us first, don't expect "seek complete" message
+       since the codec can't post it now - do things like it would have
+       done */
+    audio_complete_codec_seek();
+
+    if (play_status == PLAY_PAUSED)
     {
-        dir_skip = false;
-        /* regardless of the return value we need to rebuffer.
-           if it fails the old playlist will resume, else the
-           next dir will start playing */
-        playlist_next_dir(ci.new_track);
-        ci.new_track = 0;
-        audio_rebuffer();
-        goto skip_done;
+        /* Old-hay on the ip-skay - codec has completed decoding the track but
+           we're not sounding it, so just remember that it happened and the
+           resume will begin the transition */
+        codec_skip_pending = true;
+        return;
     }
 
-    if (new_playlist)
-        ci.new_track = 0;
+    codec_skip_pending = false;
 
-    /* If the playlist isn't that big */
-    if (automatic_skip)
+    if (status >= 0)
     {
-        while (!playlist_check(ci.new_track))
+        /* Normal automatic skip */
+#ifdef AB_REPEAT_ENABLE
+        ab_end_of_track_report();
+#endif
+    }
+
+    /* else AB shouldn't seek this on error since decoding reported a
+       problem - it might be better to just stop playing altogether rather
+       than repeat the difficulty if doing AB or repeat one */
+
+    /* This is always to move by +1 */
+    automatic_skip = true;
+
+    if (skip_pending != TRACK_SKIP_NONE)
+    {
+        /* If there was a pending skip, finish it first - until pcmbuf is
+           better suited, we'll not allow them to build up ahead, thus
+           track changes with really short files in the pcm buffer won't
+           look perfect to the user but they'll end up correct */
+        audio_clear_track_notifications();
+        audio_finalise_track_change(true);
+
+        if (play_status == PLAY_STOPPED)
+            return; /* Stopped us */
+    }
+
+    enum track_load_status trackstat = LOAD_TRACK_OK;
+
+    skip_pending = TRACK_SKIP_AUTO;
+
+    /* Does this track have an entry allocated? */
+    struct track_info *info = track_list_advance_current(1);
+
+    if (!info || info->audio_hid < 0)
+    {
+        bool end_of_playlist = false;
+
+        if (info)
         {
-            if (ci.new_track >= 0)
+            /* Track load is not complete - it might have stopped on a
+               full buffer without reaching the audio handle or we just
+               arrived at it early
+
+               If this type is atomic and we couldn't get the audio,
+               perhaps it would need to wrap to make the allocation and
+               handles are in the way - to maximize the liklihood it can
+               be allocated, clear all handles to reset the buffer and
+               its indexes to 0 - for packet audio, this should not be an
+               issue and a pointless full reload of all the track's
+               metadata may be avoided */
+
+            struct mp3entry *track_id3 = bufgetid3(info->id3_hid);
+
+            if (track_id3 &&
+                get_audio_base_data_type(track_id3->codectype)
+                            == TYPE_PACKET_AUDIO)
             {
-                audio_last_track(true);
+                /* Continue filling after this track */
+                audio_reset_and_rebuffer(TRACK_LIST_KEEP_CURRENT, 1);
+                audio_begin_track_change(trackstat, true);
                 return;
             }
-            ci.new_track++;
+            /* else rebuffer at this track; status applies to the track we
+               want */
         }
+        else if (!playlist_peek(1, NULL, 0))
+        {
+            /* Play sequence is complete - directory change or other playlist
+               resequencing - the playlist must now be advanced in order to
+               continue since a peek ahead to the next track is not possible */
+            skip_pending = TRACK_SKIP_AUTO_NEW_PLAYLIST;
+            end_of_playlist = playlist_next(1) < 0;
+        }
+
+        if (!end_of_playlist)
+        {
+            trackstat = audio_reset_and_rebuffer(TRACK_LIST_CLEAR_ALL,
+                            skip_pending == TRACK_SKIP_AUTO ? 0 : -1);
+
+            if (trackstat == LOAD_TRACK_ERR_NO_MORE)
+            {
+                /* Failed to find anything afterall - do playlist switchover
+                   instead */
+                skip_pending = TRACK_SKIP_AUTO_NEW_PLAYLIST;
+                end_of_playlist = playlist_next(1) < 0;
+            }
+        }
+
+        if (end_of_playlist)
+        {
+            audio_monitor_end_of_playlist();
+            return;
+        }
     }
 
-    /* Update the playlist */
-    last_peek_offset -= ci.new_track;
+    audio_begin_track_change(trackstat, true);
+}
 
-    if (playlist_next(ci.new_track) < 0)
+/* Begin playback from an idle state, transition to a new playlist or
+   invalidate the buffer and resume (if playing).
+   (usually Q_AUDIO_PLAY, Q_AUDIO_REMAKE_AUDIO_BUFFER) */
+static void audio_start_playback(size_t offset, bool restart, bool invalid)
+{
+    enum play_status old_status = play_status;
+
+    if (invalid)
     {
-        /* End of list */
-        audio_last_track(automatic_skip);
+        /* Mark the buffer dirty - if not playing, it will be reset next
+           time */
+        if (buffer_state == AUDIOBUF_STATE_INITIALIZED)
+            buffer_state = AUDIOBUF_STATE_VOICED_ONLY;
+    }
+
+    if (old_status != PLAY_STOPPED)
+    {
+        logf("%s(%lu): skipping", __func__, (unsigned long)offset);
+
+        halt_decoding_track(true);
+
+        skip_pending = TRACK_SKIP_NONE;
+        automatic_skip = false;
+        ff_rw_mode = false;
+
+        if (restart)
+        {
+            /* Clear out some stuff to resume the current track where it
+               left off */
+            pcmbuf_play_stop();
+            offset = id3_get(PLAYING_ID3)->offset;
+            track_list_clear(TRACK_LIST_CLEAR_ALL);
+        }
+        else
+        {
+            /* This is more-or-less treated as manual track transition */
+            /* Save resume information for current track */
+            audio_playlist_track_finish();
+            track_list_clear(TRACK_LIST_CLEAR_ALL);
+
+            /* Indicate manual track change */
+            pcmbuf_start_track_change(false);
+            audio_clear_paused_pcm();
+            wipe_track_metadata(true);
+        }
+    }
+    else
+    {
+        if (restart)
+            return; /* Must already be playing */
+
+        /* Cold playback start from a stopped state */
+        logf("%s(%lu): starting", __func__, offset);
+
+        /* Set audio parameters */
+#if INPUT_SRC_CAPS != 0
+        audio_set_input_source(AUDIO_SRC_PLAYBACK, SRCF_PLAYBACK);
+        audio_set_output_source(AUDIO_SRC_PLAYBACK);
+#endif
+#ifndef PLATFORM_HAS_VOLUME_CHANGE
+        sound_set_volume(global_settings.volume);
+#endif
+        /* Update our state */
+        //playing = true;
+        play_status = PLAY_PLAYING;
+
+        /* If 'paused' was set, keep it because it was a restart during
+           pause - normally it will be set 'false' during stop */
+    }
+
+    /* Start fill from beginning of playlist */
+    playlist_peek_offset = -1;
+    buf_set_base_handle(-1);
+
+    /* Officially playing */
+    queue_reply(&audio_queue, 1);
+
+    /* Add these now - finish event for the first id3 will come during
+       audio_fill_file_buffer */
+    add_event(BUFFER_EVENT_REBUFFER, false, buffer_event_rebuffer_callback);
+    add_event(BUFFER_EVENT_FINISHED, false, buffer_event_finished_callback);
+
+    if (old_status == PLAY_STOPPED)
+    {
+        /* Send coldstart event */
+        send_event(PLAYBACK_EVENT_START_PLAYBACK, NULL);
+    }
+
+    /* Fill the buffer */
+    enum track_load_status trackstat = audio_fill_file_buffer();
+
+    if (trackstat >= LOAD_TRACK_OK)
+    {
+        /* This is the currently playing track - get metadata, stat */
+        struct mp3entry *id3 = bufgetid3(track_list_current(0)->id3_hid);
+
+        /* Save starting offset for later when starting the codec */
+        if (id3)
+            id3->offset = offset;
+
+        id3_write_locked(PLAYING_ID3, id3); /* pointer safe - only item */
+
+        /* Track load initiation was successful */
+        audio_playlist_track_change();
+    }
+    else
+    {
+        /* Found nothing playable */
+        audio_handle_track_load_status(trackstat);
+    }
+}
+
+/* Stop playback and enter an idle state
+   (usually Q_AUDIO_STOP) */
+static void audio_stop_playback(void)
+{
+    logf("%s()", __func__);
+
+    if (play_status == PLAY_STOPPED)
         return;
-    }
+
+    /* Stop the codec and unload it */
+    halt_decoding_track(true);
+    pcmbuf_play_stop();
+    codec_unload();
+
+    skip_pending = TRACK_SKIP_NONE;
+
+    /* Save resume information  - "filling" might have been set to
+       "STATE_ENDED" by caller in order to facilitate end of playlist */
+    audio_playlist_track_finish();
+
+    automatic_skip = false;
+
+    /* Close all tracks and mark them NULL */
+    remove_event(BUFFER_EVENT_REBUFFER, buffer_event_rebuffer_callback);
+    remove_event(BUFFER_EVENT_FINISHED, buffer_event_finished_callback);
+    remove_event(BUFFER_EVENT_BUFFER_LOW, buffer_event_buffer_low_callback);
+
+    track_list_clear(TRACK_LIST_CLEAR_ALL);
+
+    /* Update our state */
     
-    if (new_playlist)
+    ff_rw_mode = false;
+    play_status = PLAY_STOPPED;
+
+    wipe_track_metadata(true);
+
+    /* Go idle */
+    filling = STATE_IDLE;
+    cancel_cpu_boost();
+}
+
+/* Pause the playback of the current track
+   (Q_AUDIO_PAUSE) */
+static void audio_on_pause(bool pause)
+{
+    logf("%s(%s)", __func__, pause ? "true" : "false");
+
+    if (play_status == PLAY_STOPPED || pause == (play_status == PLAY_PAUSED))
+        return;
+
+    if (!ff_rw_mode)
     {
-        ci.new_track = 1;
-        new_playlist = false;
+        /* Not in ff/rw mode - may set the state (otherwise this could make
+           old data play because seek hasn't completed and cleared it) */
+        pcmbuf_pause(pause);
     }
 
-    /* Save a pointer to the old track to allow later clearing */
-    prev_ti = CUR_TI;
+    play_status = pause ? PLAY_PAUSED : PLAY_PLAYING;
 
-    for (i = 0; i < ci.new_track; i++)
+    if (!pause && codec_skip_pending)
     {
-        idx = (track_ridx + i) & MAX_TRACK_MASK;
-        struct mp3entry *id3 = bufgetid3(tracks[idx].id3_hid);
-        ssize_t offset = buf_handle_offset(tracks[idx].audio_hid);
-        if (!id3 || offset < 0 || (unsigned)offset > id3->first_frame_offset)
+        /* Actually do the skip that is due - resets the status flag */
+        audio_on_codec_complete(CODEC_OK);
+    }
+}
+
+/* Skip a certain number of tracks forwards or backwards
+   (Q_AUDIO_SKIP) */
+static void audio_on_skip(void)
+{
+    id3_mutex_lock();
+
+    /* Eat the delta to keep it synced, even if not playing */
+    int toskip = skip_offset;
+    skip_offset = 0;
+
+    logf("%s(): %d", __func__, toskip);
+
+    id3_mutex_unlock();
+
+    if (play_status == PLAY_STOPPED)
+        return;
+
+    /* Force codec to abort this track */
+    halt_decoding_track(true);
+
+    /* Kill the ff/rw halt */
+    ff_rw_mode = false;
+
+    /* Manual skip */
+    automatic_skip = false;
+
+    /* If there was an auto skip in progress, there will be residual
+       advancement of the playlist and/or track list so compensation will be
+       required in order to end up in the right spot */
+    int track_list_delta = toskip;
+    int playlist_delta = toskip;
+
+    if (skip_pending != TRACK_SKIP_NONE)
+    {
+        track_list_delta--;
+
+        if (skip_pending == TRACK_SKIP_AUTO_NEW_PLAYLIST)
+            playlist_delta--;
+    }
+
+    skip_pending = TRACK_SKIP_NONE;
+    audio_playlist_track_finish();
+
+    /* Update the playlist current track now */
+    while (playlist_next(playlist_delta) < 0)
+    {
+        /* Manual skip out of range (because the playlist wasn't updated
+           yet by us and so the check in audio_skip returned 'ok') - bring
+           back into range */
+        int d = toskip < 0 ? 1 : -1;
+
+        while (!playlist_check(playlist_delta))
         {
-            /* We don't have all the audio data for that track, so clear it,
-               but keep the metadata. */
-            if (tracks[idx].audio_hid >= 0 && bufclose(tracks[idx].audio_hid))
+            if (playlist_delta == d)
             {
-                tracks[idx].audio_hid = -1;
-                tracks[idx].filesize = 0;
+                /* Had to move the opposite direction to correct, which is
+                   wrong - this is the end */
+                filling = STATE_ENDED;
+                audio_stop_playback();
+                return;
             }
+
+            playlist_delta += d;
+            track_list_delta += d;
         }
     }
 
-    /* Move to the new track */
-    track_ridx = (track_ridx + ci.new_track) & MAX_TRACK_MASK;
-    buf_set_base_handle(CUR_TI->audio_hid);
+    /* Adjust things by how much the playlist was manually moved */
+    playlist_peek_offset -= playlist_delta;
 
-    if (automatic_skip)
-    {
-        wps_offset = -ci.new_track;
-    }
+    struct track_info *info = track_list_advance_current(track_list_delta);
+    enum track_load_status trackstat = LOAD_TRACK_OK;
 
-    /* If it is not safe to even skip this many track entries */
-    if (ci.new_track >= track_count || ci.new_track <= track_count - MAX_TRACK)
+    if (!info || info->audio_hid < 0)
     {
-        ci.new_track = 0;
-        audio_rebuffer();
-        goto skip_done;
+        /* We don't know the next track thus we know we don't have it */
+        trackstat = audio_reset_and_rebuffer(TRACK_LIST_CLEAR_ALL, -1);
     }
 
-    forward = ci.new_track > 0;
-    ci.new_track = 0;
+    audio_begin_track_change(trackstat, false);
+}
 
-    /* If the target track is clearly not in memory */
-    if (CUR_TI->filesize == 0 || !CUR_TI->taginfo_ready)
+/* Skip to the next/previous directory
+   (Q_AUDIO_DIR_SKIP) */
+static void audio_on_dir_skip(int direction)
+{
+    logf("%s(%d)", __func__, direction);
+
+    id3_mutex_lock();
+    skip_offset = 0;
+    id3_mutex_unlock();
+
+    if (play_status == PLAY_STOPPED)
+        return;
+
+    /* Force codec to abort this track */
+    halt_decoding_track(true);
+
+    /* Kill the ff/rw halt */
+    ff_rw_mode = false;
+
+    /* Manual skip */
+    automatic_skip = false;
+
+    /* Regardless of the return value we need to rebuffer. If it fails the old
+       playlist will resume, else the next dir will start playing. */
+
+    /* Unless automatic and gapless, skips do not pend */
+    skip_pending = TRACK_SKIP_NONE;
+
+    audio_playlist_track_finish();
+
+    playlist_next_dir(direction);
+    wipe_track_metadata(false);
+
+    enum track_load_status trackstat =
+        audio_reset_and_rebuffer(TRACK_LIST_CLEAR_ALL, -1);
+
+    if (trackstat == LOAD_TRACK_ERR_NO_MORE)
     {
-        audio_rebuffer();
-        goto skip_done;
+        /* The day the music died - finish-off whatever is playing and call it
+           quits */
+        audio_monitor_end_of_playlist();
+        return;
     }
 
-    /* When skipping backwards, it is possible that we've found a track that's
-     * buffered, but which is around the track-wrap and therefore not the track
-     * we are looking for */
-    if (!forward)
+    audio_begin_track_change(trackstat, false);
+}
+
+/* Enter seek mode in order to start a seek
+   (Q_AUDIO_PRE_FF_REWIND) */
+static void audio_on_pre_ff_rewind(void)
+{
+    logf("%s()", __func__);
+
+    if (play_status == PLAY_STOPPED || ff_rw_mode)
+        return;
+
+    ff_rw_mode = true;
+
+    if (play_status == PLAY_PAUSED)
+        return;
+
+    pcmbuf_pause(true);
+}
+
+/* Seek the playback of the current track to the specified time
+   (Q_AUDIO_FF_REWIND) */
+static void audio_on_ff_rewind(long time)
+{
+    logf("%s(%ld)", __func__, time);
+
+    if (play_status == PLAY_STOPPED)
+        return;
+
+    enum track_skip_type pending = skip_pending;
+
+    switch (pending)
     {
-        int cur_idx = track_ridx;
-        bool taginfo_ready = true;
-        /* We've wrapped the buffer backwards if new > old */
-        bool wrap = track_ridx > old_track_ridx;
+    case TRACK_SKIP_NONE:              /* The usual case */
+    case TRACK_SKIP_AUTO:              /* Have to back it out (fun!) */
+    case TRACK_SKIP_AUTO_END_PLAYLIST: /* Still have the last codec used */
+    {
+        struct mp3entry *id3 = id3_get(PLAYING_ID3);
+        struct mp3entry *ci_id3 = id3_get(CODEC_ID3);
 
-        while (1)
+        automatic_skip = false;
+
+        /* Send event before clobbering the time */
+        /* FIXME: Nasty, but the tagtree expects this so that rewinding and
+           then skipping back to this track resumes properly. Something else
+           should be sent. We're not _really_ finishing the track are we? */
+        if (time == 0)
+            send_event(PLAYBACK_EVENT_TRACK_FINISH, id3);
+
+        /* Prevent user codec time update - coerce to something that is
+           innocuous concerning lookaheads */
+        if (pending == TRACK_SKIP_NONE)
+            skip_pending = TRACK_SKIP_AUTO_END_PLAYLIST;
+
+        id3->elapsed = time;
+        queue_reply(&audio_queue, 1);
+
+        bool haltres = halt_decoding_track(pending == TRACK_SKIP_AUTO);
+
+        /* Need this set in case ff/rw mode + error but _after_ the codec
+           halt that will reset it */
+        codec_seeking = true;
+
+        if (pending == TRACK_SKIP_AUTO)
         {
-            cur_idx = (cur_idx + 1) & MAX_TRACK_MASK;
+            if (!track_list_advance_current(-1))
+            {
+                /* Not in list - must rebuffer at the current playlist index */
+                if (audio_reset_and_rebuffer(TRACK_LIST_CLEAR_ALL, -1)
+                        < LOAD_TRACK_OK)
+                {
+                    /* Codec is stopped */
+                    break;
+                }
+            }
+        }
 
-            /* if we've advanced past the wrap when cur_idx is zeroed */
-            if (!cur_idx)
-                wrap = false;
+        /* Set after audio_fill_file_buffer to disable playing id3 clobber if
+           rebuffer is needed */
+        skip_pending = TRACK_SKIP_NONE;
+        struct track_info *cur_info = track_list_current(0);
 
-            /* if we aren't still on the wrap and we've caught the old track */
-            if (!(wrap || cur_idx < old_track_ridx))
-                break;
+        /* Track must complete the loading _now_ since a codec and audio
+           handle are needed in order to do the seek */
+        if (cur_info->audio_hid < 0 &&
+            audio_finish_load_track(cur_info) != LOAD_TRACK_READY)
+        {
+            /* Call above should push any load sequence - no need for
+               halt_decoding_track here if no skip was pending here because
+               there would not be a codec started if no audio handle was yet
+               opened */
+            break;
+        }
 
-            /* If we hit a track in between without valid tag info, bail */
-            if (!tracks[cur_idx].taginfo_ready)
+        if (pending == TRACK_SKIP_AUTO)
+        {
+            if (!bufreadid3(cur_info->id3_hid, ci_id3) ||
+                !audio_init_codec(cur_info, ci_id3))
             {
-                taginfo_ready = false;
+                /* We should have still been able to get it - skip it and move
+                   onto the next one - like it or not this track is borken */
                 break;
             }
+
+            /* Set the codec API to the correct metadata and track info */
+            ci.audio_hid = cur_info->audio_hid;
+            ci.filesize = cur_info->filesize;
+            buf_set_base_handle(cur_info->audio_hid);
         }
-        if (!taginfo_ready)
+
+        if (!haltres)
         {
-            audio_rebuffer();
+            /* If codec must be (re)started, reset the offset */
+            ci_id3->offset = 0;
         }
-    }
 
-skip_done:
-    audio_update_trackinfo();
-    pcmbuf_start_track_change(automatic_skip);
+        codec_seek(time);
+        return;
+        }
 
-    if (get_codec_base_type(codec_loaded()) ==
-        get_codec_base_type(thistrack_id3->codectype))
+    case TRACK_SKIP_AUTO_NEW_PLAYLIST:
     {
-        /* codec is the same base type */
-        logf("New track loaded");
-        codec_ack_msg(Q_CODEC_REQUEST_COMPLETE, false);
+        /* We cannot do this because the playlist must be reversed by one
+           and it doesn't always return the same song when going backwards
+           across boundaries as forwards (either because of randomization
+           or inconsistency in deciding what the previous track should be),
+           therefore the whole operation would often end up as nonsense -
+           lock out seeking for a couple seconds */
+
+        /* Sure as heck cancel seek mode too! */
+        audio_ff_rewind_end();
+        return;
+        }
+
+    default:
+        /* Won't see this */
+        return;
     }
-    else
+
+    if (play_status == PLAY_STOPPED)
     {
-        /* a codec change is required */
-        logf("New codec: %d/%d", thistrack_id3->codectype, codec_loaded());
-        codec_ack_msg(Q_CODEC_REQUEST_COMPLETE, true);
-        codec_load(tracks[track_ridx].codec_hid, thistrack_id3->codectype);
-        tracks[track_ridx].codec_hid = -1; /* Codec thread will close it */
+        /* Playback ended because of an error completing a track load */
+        return;
     }
+
+    /* Always fake it as a codec start error which will handle mode
+       cancellations and skip to the next track */
+    audio_handle_track_load_status(LOAD_TRACK_ERR_START_CODEC);
 }
 
-unsigned long audio_prev_elapsed(void)
+/* Invalidates all but currently playing track
+   (Q_AUDIO_FLUSH) */
+static void audio_on_audio_flush(void)
 {
-    return prev_track_elapsed;
+    logf("%s", __func__);
+
+    if (track_list_empty())
+        return; /* Nothing to flush out */
+
+    switch (skip_pending)
+    {
+    case TRACK_SKIP_NONE:
+    case TRACK_SKIP_AUTO_END_PLAYLIST:
+        /* Remove all but the currently playing track from the list and
+           refill after that */
+        track_list_clear(TRACK_LIST_KEEP_CURRENT);
+        playlist_peek_offset = 0;
+        id3_write_locked(UNBUFFERED_ID3, NULL);
+        audio_update_and_announce_next_track(NULL);
+
+        /* Ignore return since it's about the next track, not this one */        
+        audio_fill_file_buffer();
+
+        if (skip_pending == TRACK_SKIP_NONE)
+            break;
+
+        /* There's now a track after this one now - convert to auto skip -
+           no skip should pend right now because multiple flush messages can
+           be fired which would cause a restart in the below cases */
+        skip_pending = TRACK_SKIP_NONE;
+        audio_clear_track_notifications();
+        audio_queue_post(Q_AUDIO_CODEC_COMPLETE, CODEC_OK);
+        break;
+
+    case TRACK_SKIP_AUTO:
+    case TRACK_SKIP_AUTO_NEW_PLAYLIST:
+        /* Precisely removing what it already decoded for the next track is
+           not possible so a restart is required in order to continue the
+           currently playing track without the now invalid future track
+           playing */
+        audio_start_playback(0, true, false);
+        break;
+
+    default: /* Nothing else is a state */
+        break;
+    }
 }
 
-void audio_set_prev_elapsed(unsigned long setting)
+#ifdef AUDIO_HAVE_RECORDING
+/* Load the requested encoder type
+   (Q_AUDIO_LOAD_ENCODER) */
+static void audio_on_load_encoder(int afmt)
 {
-    prev_track_elapsed = setting;
+    bool res = true;
+
+    if (play_status != PLAY_STOPPED)
+        audio_stop_playback(); /* Can't load both types at once */
+    else
+        codec_unload(); /* Encoder still loaded, stop and unload it */
+
+    if (afmt != AFMT_UNKNOWN)
+    {
+        res = codec_load(-1, afmt | CODEC_TYPE_ENCODER);
+        if (res)
+            codec_go(); /* These are run immediately */
+    }
+
+    queue_reply(&audio_queue, res);
 }
+#endif /* AUDIO_HAVE_RECORDING */
 
-/* Stop the codec and reset the PCM buffer */
-static void audio_stop_codec_flush(void)
+static void audio_thread(void)
 {
-    bool pcm_playing;
+    struct queue_event ev;
 
-    pcmbuf_pause(true);
+    pcm_postinit();
 
-    codec_stop();
+    filling = STATE_IDLE;
 
-    pcm_play_lock();
+    while (1)
+    {
+        switch (filling)
+        {
+        /* Active states */
+        case STATE_FULL:
+        case STATE_END_OF_PLAYLIST:
+            if (buf_get_watermark() == 0)
+            {
+                /* End of buffering for now, let's calculate the watermark,
+                   register for a low buffer event and unboost */
+                audio_update_filebuf_watermark(0);
+                add_event(BUFFER_EVENT_BUFFER_LOW, true,
+                          buffer_event_buffer_low_callback);
+            }
+            /* Fall-through */
+        case STATE_FINISHED:
+            /* All data was buffered */
+            cancel_cpu_boost();
+            /* Fall-through */
+        case STATE_FILLING:
+        case STATE_ENDING:
+            if (audio_pcmbuf_track_change_scan())
+            {
+                /* Transfer notification to audio queue event */
+                ev.id = Q_AUDIO_TRACK_CHANGED;
+                ev.data = 1;
+            }
+            else
+            {
+                /* If doing auto skip, poll pcmbuf track notifications a bit
+                   faster to promply detect the transition */
+                queue_wait_w_tmo(&audio_queue, &ev,
+                                 skip_pending == TRACK_SKIP_NONE ?
+                                    HZ/2 : HZ/10);
+            }
+            break;
 
-    pcm_playing = pcm_is_playing();
+        /* Idle states */
+        default:
+            queue_wait(&audio_queue, &ev);
 
-    pcmbuf_play_stop();
-    queue_clear(&pcmbuf_queue);
+#if (CONFIG_PLATFORM & PLATFORM_NATIVE)
+            switch (ev.id)
+            {
+#ifdef AUDIO_HAVE_RECORDING
+            /* Must monitor the encoder message for recording so it can remove
+               it if we process the insertion before it does. It cannot simply
+               be removed from under recording however. */
+            case Q_AUDIO_LOAD_ENCODER:
+                break;
+#endif
+            case SYS_USB_DISCONNECTED:
+                filling = STATE_IDLE;
+                break;
 
-    if (pcm_playing)
-        pcmbuf_pause(paused);
+            default:
+                if (filling == STATE_USB)
+                    continue;
+            }
+#endif /* CONFIG_PLATFORM */
+        }
 
-    pcm_play_unlock();
+        switch (ev.id)
+        {
+        /** Codec and track change messages **/
+        case Q_AUDIO_TRACK_CHANGED:
+            /* PCM track change done */
+            LOGFQUEUE("audio < Q_AUDIO_TRACK_CHANGED");
+            audio_finalise_track_change(true);
+            break;
+
+        case Q_AUDIO_CODEC_COMPLETE:
+            /* Codec is done processing track and has gone idle */
+            LOGFQUEUE("audio < Q_AUDIO_CODEC_COMPLETE: %ld", (long)ev.data);
+            audio_on_codec_complete(ev.data);
+            break;
+
+        case Q_AUDIO_CODEC_SEEK_COMPLETE:
+            /* Codec is done seeking */
+            LOGFQUEUE("audio < Q_AUDIO_SEEK_COMPLETE");
+            audio_on_codec_seek_complete();
+            break;
+
+        /** Control messages **/
+        case Q_AUDIO_PLAY:
+            LOGFQUEUE("audio < Q_AUDIO_PLAY");
+            audio_start_playback(ev.data, false, false);
+            break;
+
+        case Q_AUDIO_STOP:
+            LOGFQUEUE("audio < Q_AUDIO_STOP");
+            audio_stop_playback();
+            if (ev.data != 0)
+                queue_clear(&audio_queue);
+            break;
+
+        case Q_AUDIO_PAUSE:
+            LOGFQUEUE("audio < Q_AUDIO_PAUSE");
+            audio_on_pause(ev.data);
+            break;
+
+        case Q_AUDIO_SKIP:
+            LOGFQUEUE("audio < Q_AUDIO_SKIP");
+            audio_on_skip();
+            break;
+
+        case Q_AUDIO_DIR_SKIP:
+            LOGFQUEUE("audio < Q_AUDIO_DIR_SKIP");
+            audio_on_dir_skip(ev.data);
+            break;
+
+        case Q_AUDIO_PRE_FF_REWIND:
+            LOGFQUEUE("audio < Q_AUDIO_PRE_FF_REWIND");
+            audio_on_pre_ff_rewind();
+            break;
+
+        case Q_AUDIO_FF_REWIND:
+            LOGFQUEUE("audio < Q_AUDIO_FF_REWIND");
+            audio_on_ff_rewind(ev.data);
+            break;
+
+        case Q_AUDIO_FLUSH:
+            LOGFQUEUE("audio < Q_AUDIO_FLUSH: %d", (int)ev.data);
+            audio_on_audio_flush();
+            break;
+
+        /** Buffering messages **/
+        case Q_AUDIO_BUFFERING:
+            /* some buffering event */
+            LOGFQUEUE("audio < Q_AUDIO_BUFFERING: %d", (int)ev.data);
+            audio_on_buffering(ev.data);
+            break;
+
+        case Q_AUDIO_FILL_BUFFER:
+            /* continue buffering next track */
+            LOGFQUEUE("audio < Q_AUDIO_FILL_BUFFER");
+            audio_on_fill_buffer();
+            break;
+
+        case Q_AUDIO_FINISH_LOAD_TRACK:
+            /* metadata is buffered */
+            LOGFQUEUE("audio < Q_AUDIO_FINISH_LOAD_TRACK");
+            audio_on_finish_load_track(ev.data);
+            break;
+
+        case Q_AUDIO_HANDLE_FINISHED:
+            /* some other type is buffered */
+            LOGFQUEUE("audio < Q_AUDIO_HANDLE_FINISHED");
+            audio_on_handle_finished(ev.data); 
+            break;
+
+        /** Miscellaneous messages **/
+        case Q_AUDIO_REMAKE_AUDIO_BUFFER:
+            /* buffer needs to be reinitialized */
+            LOGFQUEUE("audio < Q_AUDIO_REMAKE_AUDIO_BUFFER");
+            audio_start_playback(0, true, true);
+            break;
+
+#ifdef HAVE_DISK_STORAGE
+        case Q_AUDIO_UPDATE_WATERMARK:
+            /* buffering watermark needs updating */
+            LOGFQUEUE("audio < Q_AUDIO_UPDATE_WATERMARK: %d", (int)ev.data);
+            audio_update_filebuf_watermark(ev.data);
+            break;
+#endif /* HAVE_DISK_STORAGE */
+
+#ifdef AUDIO_HAVE_RECORDING
+        case Q_AUDIO_LOAD_ENCODER:
+            /* load an encoder for recording */
+            LOGFQUEUE("audio < Q_AUDIO_LOAD_ENCODER: %d", (int)ev.data);
+            audio_on_load_encoder(ev.data);
+            break;
+#endif /* AUDIO_HAVE_RECORDING */
+
+#if (CONFIG_PLATFORM & PLATFORM_NATIVE)
+        case SYS_USB_CONNECTED:
+            LOGFQUEUE("audio < SYS_USB_CONNECTED");
+            audio_stop_playback();
+#ifdef PLAYBACK_VOICE
+            voice_stop();
+#endif
+            filling = STATE_USB;
+            usb_acknowledge(SYS_USB_CONNECTED_ACK);
+            break;
+#endif /* (CONFIG_PLATFORM & PLATFORM_NATIVE) */
+
+        case SYS_TIMEOUT:
+            LOGFQUEUE_SYS_TIMEOUT("audio < SYS_TIMEOUT");
+            break;
+
+        default:
+            /* LOGFQUEUE("audio < default : %08lX", ev.id); */
+            break;
+        } /* end switch */
+    } /* end while */
 }
 
-static void audio_stop_playback(void)
+
+/* --- Buffering callbacks --- */
+
+/* Called when fullness is below the watermark level */
+static void buffer_event_buffer_low_callback(void *data)
 {
-    if (playing)
-    {
-        /* If we were playing, save resume information */
-        struct mp3entry *id3 = NULL;
+    logf("low buffer callback");
+    LOGFQUEUE("buffering > audio Q_AUDIO_BUFFERING: buffer low");
+    audio_queue_post(Q_AUDIO_BUFFERING, BUFFER_EVENT_BUFFER_LOW);
+    (void)data;
+}
 
-        if (!ci.stop_codec)
-            id3 = audio_current_track();
+/* Called when handles must be discarded in order to buffer new data */
+static void buffer_event_rebuffer_callback(void *data)
+{
+    logf("rebuffer callback");
+    LOGFQUEUE("buffering > audio Q_AUDIO_BUFFERING: rebuffer");
+    audio_queue_post(Q_AUDIO_BUFFERING, BUFFER_EVENT_REBUFFER);
+    (void)data;
+}
 
-        /* Save the current playing spot, or NULL if the playlist has ended */
-        playlist_update_resume_info(id3);
+/* A handle has completed buffering and all required data is available */
+static void buffer_event_finished_callback(void *data)
+{
+    int hid = *(const int *)data;
+    const enum data_type htype = buf_handle_data_type(hid);
 
-        /* Now it's good time to send track finish events.  Do this
-           only if this hasn't been done already as part of a track
-           switch. */
-        if (id3 == thistrack_id3)
-            send_event(PLAYBACK_EVENT_TRACK_FINISH, thistrack_id3);
+    logf("handle %d finished buffering (type:%u)", hid, (unsigned)htype);
 
-        /* TODO: Create auto bookmark too? */
+    /* Limit queue traffic */
+    switch (htype)
+    {
+    case TYPE_ID3:
+        /* The metadata handle for the last loaded track has been buffered.
+           We can ask the audio thread to load the rest of the track's data. */
+        LOGFQUEUE("buffering > audio Q_AUDIO_FINISH_LOAD_TRACK: %d", hid);
+        audio_queue_post(Q_AUDIO_FINISH_LOAD_TRACK, hid);
+        break;
 
-        prev_track_elapsed = othertrack_id3->elapsed;
+    case TYPE_PACKET_AUDIO:
+        /* Strip any useless trailing tags that are left. */
+        strip_tags(hid);
+        /* Fall-through */
+    case TYPE_ATOMIC_AUDIO:
+        LOGFQUEUE("buffering > audio Q_AUDIO_HANDLE_FINISHED: %d", hid);
+        audio_queue_post(Q_AUDIO_HANDLE_FINISHED, hid);
+        break;
 
-        remove_event(BUFFER_EVENT_BUFFER_LOW, buffering_low_buffer_callback);
+    default:
+        /* Don't care to know about these */
+        break;
     }
+}
 
-    audio_stop_codec_flush();
-    paused = false;
-    playing = false;
-    track_load_started = false;
 
-    filling = STATE_IDLE;
+/** -- Codec callbacks -- **/
 
-    /* Mark all entries null. */
-    audio_clear_track_entries();
+/* Update elapsed times with latency-adjusted values */
+void audio_codec_update_elapsed(unsigned long value)
+{
+#ifdef AB_REPEAT_ENABLE
+    ab_position_report(value);
+#endif
 
-    /* Close all tracks */
-    audio_release_tracks();
+    unsigned long latency = pcmbuf_get_latency();
+
+    if (LIKELY(value >= latency))
+    {
+        unsigned long elapsed = value - latency;
+
+        if (elapsed > value || elapsed < value - 2)
+            value = elapsed;
+    }
+    else
+    {
+        value = 0;
+    }
+
+    /* Track codec: used later when updating the playing at the user
+       transition */
+    id3_get(CODEC_ID3)->elapsed = value;
+
+    /* If a skip is pending, the PCM buffer is updating the time on the
+       previous song */
+    if (LIKELY(skip_pending == TRACK_SKIP_NONE))
+        id3_get(PLAYING_ID3)->elapsed = value;
 }
 
-static void audio_play_start(size_t offset)
+/* Update offsets with latency-adjusted values */
+void audio_codec_update_offset(size_t value)
 {
-    int i;
+    struct mp3entry *ci_id3 = id3_get(CODEC_ID3);
+    unsigned long latency = pcmbuf_get_latency() * ci_id3->bitrate / 8;
 
-    send_event(PLAYBACK_EVENT_START_PLAYBACK, NULL);
-#if INPUT_SRC_CAPS != 0
-    audio_set_input_source(AUDIO_SRC_PLAYBACK, SRCF_PLAYBACK);
-    audio_set_output_source(AUDIO_SRC_PLAYBACK);
-#endif
+    if (LIKELY(value >= latency))
+    {
+        value -= latency;
+    }
+    else
+    {
+        value = 0;
+    }
 
-    paused = false;
-    audio_stop_codec_flush();
+    /* Track codec: used later when updating the playing id3 at the user
+       transition */
+    ci_id3->offset = value;
 
-    playing = true;
-    track_load_started = false;
+    /* If a skip is pending, the PCM buffer is updating the time on the
+       previous song */
+    if (LIKELY(skip_pending == TRACK_SKIP_NONE))
+        id3_get(PLAYING_ID3)->offset = value;
+}
 
-    ci.new_track = 0;
-    ci.seek_time = 0;
-    wps_offset = 0;
 
-#ifndef PLATFORM_HAS_VOLUME_CHANGE
-    sound_set_volume(global_settings.volume);
-#endif
-    track_widx = track_ridx = 0;
-    buf_set_base_handle(-1);
+/** --- Pcmbuf callbacks --- **/
 
-    /* Clear all track entries. */
-    for (i = 0; i < MAX_TRACK; i++) {
-        clear_track_info(&tracks[i]);
+/* Between the codec and PCM track change, we need to keep updating the
+ * "elapsed" value of the previous (to the codec, but current to the
+ * user/PCM/WPS) track, so that the progressbar reaches the end. */
+void audio_pcmbuf_position_callback(unsigned int time)
+{
+    struct mp3entry *id3 = id3_get(PLAYING_ID3);
+
+    time += id3->elapsed;
+
+    id3->elapsed = MIN(time, id3->length);
+}
+
+/* Post message from pcmbuf that the end of the previous track has just
+ * been played */
+void audio_pcmbuf_track_change(bool pcmbuf)
+{
+    if (pcmbuf)
+    {
+        /* Notify of the change in special-purpose semaphore object */
+        LOGFQUEUE("pcmbuf > pcmbuf Q_AUDIO_TRACK_CHANGED");
+        audio_pcmbuf_track_change_post();
     }
+    else
+    {
+        /* Safe to post directly to the queue */
+        LOGFQUEUE("pcmbuf > audio Q_AUDIO_TRACK_CHANGED");
+        audio_queue_post(Q_AUDIO_TRACK_CHANGED, 0);
+    }
+}
 
-    last_peek_offset = -1;
+/* May pcmbuf start PCM playback when the buffer is full enough? */
+bool audio_pcmbuf_may_play(void)
+{
+    return play_status == PLAY_PLAYING && !ff_rw_mode;
+}
 
-    /* Officially playing */
-    queue_reply(&audio_queue, 1);
 
-    audio_fill_file_buffer(true, offset);
+/** -- External interfaces -- **/
 
-    add_event(BUFFER_EVENT_BUFFER_LOW, false, buffering_low_buffer_callback);
+/* Return the playback and recording status */
+int audio_status(void)
+{
+    unsigned int ret = play_status;
 
-    LOGFQUEUE("audio > audio Q_AUDIO_TRACK_CHANGED");
-    queue_post(&audio_queue, Q_AUDIO_TRACK_CHANGED, 0);
+#ifdef AUDIO_HAVE_RECORDING
+    /* Do this here for constitency with mpeg.c version */
+    ret |= pcm_rec_status();
+#endif
+
+    return (int)ret;
 }
 
+/* Clear all accumulated audio errors for playback and recording */
+void audio_error_clear(void)
+{
+#ifdef AUDIO_HAVE_RECORDING
+    pcm_rec_error_clear();
+#endif
+}
 
-/* Invalidates all but currently playing track. */
-static void audio_invalidate_tracks(void)
+/* Get a copy of the id3 data for the for current track + offset + skip delta */
+bool audio_peek_track(struct mp3entry *id3, int offset)
 {
-    if (audio_have_tracks())
+    bool retval = false;
+
+    id3_mutex_lock();
+
+    if (play_status != PLAY_STOPPED)
     {
-        last_peek_offset = 0;
-        track_widx = track_ridx;
+        id3->path[0] = '\0'; /* Null path means it should be filled now */
+        retval = audio_get_track_metadata(offset + skip_offset, id3) &&
+                id3->path[0] != '\0';
+    }
 
-        /* Mark all other entries null (also buffered wrong metadata). */
-        audio_clear_track_entries();
+    id3_mutex_unlock();
 
-        track_widx = (track_widx + 1) & MAX_TRACK_MASK;
+    return retval;
+}
 
-        audio_fill_file_buffer(false, 0);
-        send_event(PLAYBACK_EVENT_TRACK_CHANGE, thistrack_id3);
+/* Return the mp3entry for the currently playing track */
+struct mp3entry * audio_current_track(void)
+{
+    struct mp3entry *id3;
+
+    id3_mutex_lock();
+
+#ifdef AUDIO_FAST_SKIP_PREVIEW
+    if (skip_offset != 0)
+    {
+        /* This is a peekahead */
+        id3 = id3_get(PLAYING_PEEK_ID3);
+        audio_peek_track(id3, 0);
     }
+    else
+#endif
+    {
+        /* Normal case */
+        id3 = id3_get(PLAYING_ID3);
+        audio_get_track_metadata(0, id3);
+    }
+
+    id3_mutex_unlock();
+
+    return id3;
 }
 
-static void audio_new_playlist(void)
+/* Obtains the mp3entry for the next track from the current */
+struct mp3entry * audio_next_track(void)
 {
-    /* Prepare to start a new fill from the beginning of the playlist */
-    last_peek_offset = -1;
+    struct mp3entry *id3 = id3_get(NEXTTRACK_ID3);
 
-    /* Signal the codec to initiate a track change forward */
-    new_playlist = true;
-    ci.new_track = 1;
+    id3_mutex_lock();
 
-    if (audio_have_tracks())
+#ifdef AUDIO_FAST_SKIP_PREVIEW
+    if (skip_offset != 0)
     {
-        if (paused)
-            skipped_during_pause = true;
-        track_widx = track_ridx;
-        audio_clear_track_entries();
+        /* This is a peekahead */
+        if (!audio_peek_track(id3, 1))
+            id3 = NULL;
+    }
+    else
+#endif
+    {
+        /* Normal case */
+        if (!audio_get_track_metadata(1, id3))
+            id3 = NULL;
+    }
 
-        track_widx = (track_widx + 1) & MAX_TRACK_MASK;
+    id3_mutex_unlock();
 
-        /* Mark the current track as invalid to prevent skipping back to it */
-        CUR_TI->taginfo_ready = false;
-    }
+    return id3;
+}
 
-    /* Officially playing */
-    queue_reply(&audio_queue, 1);
+/* Start playback at the specified offset */
+void audio_play(long offset)
+{
+    logf("audio_play");
 
-    audio_fill_file_buffer(false, 0);
+#ifdef PLAYBACK_VOICE
+    /* Truncate any existing voice output so we don't have spelling
+     * etc. over the first part of the played track */
+    talk_force_shutup();
+#endif
+
+    LOGFQUEUE("audio >| audio Q_AUDIO_PLAY: %ld", offset);
+    audio_queue_send(Q_AUDIO_PLAY, offset);
 }
 
-/* Called on manual track skip */
-static void audio_initiate_track_change(long direction)
+/* Stop playback if playing */
+void audio_stop(void)
 {
-    logf("audio_initiate_track_change(%ld)", direction);
+    LOGFQUEUE("audio >| audio Q_AUDIO_STOP");
+    audio_queue_send(Q_AUDIO_STOP, 0);
+}
 
-    ci.new_track += direction;
-    wps_offset -= direction;
-    if (paused)
-        skipped_during_pause = true;
+/* Pause playback if playing */
+void audio_pause(void)
+{
+    LOGFQUEUE("audio >| audio Q_AUDIO_PAUSE");
+    audio_queue_send(Q_AUDIO_PAUSE, true);
 }
 
-/* Called on manual dir skip */
-static void audio_initiate_dir_change(long direction)
+/* This sends a stop message and the audio thread will dump all its
+   subsequent messages */
+void audio_hard_stop(void)
 {
-    dir_skip = true;
-    ci.new_track = direction;
-    if (paused)
-        skipped_during_pause = true;
+    /* Stop playback */
+    LOGFQUEUE("audio >| audio Q_AUDIO_STOP: 1");
+    audio_queue_send(Q_AUDIO_STOP, 1);
+#ifdef PLAYBACK_VOICE
+    voice_stop();
+#endif
 }
 
-/* Called when PCM track change is complete */
-static void audio_finalise_track_change(void)
+/* Resume playback if paused */
+void audio_resume(void)
 {
-    logf("audio_finalise_track_change");
+    LOGFQUEUE("audio >| audio Q_AUDIO_PAUSE resume");
+    audio_queue_send(Q_AUDIO_PAUSE, false);
+}
 
-    if (automatic_skip)
+/* Skip the specified number of tracks forward or backward from the current */
+void audio_skip(int offset)
+{
+    id3_mutex_lock();
+
+    /* If offset has to be backed-out to stay in range, no skip is done */
+    int accum = skip_offset + offset;
+
+    while (offset != 0 && !playlist_check(accum))
     {
-        wps_offset = 0;
-        automatic_skip = false;
+        offset += offset < 0 ? 1 : -1;
+        accum = skip_offset + offset;
+    }
 
-        /* Invalidate prevtrack_id3 */
-        memset(othertrack_id3, 0, sizeof(struct mp3entry));
+    if (offset != 0)
+    {
+        /* Accumulate net manual skip count since the audio thread last
+           processed one */
+        skip_offset = accum;
 
-        if (prev_ti && prev_ti->audio_hid < 0)
-        {
-            /* No audio left so we clear all the track info. */
-            clear_track_info(prev_ti);
-        }
+        if (global_settings.beep)
+            pcmbuf_beep(2000, 100, 2500*global_settings.beep);
+
+        LOGFQUEUE("audio > audio Q_AUDIO_SKIP %d", offset);
+
+#ifdef AUDIO_FAST_SKIP_PREVIEW
+        /* Do this before posting so that the audio thread can correct us
+           when things settle down - additionally, if audio gets a message
+           and the delta is zero, the Q_AUDIO_SKIP handler (audio_on_skip)
+           handler a skip event with the correct info but doesn't skip */
+        send_event(PLAYBACK_EVENT_TRACK_SKIP, NULL);
+#endif /* AUDIO_FAST_SKIP_PREVIEW */
+
+        /* Playback only needs the final state even if more than one is
+           processed because it wasn't removed in time */
+        queue_remove_from_head(&audio_queue, Q_AUDIO_SKIP);
+        audio_queue_post(Q_AUDIO_SKIP, 0);
     }
-    send_event(PLAYBACK_EVENT_TRACK_CHANGE, thistrack_id3);
-    playlist_update_resume_info(audio_current_track());
+    else
+    {
+        /* No more tracks */
+        if (global_settings.beep)
+            pcmbuf_beep(1000, 100, 1500*global_settings.beep);
+    }
+
+    id3_mutex_unlock();
 }
 
-static void audio_seek_complete(void)
+/* Skip one track forward from the current */
+void audio_next(void)
 {
-    logf("audio_seek_complete");
+    audio_skip(1);
+}
 
-    if (!playing)
-        return;
+/* Skip one track backward from the current */
+void audio_prev(void)
+{
+    audio_skip(-1);
+}
 
-    /* If seeking-while-playing, pcm_is_paused() is true.
-     * If seeking-while-paused, audio_status PAUSE is true.
-     * A seamless seek skips this section. */
-    ci.seek_time = 0;
+/* Move one directory forward */
+void audio_next_dir(void)
+{
+    LOGFQUEUE("audio > audio Q_AUDIO_DIR_SKIP 1");
+    audio_queue_post(Q_AUDIO_DIR_SKIP, 1);
+}
 
-    pcm_play_lock();
+/* Move one directory backward */
+void audio_prev_dir(void)
+{
+    LOGFQUEUE("audio > audio Q_AUDIO_DIR_SKIP -1");
+    audio_queue_post(Q_AUDIO_DIR_SKIP, -1);
+}
 
-    if (pcm_is_paused() || paused)
-    {
-        /* Clear the buffer */
-        pcmbuf_play_stop();
+/* Pause playback in order to start a seek that flushes the old audio */
+void audio_pre_ff_rewind(void)
+{
+    LOGFQUEUE("audio > audio Q_AUDIO_PRE_FF_REWIND");
+    audio_queue_post(Q_AUDIO_PRE_FF_REWIND, 0);
+}
 
-        /* If seeking-while-playing, resume PCM playback */
-        if (!paused)
-            pcmbuf_pause(false);
-    }
+/* Seek to the new time in the current track */
+void audio_ff_rewind(long time)
+{
+    LOGFQUEUE("audio > audio Q_AUDIO_FF_REWIND");
+    audio_queue_post(Q_AUDIO_FF_REWIND, time);
+}
 
-    pcm_play_unlock();
+/* Clear all but the currently playing track then rebuffer */
+void audio_flush_and_reload_tracks(void)
+{
+    LOGFQUEUE("audio > audio Q_AUDIO_FLUSH");
+    audio_queue_post(Q_AUDIO_FLUSH, 0);
 }
 
-static void audio_codec_status_message(long reason, int status)
+/* Return the pointer to the main audio buffer, optionally preserving
+   voicing */
+unsigned char * audio_get_buffer(bool talk_buf, size_t *buffer_size)
 {
-    /* TODO: Push the errors up to the normal UI somewhere */
-    switch (reason)
+    unsigned char *buf, *end;
+
+    if (audio_is_initialized)
     {
-    case Q_CODEC_LOAD_DISK:
-    case Q_CODEC_LOAD:
-        if (!playing)
-            return;
+        audio_hard_stop();
+    }
+    /* else buffer_state will be AUDIOBUF_STATE_TRASHED at this point */
 
-        if (status < 0)
+    if (buffer_size == NULL)
+    {
+        /* Special case for talk_init to use since it already knows it's
+           trashed */
+        buffer_state = AUDIOBUF_STATE_TRASHED;
+        return NULL;
+    }
+
+    if (talk_buf || buffer_state == AUDIOBUF_STATE_TRASHED
+           || !talk_voice_required())
+    {
+        logf("get buffer: talk, audio");
+        /* Ok to use everything from audiobuf to audiobufend - voice is loaded,
+           the talk buffer is not needed because voice isn't being used, or
+           could be AUDIOBUF_STATE_TRASHED already. If state is
+           AUDIOBUF_STATE_VOICED_ONLY, no problem as long as memory isn't written
+           without the caller knowing what's going on. Changing certain settings
+           may move it to a worse condition but the memory in use by something
+           else will remain undisturbed.
+         */
+        if (buffer_state != AUDIOBUF_STATE_TRASHED)
         {
-            splash(HZ*2, "Codec failure");
-            audio_check_new_track();
+            talk_buffer_steal();
+            buffer_state = AUDIOBUF_STATE_TRASHED;
         }
-        break;
 
-#ifdef AUDIO_HAVE_RECORDING
-    case Q_ENCODER_LOAD_DISK:
-        if (status < 0)
-            splash(HZ*2, "Encoder failure");
-        break;
-#endif /* AUDIO_HAVE_RECORDING */
+        buf = audiobuf;
+        end = audiobufend;
     }
+    else
+    {
+        /* Safe to just return this if already AUDIOBUF_STATE_VOICED_ONLY or
+           still AUDIOBUF_STATE_INITIALIZED */
+        /* Skip talk buffer and move pcm buffer to end to maximize available
+           contiguous memory - no audio running means voice will not need the
+           swap space */
+        logf("get buffer: audio");
+        buf = audiobuf + talk_get_bufsize();
+        end = audiobufend - pcmbuf_init(audiobufend);
+        buffer_state = AUDIOBUF_STATE_VOICED_ONLY;
+    }
+
+    *buffer_size = end - buf;
+
+    return buf;
 }
 
-/*
- * Layout audio buffer as follows - iram buffer depends on target:
- * [|SWAP:iram][|TALK]|FILE|GUARD|PCM|[SWAP:dram[|iram]|]
- */
-static void audio_reset_buffer(void)
+#ifdef HAVE_RECORDING
+/* Stop audio, voice and obtain all available buffer space */
+unsigned char * audio_get_recording_buffer(size_t *buffer_size)
 {
-    /* see audio_get_recording_buffer if this is modified */
-    logf("audio_reset_buffer");
+    audio_hard_stop();
+    talk_buffer_steal();
 
-    /* If the setup of anything allocated before the file buffer is
-       changed, do check the adjustments after the buffer_alloc call
-       as it will likely be affected and need sliding over */
+    unsigned char *end = audiobufend;
+    buffer_state = AUDIOBUF_STATE_TRASHED;
+    *buffer_size = end - audiobuf;
 
-    /* Initially set up file buffer as all space available */
-    filebuf = audiobuf + talk_get_bufsize();
-    filebuflen = audiobufend - filebuf;
+    return (unsigned char *)audiobuf;
+}
+#endif /* HAVE_RECORDING */
 
-    ALIGN_BUFFER(filebuf, filebuflen, sizeof (intptr_t));
+/* Restore audio buffer to a particular state (one more valid than the current
+   state) */
+bool audio_restore_playback(int type)
+{
+    switch (type)
+    {
+    case AUDIO_WANT_PLAYBACK:
+        if (buffer_state != AUDIOBUF_STATE_INITIALIZED)
+            audio_reset_buffer();
+        return true;
+    case AUDIO_WANT_VOICE:
+        if (buffer_state == AUDIOBUF_STATE_TRASHED)
+            audio_reset_buffer();
+        return true;
+    default:
+        return false;
+    }
+}
 
-    /* Subtract whatever the pcm buffer says it used plus the guard buffer */
-    size_t pcmbuf_size = pcmbuf_init(filebuf + filebuflen) + GUARD_BUFSIZE;
+/* Has the playback buffer been completely claimed? */
+bool audio_buffer_state_trashed(void)
+{
+    return buffer_state == AUDIOBUF_STATE_TRASHED;
+}
 
-    /* Make sure filebuflen is a pointer sized multiple after adjustment */
-    pcmbuf_size = ALIGN_UP(pcmbuf_size, sizeof (intptr_t));
 
-    if(pcmbuf_size > filebuflen)
-        panicf("%s(): EOM (%zu > %zu)", __func__, pcmbuf_size, filebuflen);
+/** --- Miscellaneous public interfaces --- **/
 
-    filebuflen -= pcmbuf_size;
-    buffering_reset(filebuf, filebuflen);
+#ifdef HAVE_ALBUMART
+/* Return which album art handle is current for the user in the given slot */
+int playback_current_aa_hid(int slot)
+{
+    if ((unsigned)slot < MAX_MULTIPLE_AA)
+    {
+        struct track_info *info = track_list_user_current(skip_offset);
 
-    /* Clear any references to the file buffer */
-    buffer_state = AUDIOBUF_STATE_INITIALIZED;
+        if (!info && abs(skip_offset) <= 1)
+        {
+            /* Give the actual position a go */
+            info = track_list_user_current(0);
+        }
 
-#if defined(ROCKBOX_HAS_LOGF) && defined(LOGF_ENABLE)
-    /* Make sure everything adds up - yes, some info is a bit redundant but
-       aids viewing and the sumation of certain variables should add up to
-       the location of others. */
-    {
-        size_t pcmbufsize;
-        const unsigned char *pcmbuf = pcmbuf_get_meminfo(&pcmbufsize);
-        logf("fbuf:   %08X", (unsigned)filebuf);
-        logf("fbufe:  %08X", (unsigned)(filebuf + filebuflen));
-        logf("gbuf:   %08X", (unsigned)(filebuf + filebuflen));
-        logf("gbufe:  %08X", (unsigned)(filebuf + filebuflen + GUARD_BUFSIZE));
-        logf("pcmb:   %08X", (unsigned)pcmbuf);
-        logf("pcmbe:  %08X", (unsigned)(pcmbuf + pcmbufsize));
+        if (info)
+            return info->aa_hid[slot];
     }
-#endif
+
+    return ERR_HANDLE_NOT_FOUND;
 }
 
-static void audio_thread(void)
+/* Find an album art slot that doesn't match the dimensions of another that
+   is already claimed - increment the use count if it is */
+int playback_claim_aa_slot(struct dim *dim)
 {
-    struct queue_event ev;
+    int i;
 
-    pcm_postinit();
+    /* First try to find a slot already having the size to reuse it since we
+       don't want albumart of the same size buffered multiple times */
+    FOREACH_ALBUMART(i)
+    {
+        struct albumart_slot *slot = &albumart_slots[i];
 
-    audio_thread_ready = true;
+        if (slot->dim.width == dim->width &&
+            slot->dim.height == dim->height)
+        {
+            slot->used++;
+            return i;
+        }
+    }
 
-    while (1)
+    /* Size is new, find a free slot */
+    FOREACH_ALBUMART(i)
     {
-        switch (filling) {
-            case STATE_IDLE:
-                queue_wait(&audio_queue, &ev);
-                break;
-
-#if (CONFIG_PLATFORM & PLATFORM_NATIVE)
-            case STATE_USB:
-                queue_wait(&audio_queue, &ev);
-                switch (ev.id) {
-#ifdef AUDIO_HAVE_RECORDING
-                    /* Must monitor the encoder message for recording so it can
-                       remove it if we process the insertion before it does. It
-                       cannot simply be removed from under recording however. */
-                    case Q_AUDIO_LOAD_ENCODER:
-                        break;
-#endif
-                    case SYS_USB_DISCONNECTED:
-                        filling = STATE_IDLE;
-                    default:
-                        continue;
-                }
-                break;
-#endif /* CONFIG_PLATFORM */
-
-            default:
-                /* End of buffering, let's calculate the watermark and
-                   unboost */
-                set_filebuf_watermark();
-                cancel_cpu_boost();
-                /* Fall-through */
-            case STATE_FILLING:
-            case STATE_ENDING:
-                if (!pcmbuf_queue_scan(&ev))
-                    queue_wait_w_tmo(&audio_queue, &ev, HZ/2);
-                break;
+        if (!albumart_slots[i].used)
+        {
+            albumart_slots[i].used++;
+            albumart_slots[i].dim = *dim;
+            return i;
         }
+    }
 
-        switch (ev.id) {
+    /* Sorry, no free slot */
+    return -1;
+}
 
-            case Q_AUDIO_FILL_BUFFER:
-                LOGFQUEUE("audio < Q_AUDIO_FILL_BUFFER %d", (int)ev.data);
-                audio_fill_file_buffer((bool)ev.data, 0);
-                break;
+/* Invalidate the albumart_slot - decrement the use count if > 0 */
+void playback_release_aa_slot(int slot)
+{
+    if ((unsigned)slot < MAX_MULTIPLE_AA)
+    {
+        struct albumart_slot *aa_slot = &albumart_slots[slot];
 
-            case Q_AUDIO_FINISH_LOAD:
-                LOGFQUEUE("audio < Q_AUDIO_FINISH_LOAD");
-                audio_finish_load_track();
-                buf_set_base_handle(CUR_TI->audio_hid);
-                break;
+        if (aa_slot->used > 0)
+            aa_slot->used--;
+    }
+}
+#endif /* HAVE_ALBUMART */
 
-            case Q_AUDIO_PLAY:
-                LOGFQUEUE("audio < Q_AUDIO_PLAY");
-                if (playing && ev.data <= 0)
-                    audio_new_playlist();
-                else
-                {
-                    audio_stop_playback();
-                    audio_play_start((size_t)ev.data);
-                }
-                break;
 
-            case Q_AUDIO_STOP:
-                LOGFQUEUE("audio < Q_AUDIO_STOP");
-                if (playing)
-                    audio_stop_playback();
-                if (ev.data != 0)
-                    queue_clear(&audio_queue);
-                break;
+#ifdef HAVE_RECORDING
+/* Load an encoder and run it */
+bool audio_load_encoder(int afmt)
+{
+#if (CONFIG_PLATFORM & PLATFORM_NATIVE)
+    LOGFQUEUE("audio >| Q_AUDIO_LOAD_ENCODER: %d", afmt);
+    return audio_queue_send(Q_AUDIO_LOAD_ENCODER, afmt) != 0;
+#else
+    (void)afmt;
+    return true;
+#endif
+}
 
-            case Q_AUDIO_PAUSE:
-                LOGFQUEUE("audio < Q_AUDIO_PAUSE");
-                if (!(bool) ev.data && skipped_during_pause
-#ifdef HAVE_CROSSFADE
-                    && !pcmbuf_is_crossfade_active()
+/* Stop an encoder and unload it */
+void audio_remove_encoder(void)
+{
+#if (CONFIG_PLATFORM & PLATFORM_NATIVE)
+    LOGFQUEUE("audio >| Q_AUDIO_LOAD_ENCODER: NULL");
+    audio_queue_send(Q_AUDIO_LOAD_ENCODER, AFMT_UNKNOWN);
 #endif
-                    )
-                    pcmbuf_play_stop(); /* Flush old track on resume after skip */
-                skipped_during_pause = false;
-                if (!playing)
-                    break;
-                pcmbuf_pause((bool)ev.data);
-                paused = (bool)ev.data;
-                break;
+}
+#endif /* HAVE_RECORDING */
 
-            case Q_AUDIO_SKIP:
-                LOGFQUEUE("audio < Q_AUDIO_SKIP");
-                audio_initiate_track_change((long)ev.data);
-                break;
+/* Is an automatic skip in progress? If called outside transistion callbacks,
+   indicates the last skip type at the time it was processed and isn't very
+   meaningful. */
+bool audio_automatic_skip(void)
+{
+    return automatic_skip;
+}
 
-            case Q_AUDIO_PRE_FF_REWIND:
-                LOGFQUEUE("audio < Q_AUDIO_PRE_FF_REWIND");
-                if (!playing)
-                    break;
-                pcmbuf_pause(true);
-                break;
+/* Would normally calculate byte offset from an elapsed time but is not
+   used on SWCODEC */
+int audio_get_file_pos(void)
+{
+    return 0;
+}
 
-            case Q_AUDIO_FF_REWIND:
-                LOGFQUEUE("audio < Q_AUDIO_FF_REWIND");
-                if (!playing)
-                    break;
+/* Return the elasped time of the track previous to the current */
+unsigned long audio_prev_elapsed(void)
+{
+    return prev_track_elapsed;
+}
 
-                if (filling == STATE_ENDING)
-                {
-                    /* Temp workaround: There is no codec available */
-                    if (!paused)
-                        pcmbuf_pause(false);
-                    break;
-                }
+/* Is the audio thread ready to accept commands? */
+bool audio_is_thread_ready(void)
+{
+    return filling != STATE_BOOT;
+}
 
-                if ((long)ev.data == 0)
-                {
-                    /* About to restart the track - send track finish
-                       events if not already done. */
-                    if (thistrack_id3 == audio_current_track())
-                        send_event(PLAYBACK_EVENT_TRACK_FINISH, thistrack_id3);
-                }
+/* Return total file buffer length after accounting for the talk buf */
+size_t audio_get_filebuflen(void)
+{
+    return buf_length();
+}
 
-                if (automatic_skip)
-                {
-                    /* An automatic track skip is in progress. Finalize it,
-                       then go back to the previous track */
-                    audio_finalise_track_change();
-                    ci.new_track = -1;
-                }
-                ci.seek_time = (long)ev.data+1;
-                break;
+/* How many tracks exist on the buffer - full or partial */
+int audio_track_count(void)
+    __attribute__((alias("track_list_count")));
 
-            case Q_AUDIO_CHECK_NEW_TRACK:
-                LOGFQUEUE("audio < Q_AUDIO_CHECK_NEW_TRACK");
-                audio_check_new_track();
-                break;
+/* Return total ringbuffer space occupied - ridx to widx */
+long audio_filebufused(void)
+{
+    return buf_used();
+}
 
-            case Q_AUDIO_DIR_SKIP:
-                LOGFQUEUE("audio < Q_AUDIO_DIR_SKIP");
-                audio_initiate_dir_change(ev.data);
-                break;
 
-            case Q_AUDIO_FLUSH:
-                LOGFQUEUE("audio < Q_AUDIO_FLUSH");
-                audio_invalidate_tracks();
-                break;
+/** -- Settings -- **/
 
-            case Q_AUDIO_TRACK_CHANGED:
-                /* PCM track change done */
-                LOGFQUEUE("audio < Q_AUDIO_TRACK_CHANGED");
-                /* Set new playlist position for resuming. */
-                playlist_update_resume_index();
-                if (filling != STATE_ENDING)
-                    audio_finalise_track_change();
-                else if (playing)
-                    audio_stop_playback();
-                break;
+/* Enable or disable cuesheet support and allocate/don't allocate the
+   extra associated resources */
+void audio_set_cuesheet(int enable)
+{
+    if (play_status == PLAY_STOPPED || !enable != !get_current_cuesheet())
+    {
+        LOGFQUEUE("audio >| audio Q_AUDIO_REMAKE_AUDIO_BUFFER");
+        audio_queue_send(Q_AUDIO_REMAKE_AUDIO_BUFFER, 0);
+    }
+}
 
-            case Q_AUDIO_SEEK_COMPLETE:
-                /* Codec seek done */
-                LOGFQUEUE("audio < Q_AUDIO_SEEK_COMPLETE");
-                audio_seek_complete();
-                codec_ack_msg(Q_AUDIO_SEEK_COMPLETE, false);
-                break;
+#ifdef HAVE_DISK_STORAGE
+/* Set the audio antiskip buffer margin by index */
+void audio_set_buffer_margin(int setting)
+{
+    static const unsigned short lookup[] =
+        { 5, 15, 30, 60, 120, 180, 300, 600 };
 
-            case Q_CODEC_LOAD:
-            case Q_CODEC_LOAD_DISK:
-#ifdef AUDIO_HAVE_RECORDING
-            case Q_ENCODER_LOAD_DISK:
-#endif
-                /* These are received when a codec has finished normally or
-                   upon a codec error */
-                audio_codec_status_message(ev.id, ev.data);
-                break;
+    if ((unsigned)setting >= ARRAYLEN(lookup))
+        setting = 0;
 
-#if (CONFIG_PLATFORM & PLATFORM_NATIVE)
-            case SYS_USB_CONNECTED:
-                LOGFQUEUE("audio < SYS_USB_CONNECTED");
-                if (playing)
-                    audio_stop_playback();
-#ifdef PLAYBACK_VOICE
-                voice_stop();
-#endif
-                filling = STATE_USB;
-                usb_acknowledge(SYS_USB_CONNECTED_ACK);
-                break;
-#endif
+    logf("buffer margin: %u", (unsigned)lookup[setting]);
 
-#ifdef AUDIO_HAVE_RECORDING
-            case Q_AUDIO_LOAD_ENCODER:
-                if (playing)
-                    audio_stop_playback();
-                else
-                    codec_stop(); /* If encoder still loaded, stop it */
+    LOGFQUEUE("audio > audio Q_AUDIO_UPDATE_WATERMARK: %u",
+              (unsigned)lookup[setting]);
+    audio_queue_post(Q_AUDIO_UPDATE_WATERMARK, lookup[setting]);
+}
+#endif /* HAVE_DISK_STORAGE */
 
-                if (ev.data == AFMT_UNKNOWN)
-                    break;
+#ifdef HAVE_CROSSFADE
+/* Take necessary steps to enable or disable the crossfade setting */
+void audio_set_crossfade(int enable)
+{
+    /* Tell it the next setting to use */
+    pcmbuf_request_crossfade_enable(enable);
 
-                queue_reply(&audio_queue,
-                            codec_load(-1, ev.data | CODEC_TYPE_ENCODER));
-                break;
-#endif /* AUDIO_HAVE_RECORDING */
+    /* Return if size hasn't changed or this is too early to determine
+       which in the second case there's no way we could be playing
+       anything at all */
+    if (!pcmbuf_is_same_size())
+    {
+        LOGFQUEUE("audio >| audio Q_AUDIO_REMAKE_AUDIO_BUFFER");
+        audio_queue_send(Q_AUDIO_REMAKE_AUDIO_BUFFER, 0);
+    }
+}
+#endif /* HAVE_CROSSFADE */
 
-            case SYS_TIMEOUT:
-                LOGFQUEUE_SYS_TIMEOUT("audio < SYS_TIMEOUT");
-                break;
 
-            default:
-                /* LOGFQUEUE("audio < default : %08lX", ev.id); */
-                break;
-        } /* end switch */
-    } /* end while */
-}
+/** -- Startup -- **/
 
-/* Initialize the audio system - called from init() in main.c.
- * Last function because of all the references to internal symbols
- */
+/* Initialize the audio system - called from init() in main.c */
 void audio_init(void)
 {
-    unsigned int audio_thread_id;
-
     /* Can never do this twice */
     if (audio_is_initialized)
     {
@@ -2290,31 +3646,20 @@
        to send messages. Thread creation will be delayed however so nothing
        starts running until ready if something yields such as talk_init. */
     queue_init(&audio_queue, true);
-    queue_init(&pcmbuf_queue, false);
 
+    mutex_init(&id3_mutex);
+
     pcm_init();
 
     codec_init_codec_api();
     
-    thistrack_id3 = &mp3entry_buf[0];
-    othertrack_id3 = &mp3entry_buf[1];
-    
-    /* cuesheet support */
-    if (global_settings.cuesheet)
-        curr_cue = (struct cuesheet*)buffer_alloc(sizeof(struct cuesheet));
-    
-    /* initialize the buffer */
-    filebuf = audiobuf;
-
-    /* audio_reset_buffer must to know the size of voice buffer so init
-       talk first */
-    talk_init();
-
     make_codec_thread();
 
+    /* This thread does buffer, so match its priority */
     audio_thread_id = create_thread(audio_thread, audio_stack,
                   sizeof(audio_stack), CREATE_THREAD_FROZEN,
-                  audio_thread_name IF_PRIO(, PRIORITY_USER_INTERFACE)
+                  audio_thread_name
+                  IF_PRIO(, MIN(PRIORITY_BUFFERING, PRIORITY_USER_INTERFACE))
                   IF_COP(, CPU));
 
     queue_enable_queue_send(&audio_queue, &audio_queue_sender_list,
@@ -2324,39 +3669,21 @@
     voice_thread_init();
 #endif
 
+    /* audio_reset_buffer must to know the size of voice buffer so init
+       talk first */
+    talk_init();
+
 #ifdef HAVE_CROSSFADE
     /* Set crossfade setting for next buffer init which should be about... */
     pcmbuf_request_crossfade_enable(global_settings.crossfade);
 #endif
 
-    /* initialize the buffering system */
-
+    /* Initialize the buffering system */
+    track_list_init();
     buffering_init();
     /* ...now! Set up the buffers */
     audio_reset_buffer();
 
-    int i;
-    for(i = 0; i < MAX_TRACK; i++)
-    {
-        tracks[i].audio_hid = -1;
-        tracks[i].id3_hid = -1;
-        tracks[i].codec_hid = -1;
-        tracks[i].cuesheet_hid = -1;
-    }
-#ifdef HAVE_ALBUMART
-    FOREACH_ALBUMART(i)
-    {
-        int j;
-        for (j = 0; j < MAX_TRACK; j++)
-        {
-            tracks[j].aa_hid[i] = -1;
-        }
-    }
-#endif
-
-    add_event(BUFFER_EVENT_REBUFFER, false, buffering_handle_rebuffer_callback);
-    add_event(BUFFER_EVENT_FINISHED, false, buffering_handle_finished_callback);
-
     /* Probably safe to say */
     audio_is_initialized = true;
 
@@ -2365,26 +3692,10 @@
     audio_set_buffer_margin(global_settings.buffer_margin);
 #endif
 
-    /* it's safe to let the threads run now */
+    /* It's safe to let the threads run now */
 #ifdef PLAYBACK_VOICE
     voice_thread_resume();
 #endif
     codec_thread_resume();
     thread_thaw(audio_thread_id);
-
-} /* audio_init */
-
-bool audio_is_thread_ready(void)
-{
-    return audio_thread_ready;
 }
-
-size_t audio_get_filebuflen(void)
-{
-    return filebuflen;
-}
-
-int get_audio_hid()
-{
-    return CUR_TI->audio_hid;
-}
Index: apps/playback.h
===================================================================
--- apps/playback.h	(revision 29752)
+++ apps/playback.h	(working copy)
@@ -26,6 +26,16 @@
 #include <stdlib.h>
 #include "config.h"
 
+#if CONFIG_CODEC == SWCODEC
+/* Including the code for fast previews is entirely optional since it
+   does add two more mp3entry's - for certain targets it may be less
+   beneficial such as flash-only storage */
+#if MEMORYSIZE > 2
+#define AUDIO_FAST_SKIP_PREVIEW
+#endif
+
+#endif /* CONFIG_CODEC == SWCODEC */
+
 #ifdef HAVE_ALBUMART
 
 #include "bmp.h"
@@ -60,13 +70,14 @@
 #endif
 
 /* Functions */
-void voice_wait(void);
 bool audio_is_thread_ready(void);
 int audio_track_count(void);
 long audio_filebufused(void);
 void audio_pre_ff_rewind(void);
 void audio_skip(int direction);
 void audio_hard_stop(void); /* Stops audio from serving playback */
+
+void audio_set_cuesheet(int enable);
 #ifdef HAVE_CROSSFADE
 void audio_set_crossfade(int enable);
 #endif
@@ -78,11 +89,10 @@
 };
 bool audio_restore_playback(int type); /* Restores the audio buffer to handle the requested playback */
 size_t audio_get_filebuflen(void);
-void audio_pcmbuf_position_callback(unsigned int time) ICODE_ATTR;
-void audio_post_track_change(bool pcmbuf);
-int get_audio_hid(void);
-void audio_set_prev_elapsed(unsigned long setting);
 bool audio_buffer_state_trashed(void);
+
+/* Automatic transition? Only valid to call during the track change events,
+   otherwise the result is undefined. */
 bool audio_automatic_skip(void);
 
 /* Define one constant that includes recording related functionality */
@@ -91,35 +101,62 @@
 #endif
 
 enum {
-    Q_NULL = 0,
+    Q_NULL = 0,                 /* reserved */
+
+    /* -> audio */
     Q_AUDIO_PLAY = 1,
     Q_AUDIO_STOP,
     Q_AUDIO_PAUSE,
     Q_AUDIO_SKIP,
     Q_AUDIO_PRE_FF_REWIND,
     Q_AUDIO_FF_REWIND,
-    Q_AUDIO_CHECK_NEW_TRACK,
     Q_AUDIO_FLUSH,
-    Q_AUDIO_TRACK_CHANGED,
-    Q_AUDIO_SEEK_COMPLETE,
     Q_AUDIO_DIR_SKIP,
-    Q_AUDIO_POSTINIT,
-    Q_AUDIO_FILL_BUFFER,
-    Q_AUDIO_FINISH_LOAD,
-    Q_CODEC_REQUEST_COMPLETE,
-    Q_CODEC_REQUEST_FAILED,
 
+    /* pcmbuf -> audio */
+    Q_AUDIO_TRACK_CHANGED,
+
+    /* audio -> audio */
+    Q_AUDIO_FILL_BUFFER,        /* continue buffering next track */
+
+    /* buffering -> audio */
+    Q_AUDIO_BUFFERING,          /* some buffer event */
+    Q_AUDIO_FINISH_LOAD_TRACK,  /* metadata is buffered */
+    Q_AUDIO_HANDLE_FINISHED,    /* some other type is buffered */
+
+    /* codec -> audio (*) */
+    Q_AUDIO_CODEC_SEEK_COMPLETE,
+    Q_AUDIO_CODEC_COMPLETE,
+
+    /* audio -> codec */
     Q_CODEC_LOAD,
-    Q_CODEC_LOAD_DISK,
+    Q_CODEC_RUN,
+    Q_CODEC_PAUSE,
+    Q_CODEC_SEEK,
+    Q_CODEC_STOP,
+    Q_CODEC_UNLOAD,
 
+
+    /*- miscellanous -*/
 #ifdef AUDIO_HAVE_RECORDING
-    Q_AUDIO_LOAD_ENCODER,
-    Q_ENCODER_LOAD_DISK,
-    Q_ENCODER_RECORD,
+    /* -> codec */
+    Q_AUDIO_LOAD_ENCODER,       /* load an encoder for recording */
 #endif
+    /* -> codec */
+    Q_CODEC_DO_CALLBACK,
 
-    Q_CODEC_DO_CALLBACK,
-    Q_CODEC_ACK,
+
+    /*- settings -*/
+
+#ifdef HAVE_DISK_STORAGE
+    /* -> audio */
+    Q_AUDIO_UPDATE_WATERMARK,   /* buffering watermark needs updating */
+#endif
+    /* -> audio */
+    Q_AUDIO_REMAKE_AUDIO_BUFFER, /* buffer needs to be reinitialized */
 };
 
-#endif
+/* (*) If you change these, you must check audio_clear_track_notifications
+       in playback.c for correctness */
+
+#endif /* _PLAYBACK_H */
