remove svn:executable
[kugel-rb.git] / apps / playback.c
blob7b614cd0d092f1224644151a552b59865964cf76
1 /***************************************************************************
2 * __________ __ ___.
3 * Open \______ \ ____ ____ | | _\_ |__ _______ ___
4 * Source | _// _ \_/ ___\| |/ /| __ \ / _ \ \/ /
5 * Jukebox | | ( <_> ) \___| < | \_\ ( <_> > < <
6 * Firmware |____|_ /\____/ \___ >__|_ \|___ /\____/__/\_ \
7 * \/ \/ \/ \/ \/
8 * $Id$
10 * Copyright (C) 2005-2007 Miika Pekkarinen
11 * Copyright (C) 2007-2008 Nicolas Pennequin
13 * This program is free software; you can redistribute it and/or
14 * modify it under the terms of the GNU General Public License
15 * as published by the Free Software Foundation; either version 2
16 * of the License, or (at your option) any later version.
18 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
19 * KIND, either express or implied.
21 ****************************************************************************/
23 /* TODO: Pause should be handled in here, rather than PCMBUF so that voice can
24 * play whilst audio is paused */
26 #include <stdio.h>
27 #include <string.h>
28 #include <stdlib.h>
29 #include <ctype.h>
31 #include "system.h"
32 #include "thread.h"
33 #include "file.h"
34 #include "panic.h"
35 #include "memory.h"
36 #include "lcd.h"
37 #include "font.h"
38 #include "button.h"
39 #include "kernel.h"
40 #include "tree.h"
41 #include "debug.h"
42 #include "sprintf.h"
43 #include "settings.h"
44 #include "codecs.h"
45 #include "audio.h"
46 #include "buffering.h"
47 #include "appevents.h"
48 #include "voice_thread.h"
49 #include "mp3_playback.h"
50 #include "usb.h"
51 #include "storage.h"
52 #include "screens.h"
53 #include "playlist.h"
54 #include "playback.h"
55 #include "pcmbuf.h"
56 #include "buffer.h"
57 #include "dsp.h"
58 #include "abrepeat.h"
59 #include "cuesheet.h"
60 #ifdef HAVE_TAGCACHE
61 #include "tagcache.h"
62 #endif
63 #ifdef HAVE_LCD_BITMAP
64 #include "icons.h"
65 #include "peakmeter.h"
66 #include "action.h"
67 #ifdef HAVE_ALBUMART
68 #include "albumart.h"
69 #include "bmp.h"
70 #endif
71 #endif
72 #include "lang.h"
73 #include "misc.h"
74 #include "sound.h"
75 #include "metadata.h"
76 #include "splash.h"
77 #include "talk.h"
78 #include "ata_idle_notify.h"
80 #ifdef HAVE_RECORDING
81 #include "recording.h"
82 #include "pcm_record.h"
83 #endif
85 #ifdef IPOD_ACCESSORY_PROTOCOL
86 #include "iap.h"
87 #endif
89 #define PLAYBACK_VOICE
91 /* amount of guess-space to allow for codecs that must hunt and peck
92 * for their correct seeek target, 32k seems a good size */
93 #define AUDIO_REBUFFER_GUESS_SIZE (1024*32)
95 /* Define LOGF_ENABLE to enable logf output in this file */
96 /*#define LOGF_ENABLE*/
97 #include "logf.h"
99 /* macros to enable logf for queues
100 logging on SYS_TIMEOUT can be disabled */
101 #ifdef SIMULATOR
102 /* Define this for logf output of all queuing except SYS_TIMEOUT */
103 #define PLAYBACK_LOGQUEUES
104 /* Define this to logf SYS_TIMEOUT messages */
105 /*#define PLAYBACK_LOGQUEUES_SYS_TIMEOUT*/
106 #endif
108 #ifdef PLAYBACK_LOGQUEUES
109 #define LOGFQUEUE logf
110 #else
111 #define LOGFQUEUE(...)
112 #endif
114 #ifdef PLAYBACK_LOGQUEUES_SYS_TIMEOUT
115 #define LOGFQUEUE_SYS_TIMEOUT logf
116 #else
117 #define LOGFQUEUE_SYS_TIMEOUT(...)
118 #endif
121 /* Define one constant that includes recording related functionality */
122 #if defined(HAVE_RECORDING) && !defined(SIMULATOR)
123 #define AUDIO_HAVE_RECORDING
124 #endif
126 enum {
127 Q_NULL = 0,
128 Q_AUDIO_PLAY = 1,
129 Q_AUDIO_STOP,
130 Q_AUDIO_PAUSE,
131 Q_AUDIO_SKIP,
132 Q_AUDIO_PRE_FF_REWIND,
133 Q_AUDIO_FF_REWIND,
134 Q_AUDIO_CHECK_NEW_TRACK,
135 Q_AUDIO_FLUSH,
136 Q_AUDIO_TRACK_CHANGED,
137 Q_AUDIO_DIR_SKIP,
138 Q_AUDIO_POSTINIT,
139 Q_AUDIO_FILL_BUFFER,
140 Q_AUDIO_FINISH_LOAD,
141 Q_CODEC_REQUEST_COMPLETE,
142 Q_CODEC_REQUEST_FAILED,
144 Q_CODEC_LOAD,
145 Q_CODEC_LOAD_DISK,
147 #ifdef AUDIO_HAVE_RECORDING
148 Q_ENCODER_LOAD_DISK,
149 Q_ENCODER_RECORD,
150 #endif
152 Q_CODEC_DO_CALLBACK,
155 enum filling_state {
156 STATE_IDLE, /* audio is stopped: nothing to do */
157 STATE_FILLING, /* adding tracks to the buffer */
158 STATE_FULL, /* can't add any more tracks */
159 STATE_END_OF_PLAYLIST, /* all remaining tracks have been added */
160 STATE_FINISHED, /* all remaining tracks are fully buffered */
163 #define MAX_TRACK 128
164 #define MAX_MULTIPLE_AA 2
166 #define MAX_TRACK_MASK (MAX_TRACK-1)
168 /* As defined in plugins/lib/xxx2wav.h */
169 #define GUARD_BUFSIZE (32*1024)
171 bool audio_is_initialized = false;
172 static bool audio_thread_ready SHAREDBSS_ATTR = false;
174 /* Variables are commented with the threads that use them: *
175 * A=audio, C=codec, V=voice. A suffix of - indicates that *
176 * the variable is read but not updated on that thread. */
177 /* TBD: Split out "audio" and "playback" (ie. calling) threads */
179 /* Main state control */
180 static volatile bool audio_codec_loaded SHAREDBSS_ATTR = false; /* Codec loaded? (C/A-) */
181 static volatile bool playing SHAREDBSS_ATTR = false; /* Is audio playing? (A) */
182 static volatile bool paused SHAREDBSS_ATTR = false; /* Is audio paused? (A/C-) */
184 /* Ring buffer where compressed audio and codecs are loaded */
185 static unsigned char *filebuf = NULL; /* Start of buffer (A/C-) */
186 static unsigned char *malloc_buf = NULL; /* Start of malloc buffer (A/C-) */
187 /* FIXME: make filebuflen static */
188 size_t filebuflen = 0; /* Size of buffer (A/C-) */
189 /* FIXME: make buf_ridx (C/A-) */
191 /* Possible arrangements of the buffer */
192 static int buffer_state = AUDIOBUF_STATE_TRASHED; /* Buffer state */
194 /* These are used to store the current and next (or prev if the current is the last)
195 * mp3entry's in a round-robin system. This guarentees that the pointer returned
196 * by audio_current/next_track will be valid for the full duration of the
197 * currently playing track */
198 static struct mp3entry mp3entry_buf[2];
199 static struct mp3entry *thistrack_id3, /* the currently playing track */
200 *othertrack_id3; /* prev track during track-change-transition, or end of playlist,
201 * next track otherwise */
202 static struct mp3entry unbuffered_id3; /* the id3 for the first unbuffered track */
204 /* for cuesheet support */
205 static struct cuesheet *curr_cue = NULL;
207 /* Track info structure about songs in the file buffer (A/C-) */
208 struct track_info {
209 int audio_hid; /* The ID for the track's buffer handle */
210 int id3_hid; /* The ID for the track's metadata handle */
211 int codec_hid; /* The ID for the track's codec handle */
212 #ifdef HAVE_ALBUMART
213 int aa_hid[MAX_MULTIPLE_AA];/* The ID for the track's album art handle */
214 #endif
215 int cuesheet_hid; /* The ID for the track's parsed cueesheet handle */
217 size_t filesize; /* File total length */
219 bool taginfo_ready; /* Is metadata read */
223 #ifdef HAVE_ALBUMART
224 struct albumart_slot {
225 struct dim dim; /* holds width, height of the albumart */
226 int used; /* counter, increments if something uses it */
227 } albumart_slots[MAX_MULTIPLE_AA];
229 #define FOREACH_ALBUMART(i) for(i = 0;i < MAX_MULTIPLE_AA; i++)
230 #endif
232 static struct track_info tracks[MAX_TRACK];
233 static volatile int track_ridx = 0; /* Track being decoded (A/C-) */
234 static int track_widx = 0; /* Track being buffered (A) */
236 #define CUR_TI (&tracks[track_ridx]) /* Playing track info pointer (A/C-) */
237 static struct track_info *prev_ti = NULL; /* Pointer to the previously played
238 track */
240 /* Information used only for filling the buffer */
241 /* Playlist steps from playing track to next track to be buffered (A) */
242 static int last_peek_offset = 0;
244 /* Scrobbler support */
245 static unsigned long prev_track_elapsed = 0; /* Previous track elapsed time (C/A-)*/
247 static enum filling_state filling;
249 /* Track change controls */
250 static bool automatic_skip = false; /* Who initiated in-progress skip? (C/A-) */
251 static bool dir_skip = false; /* Is a directory skip pending? (A) */
252 static bool new_playlist = false; /* Are we starting a new playlist? (A) */
253 static int wps_offset = 0; /* Pending track change offset, to keep WPS responsive (A) */
254 static bool skipped_during_pause = false; /* Do we need to clear the PCM buffer when playback resumes (A) */
256 static bool start_play_g = false; /* Used by audio_load_track to notify
257 audio_finish_load_track about start_play */
259 /* True when a track load is in progress, i.e. audio_load_track() has returned
260 * but audio_finish_load_track() hasn't been called yet. Used to avoid allowing
261 * audio_load_track() to get called twice in a row, which would cause problems.
263 static bool track_load_started = false;
265 /* Set to true if the codec thread should send an audio stop request
266 * (typically because the end of the playlist has been reached).
268 static bool codec_requested_stop = false;
270 #ifdef HAVE_DISK_STORAGE
271 static size_t buffer_margin = 5; /* Buffer margin aka anti-skip buffer (A/C-) */
272 #endif
274 /* Multiple threads */
275 /* Set the watermark to trigger buffer fill (A/C) */
276 static void set_filebuf_watermark(void);
278 /* Audio thread */
279 static struct event_queue audio_queue SHAREDBSS_ATTR;
280 static struct queue_sender_list audio_queue_sender_list SHAREDBSS_ATTR;
281 static long audio_stack[(DEFAULT_STACK_SIZE + 0x1000)/sizeof(long)];
282 static const char audio_thread_name[] = "audio";
284 static void audio_thread(void);
285 static void audio_initiate_track_change(long direction);
286 static bool audio_have_tracks(void);
287 static void audio_reset_buffer(void);
288 static void audio_stop_playback(void);
290 /* Codec thread */
291 extern struct codec_api ci;
292 static struct event_queue codec_queue SHAREDBSS_ATTR;
293 static struct queue_sender_list codec_queue_sender_list;
294 static long codec_stack[(DEFAULT_STACK_SIZE + 0x2000)/sizeof(long)]
295 IBSS_ATTR;
296 static const char codec_thread_name[] = "codec";
297 unsigned int codec_thread_id; /* For modifying thread priority later. */
299 /* PCM buffer messaging */
300 static struct event_queue pcmbuf_queue SHAREDBSS_ATTR;
302 /* Function to be called by pcm buffer callbacks.
303 * Permissible Context(s): Audio interrupt
305 static void pcmbuf_callback_queue_post(long id, intptr_t data)
307 /* No lock since we're already in audio interrupt context */
308 queue_post(&pcmbuf_queue, id, data);
311 /* Scan the pcmbuf queue and return true if a message pulled.
312 * Permissible Context(s): Thread
314 static bool pcmbuf_queue_scan(struct queue_event *ev)
316 if (!queue_empty(&pcmbuf_queue))
318 /* Transfer message to audio queue */
319 pcm_play_lock();
320 /* Pull message - never, ever any blocking call! */
321 queue_wait_w_tmo(&pcmbuf_queue, ev, 0);
322 pcm_play_unlock();
323 return true;
326 return false;
329 /* Clear the pcmbuf queue of messages
330 * Permissible Context(s): Thread
332 static void pcmbuf_queue_clear(void)
334 pcm_play_lock();
335 queue_clear(&pcmbuf_queue);
336 pcm_play_unlock();
339 /* --- Helper functions --- */
341 static struct mp3entry *bufgetid3(int handle_id)
343 if (handle_id < 0)
344 return NULL;
346 struct mp3entry *id3;
347 ssize_t ret = bufgetdata(handle_id, 0, (void *)&id3);
349 if (ret < 0 || ret != sizeof(struct mp3entry))
350 return NULL;
352 return id3;
355 static bool clear_track_info(struct track_info *track)
357 /* bufclose returns true if the handle is not found, or if it is closed
358 * successfully, so these checks are safe on non-existant handles */
359 if (!track)
360 return false;
362 if (track->codec_hid >= 0) {
363 if (bufclose(track->codec_hid))
364 track->codec_hid = -1;
365 else
366 return false;
369 if (track->id3_hid >= 0) {
370 if (bufclose(track->id3_hid))
371 track->id3_hid = -1;
372 else
373 return false;
376 if (track->audio_hid >= 0) {
377 if (bufclose(track->audio_hid))
378 track->audio_hid = -1;
379 else
380 return false;
383 #ifdef HAVE_ALBUMART
385 int i;
386 FOREACH_ALBUMART(i)
388 if (track->aa_hid[i] >= 0) {
389 if (bufclose(track->aa_hid[i]))
390 track->aa_hid[i] = -1;
391 else
392 return false;
396 #endif
398 if (track->cuesheet_hid >= 0) {
399 if (bufclose(track->cuesheet_hid))
400 track->cuesheet_hid = -1;
401 else
402 return false;
405 track->filesize = 0;
406 track->taginfo_ready = false;
408 return true;
411 /* --- External interfaces --- */
413 /* This sends a stop message and the audio thread will dump all it's
414 subsequenct messages */
415 void audio_hard_stop(void)
417 /* Stop playback */
418 LOGFQUEUE("audio >| audio Q_AUDIO_STOP: 1");
419 queue_send(&audio_queue, Q_AUDIO_STOP, 1);
420 #ifdef PLAYBACK_VOICE
421 voice_stop();
422 #endif
425 bool audio_restore_playback(int type)
427 switch (type)
429 case AUDIO_WANT_PLAYBACK:
430 if (buffer_state != AUDIOBUF_STATE_INITIALIZED)
431 audio_reset_buffer();
432 return true;
433 case AUDIO_WANT_VOICE:
434 if (buffer_state == AUDIOBUF_STATE_TRASHED)
435 audio_reset_buffer();
436 return true;
437 default:
438 return false;
442 unsigned char *audio_get_buffer(bool talk_buf, size_t *buffer_size)
444 unsigned char *buf, *end;
446 if (audio_is_initialized)
448 audio_hard_stop();
450 /* else buffer_state will be AUDIOBUF_STATE_TRASHED at this point */
452 /* Reset the buffering thread so that it doesn't try to use the data */
453 buffering_reset(filebuf, filebuflen);
455 if (buffer_size == NULL)
457 /* Special case for talk_init to use since it already knows it's
458 trashed */
459 buffer_state = AUDIOBUF_STATE_TRASHED;
460 return NULL;
463 if (talk_buf || buffer_state == AUDIOBUF_STATE_TRASHED
464 || !talk_voice_required())
466 logf("get buffer: talk, audio");
467 /* Ok to use everything from audiobuf to audiobufend - voice is loaded,
468 the talk buffer is not needed because voice isn't being used, or
469 could be AUDIOBUF_STATE_TRASHED already. If state is
470 AUDIOBUF_STATE_VOICED_ONLY, no problem as long as memory isn't written
471 without the caller knowing what's going on. Changing certain settings
472 may move it to a worse condition but the memory in use by something
473 else will remain undisturbed.
475 if (buffer_state != AUDIOBUF_STATE_TRASHED)
477 talk_buffer_steal();
478 buffer_state = AUDIOBUF_STATE_TRASHED;
481 buf = audiobuf;
482 end = audiobufend;
484 else
486 /* Safe to just return this if already AUDIOBUF_STATE_VOICED_ONLY or
487 still AUDIOBUF_STATE_INITIALIZED */
488 /* Skip talk buffer and move pcm buffer to end to maximize available
489 contiguous memory - no audio running means voice will not need the
490 swap space */
491 logf("get buffer: audio");
492 buf = audiobuf + talk_get_bufsize();
493 end = audiobufend - pcmbuf_init(audiobufend);
494 buffer_state = AUDIOBUF_STATE_VOICED_ONLY;
497 *buffer_size = end - buf;
499 return buf;
502 int audio_buffer_state(void)
504 return buffer_state;
507 #ifdef HAVE_RECORDING
508 unsigned char *audio_get_recording_buffer(size_t *buffer_size)
510 /* Stop audio, voice and obtain all available buffer space */
511 audio_hard_stop();
512 talk_buffer_steal();
514 unsigned char *end = audiobufend;
515 buffer_state = AUDIOBUF_STATE_TRASHED;
516 *buffer_size = end - audiobuf;
518 return (unsigned char *)audiobuf;
521 bool audio_load_encoder(int afmt)
523 #ifndef SIMULATOR
524 const char *enc_fn = get_codec_filename(afmt | CODEC_TYPE_ENCODER);
525 if (!enc_fn)
526 return false;
528 audio_remove_encoder();
529 ci.enc_codec_loaded = 0; /* clear any previous error condition */
531 LOGFQUEUE("codec > Q_ENCODER_LOAD_DISK");
532 queue_post(&codec_queue, Q_ENCODER_LOAD_DISK, (intptr_t)enc_fn);
534 while (ci.enc_codec_loaded == 0)
535 yield();
537 logf("codec loaded: %d", ci.enc_codec_loaded);
539 return ci.enc_codec_loaded > 0;
540 #else
541 (void)afmt;
542 return true;
543 #endif
544 } /* audio_load_encoder */
546 void audio_remove_encoder(void)
548 #ifndef SIMULATOR
549 /* force encoder codec unload (if currently loaded) */
550 if (ci.enc_codec_loaded <= 0)
551 return;
553 ci.stop_encoder = true;
554 while (ci.enc_codec_loaded > 0)
555 yield();
556 #endif
557 } /* audio_remove_encoder */
559 #endif /* HAVE_RECORDING */
562 struct mp3entry* audio_current_track(void)
564 const char *filename;
565 struct playlist_track_info trackinfo;
566 int cur_idx;
567 int offset = ci.new_track + wps_offset;
568 struct mp3entry *write_id3;
570 cur_idx = (track_ridx + offset) & MAX_TRACK_MASK;
572 if (cur_idx == track_ridx && *thistrack_id3->path)
574 /* The usual case */
575 if (tracks[cur_idx].cuesheet_hid >= 0 && !thistrack_id3->cuesheet)
577 bufread(tracks[cur_idx].cuesheet_hid, sizeof(struct cuesheet), curr_cue);
578 thistrack_id3->cuesheet = curr_cue;
579 cue_spoof_id3(thistrack_id3->cuesheet, thistrack_id3);
581 return thistrack_id3;
583 else if (automatic_skip && offset == -1 && *othertrack_id3->path)
585 /* We're in a track transition. The codec has moved on to the next track,
586 but the audio being played is still the same (now previous) track.
587 othertrack_id3.elapsed is being updated in an ISR by
588 codec_pcmbuf_position_callback */
589 if (tracks[cur_idx].cuesheet_hid >= 0 && !thistrack_id3->cuesheet)
591 bufread(tracks[cur_idx].cuesheet_hid, sizeof(struct cuesheet), curr_cue);
592 othertrack_id3->cuesheet = curr_cue;
593 cue_spoof_id3(othertrack_id3->cuesheet, othertrack_id3);
595 return othertrack_id3;
598 if (offset != 0)
600 /* Codec may be using thistrack_id3, so it must not be overwritten.
601 If this is a manual skip, othertrack_id3 will become
602 thistrack_id3 in audio_check_new_track().
603 FIXME: If this is an automatic skip, it probably means multiple
604 short tracks fit in the PCM buffer. Overwriting othertrack_id3
605 can lead to an incorrect value later.
606 Note that othertrack_id3 may also be used for next track.
608 write_id3 = othertrack_id3;
610 else
612 write_id3 = thistrack_id3;
615 if (tracks[cur_idx].id3_hid >= 0)
617 /* The current track's info has been buffered but not read yet, so get it */
618 if (bufread(tracks[cur_idx].id3_hid, sizeof(struct mp3entry), write_id3)
619 == sizeof(struct mp3entry))
620 return write_id3;
623 /* We didn't find the ID3 metadata, so we fill temp_id3 with the little info
624 we have and return that. */
626 memset(write_id3, 0, sizeof(struct mp3entry));
628 playlist_get_track_info(NULL, playlist_next(0)+wps_offset, &trackinfo);
629 filename = trackinfo.filename;
630 if (!filename)
631 filename = "No file!";
633 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
634 if (tagcache_fill_tags(write_id3, filename))
635 return write_id3;
636 #endif
638 strlcpy(write_id3->path, filename, sizeof(write_id3->path));
639 write_id3->title = strrchr(write_id3->path, '/');
640 if (!write_id3->title)
641 write_id3->title = &write_id3->path[0];
642 else
643 write_id3->title++;
645 return write_id3;
648 struct mp3entry* audio_next_track(void)
650 int next_idx;
651 int offset = ci.new_track + wps_offset;
653 if (!audio_have_tracks())
654 return NULL;
656 if (wps_offset == -1 && *thistrack_id3->path)
658 /* We're in a track transition. The next track for the WPS is the one
659 currently being decoded. */
660 return thistrack_id3;
663 next_idx = (track_ridx + offset + 1) & MAX_TRACK_MASK;
665 if (tracks[next_idx].id3_hid >= 0)
667 if (bufread(tracks[next_idx].id3_hid, sizeof(struct mp3entry), othertrack_id3)
668 == sizeof(struct mp3entry))
669 return othertrack_id3;
670 else
671 return NULL;
674 if (next_idx == track_widx)
676 /* The next track hasn't been buffered yet, so we return the static
677 version of its metadata. */
678 return &unbuffered_id3;
681 return NULL;
684 #ifdef HAVE_ALBUMART
685 int playback_current_aa_hid(int slot)
687 if (slot < 0)
688 return -1;
689 int cur_idx;
690 int offset = ci.new_track + wps_offset;
692 cur_idx = track_ridx + offset;
693 cur_idx &= MAX_TRACK_MASK;
695 return tracks[cur_idx].aa_hid[slot];
698 int playback_claim_aa_slot(struct dim *dim)
700 int i;
701 /* first try to find a slot already having the size to reuse it
702 * since we don't want albumart of the same size buffered multiple times */
703 FOREACH_ALBUMART(i)
705 struct albumart_slot *slot = &albumart_slots[i];
706 if (slot->dim.width == dim->width
707 && slot->dim.height == dim->height)
709 slot->used++;
710 return i;
713 /* size is new, find a free slot */
714 FOREACH_ALBUMART(i)
716 if (!albumart_slots[i].used)
718 albumart_slots[i].used++;
719 albumart_slots[i].dim = *dim;
720 return i;
723 /* sorry, no free slot */
724 return -1;
727 void playback_release_aa_slot(int slot)
729 /* invalidate the albumart_slot */
730 struct albumart_slot *aa_slot = &albumart_slots[slot];
731 if (aa_slot->used > 0)
732 aa_slot->used--;
735 #endif
736 void audio_play(long offset)
738 logf("audio_play");
740 #ifdef PLAYBACK_VOICE
741 /* Truncate any existing voice output so we don't have spelling
742 * etc. over the first part of the played track */
743 talk_force_shutup();
744 #endif
746 /* Start playback */
747 LOGFQUEUE("audio >| audio Q_AUDIO_PLAY: %ld", offset);
748 /* Don't return until playback has actually started */
749 queue_send(&audio_queue, Q_AUDIO_PLAY, offset);
752 void audio_stop(void)
754 /* Stop playback */
755 LOGFQUEUE("audio >| audio Q_AUDIO_STOP");
756 /* Don't return until playback has actually stopped */
757 queue_send(&audio_queue, Q_AUDIO_STOP, 0);
760 void audio_pause(void)
762 LOGFQUEUE("audio >| audio Q_AUDIO_PAUSE");
763 /* Don't return until playback has actually paused */
764 queue_send(&audio_queue, Q_AUDIO_PAUSE, true);
767 void audio_resume(void)
769 LOGFQUEUE("audio >| audio Q_AUDIO_PAUSE resume");
770 /* Don't return until playback has actually resumed */
771 queue_send(&audio_queue, Q_AUDIO_PAUSE, false);
774 void audio_skip(int direction)
776 if (playlist_check(ci.new_track + wps_offset + direction))
778 if (global_settings.beep)
779 pcmbuf_beep(2000, 100, 2500*global_settings.beep);
781 LOGFQUEUE("audio > audio Q_AUDIO_SKIP %d", direction);
782 queue_post(&audio_queue, Q_AUDIO_SKIP, direction);
783 /* Update wps while our message travels inside deep playback queues. */
784 wps_offset += direction;
786 else
788 /* No more tracks. */
789 if (global_settings.beep)
790 pcmbuf_beep(1000, 100, 1500*global_settings.beep);
794 void audio_next(void)
796 audio_skip(1);
799 void audio_prev(void)
801 audio_skip(-1);
804 void audio_next_dir(void)
806 LOGFQUEUE("audio > audio Q_AUDIO_DIR_SKIP 1");
807 queue_post(&audio_queue, Q_AUDIO_DIR_SKIP, 1);
810 void audio_prev_dir(void)
812 LOGFQUEUE("audio > audio Q_AUDIO_DIR_SKIP -1");
813 queue_post(&audio_queue, Q_AUDIO_DIR_SKIP, -1);
816 void audio_pre_ff_rewind(void)
818 LOGFQUEUE("audio > audio Q_AUDIO_PRE_FF_REWIND");
819 queue_post(&audio_queue, Q_AUDIO_PRE_FF_REWIND, 0);
822 void audio_ff_rewind(long newpos)
824 LOGFQUEUE("audio > audio Q_AUDIO_FF_REWIND");
825 queue_post(&audio_queue, Q_AUDIO_FF_REWIND, newpos);
828 void audio_flush_and_reload_tracks(void)
830 LOGFQUEUE("audio > audio Q_AUDIO_FLUSH");
831 queue_post(&audio_queue, Q_AUDIO_FLUSH, 0);
834 void audio_error_clear(void)
836 #ifdef AUDIO_HAVE_RECORDING
837 pcm_rec_error_clear();
838 #endif
841 int audio_status(void)
843 int ret = 0;
845 if (playing)
846 ret |= AUDIO_STATUS_PLAY;
848 if (paused)
849 ret |= AUDIO_STATUS_PAUSE;
851 #ifdef HAVE_RECORDING
852 /* Do this here for constitency with mpeg.c version */
853 ret |= pcm_rec_status();
854 #endif
856 return ret;
859 int audio_get_file_pos(void)
861 return 0;
864 #ifdef HAVE_DISK_STORAGE
865 void audio_set_buffer_margin(int setting)
867 static const unsigned short lookup[] = {5, 15, 30, 60, 120, 180, 300, 600};
868 buffer_margin = lookup[setting];
869 logf("buffer margin: %ld", (long)buffer_margin);
870 set_filebuf_watermark();
872 #endif
874 /* Take necessary steps to enable or disable the crossfade setting */
875 void audio_set_crossfade(int enable)
877 size_t offset;
878 bool was_playing;
879 size_t size;
881 /* Tell it the next setting to use */
882 pcmbuf_crossfade_enable(enable);
884 /* Return if size hasn't changed or this is too early to determine
885 which in the second case there's no way we could be playing
886 anything at all */
887 if (pcmbuf_is_same_size())
889 /* This function is a copout and just syncs some variables -
890 to be removed at a later date */
891 pcmbuf_crossfade_enable_finished();
892 return;
895 offset = 0;
896 was_playing = playing;
898 /* Playback has to be stopped before changing the buffer size */
899 if (was_playing)
901 /* Store the track resume position */
902 offset = thistrack_id3->offset;
905 /* Blast it - audio buffer will have to be setup again next time
906 something plays */
907 audio_get_buffer(true, &size);
909 /* Restart playback if audio was running previously */
910 if (was_playing)
911 audio_play(offset);
914 /* --- Routines called from multiple threads --- */
916 static void set_filebuf_watermark(void)
918 if (!filebuf)
919 return; /* Audio buffers not yet set up */
921 #ifdef HAVE_DISK_STORAGE
922 int seconds;
923 int spinup = ata_spinup_time();
924 if (spinup)
925 seconds = (spinup / HZ) + 1;
926 else
927 seconds = 5;
929 seconds += buffer_margin;
930 #else
931 /* flash storage */
932 int seconds = 1;
933 #endif
935 /* bitrate of last track in buffer dictates watermark */
936 struct mp3entry* id3 = NULL;
937 if (tracks[track_widx].taginfo_ready)
938 id3 = bufgetid3(tracks[track_widx].id3_hid);
939 else
940 id3 = bufgetid3(tracks[track_widx-1].id3_hid);
941 if (!id3) {
942 logf("fwmark: No id3 for last track (r%d/w%d), aborting!", track_ridx, track_widx);
943 return;
945 size_t bytes = id3->bitrate * (1000/8) * seconds;
946 buf_set_watermark(bytes);
947 logf("fwmark: %d", bytes);
950 const char *get_codec_filename(int cod_spec)
952 const char *fname;
954 #ifdef HAVE_RECORDING
955 /* Can choose decoder or encoder if one available */
956 int type = cod_spec & CODEC_TYPE_MASK;
957 int afmt = cod_spec & CODEC_AFMT_MASK;
959 if ((unsigned)afmt >= AFMT_NUM_CODECS)
960 type = AFMT_UNKNOWN | (type & CODEC_TYPE_MASK);
962 fname = (type == CODEC_TYPE_ENCODER) ?
963 audio_formats[afmt].codec_enc_root_fn :
964 audio_formats[afmt].codec_root_fn;
966 logf("%s: %d - %s",
967 (type == CODEC_TYPE_ENCODER) ? "Encoder" : "Decoder",
968 afmt, fname ? fname : "<unknown>");
969 #else /* !HAVE_RECORDING */
970 /* Always decoder */
971 if ((unsigned)cod_spec >= AFMT_NUM_CODECS)
972 cod_spec = AFMT_UNKNOWN;
973 fname = audio_formats[cod_spec].codec_root_fn;
974 logf("Codec: %d - %s", cod_spec, fname ? fname : "<unknown>");
975 #endif /* HAVE_RECORDING */
977 return fname;
978 } /* get_codec_filename */
980 /* --- Codec thread --- */
981 static bool codec_pcmbuf_insert_callback(
982 const void *ch1, const void *ch2, int count)
984 const char *src[2] = { ch1, ch2 };
986 while (count > 0)
988 int out_count = dsp_output_count(ci.dsp, count);
989 int inp_count;
990 char *dest;
992 /* Prevent audio from a previous track from playing */
993 if (ci.new_track || ci.stop_codec)
994 return true;
996 while ((dest = pcmbuf_request_buffer(&out_count)) == NULL)
998 cancel_cpu_boost();
999 sleep(1);
1000 if (ci.seek_time || ci.new_track || ci.stop_codec)
1001 return true;
1004 /* Get the real input_size for output_size bytes, guarding
1005 * against resampling buffer overflows. */
1006 inp_count = dsp_input_count(ci.dsp, out_count);
1008 if (inp_count <= 0)
1009 return true;
1011 /* Input size has grown, no error, just don't write more than length */
1012 if (inp_count > count)
1013 inp_count = count;
1015 out_count = dsp_process(ci.dsp, dest, src, inp_count);
1017 if (out_count <= 0)
1018 return true;
1020 pcmbuf_write_complete(out_count);
1022 count -= inp_count;
1025 return true;
1026 } /* codec_pcmbuf_insert_callback */
1028 static void* codec_get_buffer(size_t *size)
1030 if (codec_size >= CODEC_SIZE)
1031 return NULL;
1032 *size = CODEC_SIZE - codec_size;
1033 return &codecbuf[codec_size];
1036 /* Between the codec and PCM track change, we need to keep updating the
1037 "elapsed" value of the previous (to the codec, but current to the
1038 user/PCM/WPS) track, so that the progressbar reaches the end.
1039 During that transition, the WPS will display prevtrack_id3. */
1040 static void codec_pcmbuf_position_callback(size_t size) ICODE_ATTR;
1041 static void codec_pcmbuf_position_callback(size_t size)
1043 /* This is called from an ISR, so be quick */
1044 unsigned int time = size * 1000 / 4 / NATIVE_FREQUENCY +
1045 othertrack_id3->elapsed;
1047 if (time >= othertrack_id3->length)
1049 pcmbuf_set_position_callback(NULL);
1050 othertrack_id3->elapsed = othertrack_id3->length;
1052 else
1053 othertrack_id3->elapsed = time;
1056 static void codec_set_elapsed_callback(unsigned int value)
1058 unsigned int latency;
1059 if (ci.seek_time)
1060 return;
1062 #ifdef AB_REPEAT_ENABLE
1063 ab_position_report(value);
1064 #endif
1066 latency = pcmbuf_get_latency();
1067 if (value < latency)
1068 thistrack_id3->elapsed = 0;
1069 else if (value - latency > thistrack_id3->elapsed ||
1070 value - latency < thistrack_id3->elapsed - 2)
1072 thistrack_id3->elapsed = value - latency;
1076 static void codec_set_offset_callback(size_t value)
1078 unsigned int latency;
1080 if (ci.seek_time)
1081 return;
1083 latency = pcmbuf_get_latency() * thistrack_id3->bitrate / 8;
1084 if (value < latency)
1085 thistrack_id3->offset = 0;
1086 else
1087 thistrack_id3->offset = value - latency;
1090 static void codec_advance_buffer_counters(size_t amount)
1092 bufadvance(CUR_TI->audio_hid, amount);
1093 ci.curpos += amount;
1096 /* copy up-to size bytes into ptr and return the actual size copied */
1097 static size_t codec_filebuf_callback(void *ptr, size_t size)
1099 ssize_t copy_n;
1101 if (ci.stop_codec || !playing)
1102 return 0;
1104 copy_n = bufread(CUR_TI->audio_hid, size, ptr);
1106 /* Nothing requested OR nothing left */
1107 if (copy_n == 0)
1108 return 0;
1110 /* Update read and other position pointers */
1111 codec_advance_buffer_counters(copy_n);
1113 /* Return the actual amount of data copied to the buffer */
1114 return copy_n;
1115 } /* codec_filebuf_callback */
1117 static void* codec_request_buffer_callback(size_t *realsize, size_t reqsize)
1119 size_t copy_n = reqsize;
1120 ssize_t ret;
1121 void *ptr;
1123 if (!playing)
1125 *realsize = 0;
1126 return NULL;
1129 ret = bufgetdata(CUR_TI->audio_hid, reqsize, &ptr);
1130 if (ret >= 0)
1131 copy_n = MIN((size_t)ret, reqsize);
1133 if (copy_n == 0)
1135 *realsize = 0;
1136 return NULL;
1139 *realsize = copy_n;
1141 return ptr;
1142 } /* codec_request_buffer_callback */
1144 static int get_codec_base_type(int type)
1146 switch (type) {
1147 case AFMT_MPA_L1:
1148 case AFMT_MPA_L2:
1149 case AFMT_MPA_L3:
1150 return AFMT_MPA_L3;
1153 return type;
1156 static void codec_advance_buffer_callback(size_t amount)
1158 codec_advance_buffer_counters(amount);
1159 codec_set_offset_callback(ci.curpos);
1162 static void codec_advance_buffer_loc_callback(void *ptr)
1164 size_t amount = buf_get_offset(CUR_TI->audio_hid, ptr);
1165 codec_advance_buffer_callback(amount);
1168 static void codec_seek_complete_callback(void)
1170 logf("seek_complete");
1171 /* If seeking-while-playing, pcm playback is actually paused (pcm_is_paused())
1172 * but the paused flag is not set. If seeking-while-paused, the (paused) flag is
1173 * set, but pcm playback may have actually stopped due to a previous buffer clear.
1174 * The buffer clear below occurs with either condition. A seemless seek skips
1175 * this section and no buffer clear occurs.
1177 if (pcm_is_paused() || paused)
1179 /* Clear the buffer */
1180 pcmbuf_play_stop();
1181 dsp_configure(ci.dsp, DSP_FLUSH, 0);
1183 /* If seeking-while-playing, resume pcm playback */
1184 if (!paused)
1185 pcmbuf_pause(false);
1187 ci.seek_time = 0;
1190 static bool codec_seek_buffer_callback(size_t newpos)
1192 logf("codec_seek_buffer_callback");
1194 int ret = bufseek(CUR_TI->audio_hid, newpos);
1195 if (ret == 0) {
1196 ci.curpos = newpos;
1197 return true;
1199 else {
1200 return false;
1204 static void codec_configure_callback(int setting, intptr_t value)
1206 switch (setting) {
1207 default:
1208 if (!dsp_configure(ci.dsp, setting, value))
1209 { logf("Illegal key:%d", setting); }
1213 static void codec_track_changed(void)
1215 LOGFQUEUE("codec > audio Q_AUDIO_TRACK_CHANGED");
1216 queue_post(&audio_queue, Q_AUDIO_TRACK_CHANGED, 0);
1219 static void codec_pcmbuf_track_changed_callback(void)
1221 pcmbuf_set_position_callback(NULL);
1222 pcmbuf_callback_queue_post(Q_AUDIO_TRACK_CHANGED, 0);
1225 static void codec_discard_codec_callback(void)
1227 if (CUR_TI->codec_hid >= 0)
1229 bufclose(CUR_TI->codec_hid);
1230 CUR_TI->codec_hid = -1;
1234 static inline void codec_gapless_track_change(void)
1236 /* callback keeps the progress bar moving while the pcmbuf empties */
1237 pcmbuf_set_position_callback(codec_pcmbuf_position_callback);
1238 /* set the pcmbuf callback for when the track really changes */
1239 pcmbuf_set_event_handler(codec_pcmbuf_track_changed_callback);
1242 static inline void codec_crossfade_track_change(void)
1244 /* Initiate automatic crossfade mode */
1245 pcmbuf_crossfade_init(false);
1246 /* Notify the wps that the track change starts now */
1247 codec_track_changed();
1250 static void codec_track_skip_done(bool was_manual)
1252 /* Manual track change (always crossfade or flush audio). */
1253 if (was_manual)
1255 pcmbuf_crossfade_init(true);
1256 LOGFQUEUE("codec > audio Q_AUDIO_TRACK_CHANGED");
1257 queue_post(&audio_queue, Q_AUDIO_TRACK_CHANGED, 0);
1259 /* Automatic track change w/crossfade, if not in "Track Skip Only" mode. */
1260 else if (pcmbuf_is_crossfade_enabled() && !pcmbuf_is_crossfade_active()
1261 && global_settings.crossfade != CROSSFADE_ENABLE_TRACKSKIP)
1263 if (global_settings.crossfade == CROSSFADE_ENABLE_SHUFFLE_AND_TRACKSKIP)
1265 if (global_settings.playlist_shuffle)
1266 /* shuffle mode is on, so crossfade: */
1267 codec_crossfade_track_change();
1268 else
1269 /* shuffle mode is off, so do a gapless track change */
1270 codec_gapless_track_change();
1272 else
1273 /* normal crossfade: */
1274 codec_crossfade_track_change();
1276 else
1277 /* normal gapless playback. */
1278 codec_gapless_track_change();
1281 static bool codec_load_next_track(void)
1283 intptr_t result = Q_CODEC_REQUEST_FAILED;
1285 prev_track_elapsed = thistrack_id3->elapsed;
1287 #ifdef AB_REPEAT_ENABLE
1288 ab_end_of_track_report();
1289 #endif
1291 logf("Request new track");
1293 if (ci.new_track == 0)
1295 ci.new_track++;
1296 automatic_skip = true;
1299 if (!ci.stop_codec)
1301 trigger_cpu_boost();
1302 LOGFQUEUE("codec >| audio Q_AUDIO_CHECK_NEW_TRACK");
1303 result = queue_send(&audio_queue, Q_AUDIO_CHECK_NEW_TRACK, 0);
1306 switch (result)
1308 case Q_CODEC_REQUEST_COMPLETE:
1309 LOGFQUEUE("codec |< Q_CODEC_REQUEST_COMPLETE");
1310 codec_track_skip_done(!automatic_skip);
1311 return true;
1313 case Q_CODEC_REQUEST_FAILED:
1314 LOGFQUEUE("codec |< Q_CODEC_REQUEST_FAILED");
1315 ci.new_track = 0;
1316 ci.stop_codec = true;
1317 codec_requested_stop = true;
1318 return false;
1320 default:
1321 LOGFQUEUE("codec |< default");
1322 ci.stop_codec = true;
1323 codec_requested_stop = true;
1324 return false;
1328 static bool codec_request_next_track_callback(void)
1330 int prev_codectype;
1332 if (ci.stop_codec || !playing)
1333 return false;
1335 prev_codectype = get_codec_base_type(thistrack_id3->codectype);
1336 if (!codec_load_next_track())
1337 return false;
1339 /* Seek to the beginning of the new track because if the struct
1340 mp3entry was buffered, "elapsed" might not be zero (if the track has
1341 been played already but not unbuffered) */
1342 codec_seek_buffer_callback(thistrack_id3->first_frame_offset);
1343 /* Check if the next codec is the same file. */
1344 if (prev_codectype == get_codec_base_type(thistrack_id3->codectype))
1346 logf("New track loaded");
1347 codec_discard_codec_callback();
1348 return true;
1350 else
1352 logf("New codec:%d/%d", thistrack_id3->codectype, prev_codectype);
1353 return false;
1357 static void codec_thread(void)
1359 struct queue_event ev;
1360 int status;
1362 while (1) {
1363 status = 0;
1365 if (!pcmbuf_is_crossfade_active()) {
1366 cancel_cpu_boost();
1369 queue_wait(&codec_queue, &ev);
1370 codec_requested_stop = false;
1372 switch (ev.id) {
1373 case Q_CODEC_LOAD_DISK:
1374 LOGFQUEUE("codec < Q_CODEC_LOAD_DISK");
1375 queue_reply(&codec_queue, 1);
1376 audio_codec_loaded = true;
1377 ci.stop_codec = false;
1378 status = codec_load_file((const char *)ev.data, &ci);
1379 LOGFQUEUE("codec_load_file %s %d\n", (const char *)ev.data, status);
1380 break;
1382 case Q_CODEC_LOAD:
1383 LOGFQUEUE("codec < Q_CODEC_LOAD");
1384 if (CUR_TI->codec_hid < 0) {
1385 logf("Codec slot is empty!");
1386 /* Wait for the pcm buffer to go empty */
1387 while (pcm_is_playing())
1388 yield();
1389 /* This must be set to prevent an infinite loop */
1390 ci.stop_codec = true;
1391 LOGFQUEUE("codec > codec Q_AUDIO_PLAY");
1392 queue_post(&codec_queue, Q_AUDIO_PLAY, 0);
1393 break;
1396 audio_codec_loaded = true;
1397 ci.stop_codec = false;
1398 status = codec_load_buf(CUR_TI->codec_hid, &ci);
1399 LOGFQUEUE("codec_load_buf %d\n", status);
1400 break;
1402 case Q_CODEC_DO_CALLBACK:
1403 LOGFQUEUE("codec < Q_CODEC_DO_CALLBACK");
1404 queue_reply(&codec_queue, 1);
1405 if ((void*)ev.data != NULL)
1407 cpucache_invalidate();
1408 ((void (*)(void))ev.data)();
1409 cpucache_flush();
1411 break;
1413 #ifdef AUDIO_HAVE_RECORDING
1414 case Q_ENCODER_LOAD_DISK:
1415 LOGFQUEUE("codec < Q_ENCODER_LOAD_DISK");
1416 audio_codec_loaded = false; /* Not audio codec! */
1417 logf("loading encoder");
1418 ci.stop_encoder = false;
1419 status = codec_load_file((const char *)ev.data, &ci);
1420 logf("encoder stopped");
1421 break;
1422 #endif /* AUDIO_HAVE_RECORDING */
1424 default:
1425 LOGFQUEUE("codec < default");
1428 if (audio_codec_loaded)
1430 if (ci.stop_codec)
1432 status = CODEC_OK;
1433 if (!playing)
1434 pcmbuf_play_stop();
1437 audio_codec_loaded = false;
1440 switch (ev.id) {
1441 case Q_CODEC_LOAD_DISK:
1442 case Q_CODEC_LOAD:
1443 LOGFQUEUE("codec < Q_CODEC_LOAD");
1444 if (playing)
1446 if (ci.new_track || status != CODEC_OK)
1448 if (!ci.new_track)
1450 logf("Codec failure, %d %d", ci.new_track, status);
1451 splash(HZ*2, "Codec failure");
1454 if (!codec_load_next_track())
1456 LOGFQUEUE("codec > audio Q_AUDIO_STOP");
1457 /* End of playlist */
1458 queue_post(&audio_queue, Q_AUDIO_STOP, 0);
1459 break;
1462 else
1464 logf("Codec finished");
1465 if (ci.stop_codec)
1467 /* Wait for the audio to stop playing before
1468 * triggering the WPS exit */
1469 while(pcm_is_playing())
1471 /* There has been one too many struct pointer swaps by now
1472 * so even though it says othertrack_id3, its the correct one! */
1473 othertrack_id3->elapsed =
1474 othertrack_id3->length - pcmbuf_get_latency();
1475 sleep(1);
1478 if (codec_requested_stop)
1480 LOGFQUEUE("codec > audio Q_AUDIO_STOP");
1481 queue_post(&audio_queue, Q_AUDIO_STOP, 0);
1483 break;
1487 if (CUR_TI->codec_hid >= 0)
1489 LOGFQUEUE("codec > codec Q_CODEC_LOAD");
1490 queue_post(&codec_queue, Q_CODEC_LOAD, 0);
1492 else
1494 const char *codec_fn =
1495 get_codec_filename(thistrack_id3->codectype);
1496 if (codec_fn)
1498 LOGFQUEUE("codec > codec Q_CODEC_LOAD_DISK");
1499 queue_post(&codec_queue, Q_CODEC_LOAD_DISK,
1500 (intptr_t)codec_fn);
1504 break;
1506 #ifdef AUDIO_HAVE_RECORDING
1507 case Q_ENCODER_LOAD_DISK:
1508 LOGFQUEUE("codec < Q_ENCODER_LOAD_DISK");
1510 if (status == CODEC_OK)
1511 break;
1513 logf("Encoder failure");
1514 splash(HZ*2, "Encoder failure");
1516 if (ci.enc_codec_loaded < 0)
1517 break;
1519 logf("Encoder failed to load");
1520 ci.enc_codec_loaded = -1;
1521 break;
1522 #endif /* AUDIO_HAVE_RECORDING */
1524 default:
1525 LOGFQUEUE("codec < default");
1527 } /* end switch */
1531 /* Borrow the codec thread and return the ID */
1532 void codec_thread_do_callback(void (*fn)(void), unsigned int *id)
1534 /* Set id before telling thread to call something; it may be
1535 * needed before this function returns. */
1536 if (id != NULL)
1537 *id = codec_thread_id;
1539 /* Codec thread will signal just before entering callback */
1540 LOGFQUEUE("codec >| Q_CODEC_DO_CALLBACK");
1541 queue_send(&codec_queue, Q_CODEC_DO_CALLBACK, (intptr_t)fn);
1544 /* --- Buffering callbacks --- */
1546 static void buffering_low_buffer_callback(void *data)
1548 (void)data;
1549 logf("low buffer callback");
1551 if (filling == STATE_FULL || filling == STATE_END_OF_PLAYLIST) {
1552 /* force a refill */
1553 LOGFQUEUE("buffering > audio Q_AUDIO_FILL_BUFFER");
1554 queue_post(&audio_queue, Q_AUDIO_FILL_BUFFER, 0);
1558 static void buffering_handle_rebuffer_callback(void *data)
1560 (void)data;
1561 LOGFQUEUE("audio >| audio Q_AUDIO_FLUSH");
1562 queue_post(&audio_queue, Q_AUDIO_FLUSH, 0);
1565 static void buffering_handle_finished_callback(void *data)
1567 logf("handle %d finished buffering", *data);
1568 int hid = (*(int*)data);
1570 if (hid == tracks[track_widx].id3_hid)
1572 int offset = ci.new_track + wps_offset;
1573 int next_idx = (track_ridx + offset + 1) & MAX_TRACK_MASK;
1574 /* The metadata handle for the last loaded track has been buffered.
1575 We can ask the audio thread to load the rest of the track's data. */
1576 LOGFQUEUE("audio >| audio Q_AUDIO_FINISH_LOAD");
1577 queue_post(&audio_queue, Q_AUDIO_FINISH_LOAD, 0);
1578 if (tracks[next_idx].id3_hid == hid)
1579 send_event(PLAYBACK_EVENT_NEXTTRACKID3_AVAILABLE, NULL);
1581 else
1583 /* This is most likely an audio handle, so we strip the useless
1584 trailing tags that are left. */
1585 strip_tags(hid);
1587 if (hid == tracks[track_widx-1].audio_hid
1588 && filling == STATE_END_OF_PLAYLIST)
1590 /* This was the last track in the playlist.
1591 We now have all the data we need. */
1592 logf("last track finished buffering");
1593 filling = STATE_FINISHED;
1599 /* --- Audio thread --- */
1601 static bool audio_have_tracks(void)
1603 return (audio_track_count() != 0);
1606 static int audio_free_track_count(void)
1608 /* Used tracks + free tracks adds up to MAX_TRACK - 1 */
1609 return MAX_TRACK - 1 - audio_track_count();
1612 int audio_track_count(void)
1614 /* Calculate difference from track_ridx to track_widx
1615 * taking into account a possible wrap-around. */
1616 return (MAX_TRACK + track_widx - track_ridx) & MAX_TRACK_MASK;
1619 long audio_filebufused(void)
1621 return (long) buf_used();
1624 /* Update track info after successful a codec track change */
1625 static void audio_update_trackinfo(void)
1627 /* Load the curent track's metadata into curtrack_id3 */
1628 if (CUR_TI->id3_hid >= 0)
1629 copy_mp3entry(thistrack_id3, bufgetid3(CUR_TI->id3_hid));
1631 /* Reset current position */
1632 thistrack_id3->elapsed = 0;
1633 thistrack_id3->offset = 0;
1635 /* Update the codec API */
1636 ci.filesize = CUR_TI->filesize;
1637 ci.id3 = thistrack_id3;
1638 ci.curpos = 0;
1639 ci.taginfo_ready = &CUR_TI->taginfo_ready;
1642 /* Clear tracks between write and read, non inclusive */
1643 static void audio_clear_track_entries(void)
1645 int cur_idx = track_widx;
1647 logf("Clearing tracks:%d/%d", track_ridx, track_widx);
1649 /* Loop over all tracks from write-to-read */
1650 while (1)
1652 cur_idx = (cur_idx + 1) & MAX_TRACK_MASK;
1654 if (cur_idx == track_ridx)
1655 break;
1657 clear_track_info(&tracks[cur_idx]);
1661 /* Clear all tracks */
1662 static bool audio_release_tracks(void)
1664 int i, cur_idx;
1666 logf("releasing all tracks");
1668 for(i = 0; i < MAX_TRACK; i++)
1670 cur_idx = (track_ridx + i) & MAX_TRACK_MASK;
1671 if (!clear_track_info(&tracks[cur_idx]))
1672 return false;
1675 return true;
1678 static bool audio_loadcodec(bool start_play)
1680 int prev_track;
1681 char codec_path[MAX_PATH]; /* Full path to codec */
1682 const struct mp3entry *id3, *prev_id3;
1684 if (tracks[track_widx].id3_hid < 0) {
1685 return false;
1688 id3 = bufgetid3(tracks[track_widx].id3_hid);
1689 if (!id3)
1690 return false;
1692 const char *codec_fn = get_codec_filename(id3->codectype);
1693 if (codec_fn == NULL)
1694 return false;
1696 tracks[track_widx].codec_hid = -1;
1698 if (start_play)
1700 /* Load the codec directly from disk and save some memory. */
1701 track_ridx = track_widx;
1702 ci.filesize = CUR_TI->filesize;
1703 ci.id3 = thistrack_id3;
1704 ci.taginfo_ready = &CUR_TI->taginfo_ready;
1705 ci.curpos = 0;
1706 LOGFQUEUE("codec > codec Q_CODEC_LOAD_DISK");
1707 queue_post(&codec_queue, Q_CODEC_LOAD_DISK, (intptr_t)codec_fn);
1708 return true;
1710 else
1712 /* If we already have another track than this one buffered */
1713 if (track_widx != track_ridx)
1715 prev_track = (track_widx - 1) & MAX_TRACK_MASK;
1717 id3 = bufgetid3(tracks[track_widx].id3_hid);
1718 prev_id3 = bufgetid3(tracks[prev_track].id3_hid);
1720 /* If the previous codec is the same as this one, there is no need
1721 * to put another copy of it on the file buffer */
1722 if (id3 && prev_id3 &&
1723 get_codec_base_type(id3->codectype) ==
1724 get_codec_base_type(prev_id3->codectype)
1725 && audio_codec_loaded)
1727 logf("Reusing prev. codec");
1728 return true;
1733 codec_get_full_path(codec_path, codec_fn);
1735 tracks[track_widx].codec_hid = bufopen(codec_path, 0, TYPE_CODEC, NULL);
1736 if (tracks[track_widx].codec_hid < 0)
1737 return false;
1739 logf("Loaded codec");
1741 return true;
1744 /* Load metadata for the next track (with bufopen). The rest of the track
1745 loading will be handled by audio_finish_load_track once the metadata has been
1746 actually loaded by the buffering thread. */
1747 static bool audio_load_track(size_t offset, bool start_play)
1749 const char *trackname;
1750 int fd = -1;
1752 if (track_load_started) {
1753 /* There is already a track load in progress, so track_widx hasn't been
1754 incremented yet. Loading another track would overwrite the one that
1755 hasn't finished loading. */
1756 logf("audio_load_track(): a track load is already in progress");
1757 return false;
1760 start_play_g = start_play; /* will be read by audio_finish_load_track */
1762 /* Stop buffer filling if there is no free track entries.
1763 Don't fill up the last track entry (we wan't to store next track
1764 metadata there). */
1765 if (!audio_free_track_count())
1767 logf("No free tracks");
1768 return false;
1771 last_peek_offset++;
1772 tracks[track_widx].taginfo_ready = false;
1774 logf("Buffering track:%d/%d", track_widx, track_ridx);
1775 /* Get track name from current playlist read position. */
1776 while ((trackname = playlist_peek(last_peek_offset)) != NULL)
1778 /* Handle broken playlists. */
1779 fd = open(trackname, O_RDONLY);
1780 if (fd < 0)
1782 logf("Open failed");
1783 /* Skip invalid entry from playlist. */
1784 playlist_skip_entry(NULL, last_peek_offset);
1786 else
1787 break;
1790 if (!trackname)
1792 logf("End-of-playlist");
1793 memset(&unbuffered_id3, 0, sizeof(struct mp3entry));
1794 filling = STATE_END_OF_PLAYLIST;
1796 if (thistrack_id3->length == 0 && thistrack_id3->filesize == 0)
1798 /* Stop playback if no valid track was found. */
1799 audio_stop_playback();
1802 return false;
1805 tracks[track_widx].filesize = filesize(fd);
1807 if (offset > tracks[track_widx].filesize)
1808 offset = 0;
1810 /* Set default values */
1811 if (start_play)
1813 buf_set_watermark(filebuflen/2);
1814 dsp_configure(ci.dsp, DSP_RESET, 0);
1815 playlist_update_resume_info(audio_current_track());
1818 /* Get track metadata if we don't already have it. */
1819 if (tracks[track_widx].id3_hid < 0)
1821 tracks[track_widx].id3_hid = bufopen(trackname, 0, TYPE_ID3, NULL);
1823 if (tracks[track_widx].id3_hid < 0)
1825 /* Buffer is full. */
1826 get_metadata(&unbuffered_id3, fd, trackname);
1827 last_peek_offset--;
1828 close(fd);
1829 logf("buffer is full for now");
1830 filling = STATE_FULL;
1831 return false;
1834 if (track_widx == track_ridx)
1836 /* TODO: Superfluos buffering call? */
1837 buf_request_buffer_handle(tracks[track_widx].id3_hid);
1838 struct mp3entry *id3 = bufgetid3(tracks[track_widx].id3_hid);
1839 if (id3)
1841 copy_mp3entry(thistrack_id3, id3);
1842 thistrack_id3->offset = offset;
1844 else
1845 memset(thistrack_id3, 0, sizeof(struct mp3entry));
1848 if (start_play)
1850 playlist_update_resume_info(audio_current_track());
1854 close(fd);
1855 track_load_started = true; /* Remember that we've started loading a track */
1856 return true;
1859 /* Second part of the track loading: We now have the metadata available, so we
1860 can load the codec, the album art and finally the audio data.
1861 This is called on the audio thread after the buffering thread calls the
1862 buffering_handle_finished_callback callback. */
1863 static void audio_finish_load_track(void)
1865 size_t file_offset = 0;
1866 size_t offset = 0;
1867 bool start_play = start_play_g;
1869 track_load_started = false;
1871 if (tracks[track_widx].id3_hid < 0) {
1872 logf("no metatdata");
1873 return;
1876 struct mp3entry *track_id3;
1878 if (track_widx == track_ridx)
1879 track_id3 = thistrack_id3;
1880 else
1881 track_id3 = bufgetid3(tracks[track_widx].id3_hid);
1883 if (track_id3->length == 0 && track_id3->filesize == 0)
1885 logf("audio_finish_load_track: invalid metadata");
1887 /* Invalid metadata */
1888 bufclose(tracks[track_widx].id3_hid);
1889 tracks[track_widx].id3_hid = -1;
1891 /* Skip invalid entry from playlist. */
1892 playlist_skip_entry(NULL, last_peek_offset--);
1894 /* load next track */
1895 LOGFQUEUE("audio > audio Q_AUDIO_FILL_BUFFER %d", (int)start_play);
1896 queue_post(&audio_queue, Q_AUDIO_FILL_BUFFER, start_play);
1898 return;
1900 /* Try to load a cuesheet for the track */
1901 if (curr_cue)
1903 char cuepath[MAX_PATH];
1904 if (look_for_cuesheet_file(track_id3->path, cuepath))
1906 void *temp;
1907 tracks[track_widx].cuesheet_hid =
1908 bufalloc(NULL, sizeof(struct cuesheet), TYPE_CUESHEET);
1909 if (tracks[track_widx].cuesheet_hid >= 0)
1911 bufgetdata(tracks[track_widx].cuesheet_hid,
1912 sizeof(struct cuesheet), &temp);
1913 struct cuesheet *cuesheet = (struct cuesheet*)temp;
1914 if (!parse_cuesheet(cuepath, cuesheet))
1916 bufclose(tracks[track_widx].cuesheet_hid);
1917 track_id3->cuesheet = NULL;
1922 #ifdef HAVE_ALBUMART
1924 int i;
1925 char aa_path[MAX_PATH];
1926 FOREACH_ALBUMART(i)
1928 /* albumart_slots may change during a yield of bufopen,
1929 * but that's no problem */
1930 if (tracks[track_widx].aa_hid[i] >= 0 || !albumart_slots[i].used)
1931 continue;
1932 /* find_albumart will error out if the wps doesn't have AA */
1933 if (find_albumart(track_id3, aa_path, sizeof(aa_path),
1934 &(albumart_slots[i].dim)))
1936 int aa_hid = bufopen(aa_path, 0, TYPE_BITMAP,
1937 &(albumart_slots[i].dim));
1939 if(aa_hid == ERR_BUFFER_FULL)
1941 filling = STATE_FULL;
1942 logf("buffer is full for now");
1943 return; /* No space for track's album art, not an error */
1945 else if (aa_hid < 0)
1947 /* another error, ignore AlbumArt */
1948 logf("Album art loading failed");
1950 tracks[track_widx].aa_hid[i] = aa_hid;
1955 #endif
1957 /* Load the codec. */
1958 if (!audio_loadcodec(start_play))
1960 if (tracks[track_widx].codec_hid == ERR_BUFFER_FULL)
1962 /* No space for codec on buffer, not an error */
1963 filling = STATE_FULL;
1964 return;
1967 /* This is an error condition, either no codec was found, or reading
1968 * the codec file failed part way through, either way, skip the track */
1969 /* FIXME: We should not use splashf from audio thread! */
1970 splashf(HZ*2, "No codec for: %s", track_id3->path);
1971 /* Skip invalid entry from playlist. */
1972 playlist_skip_entry(NULL, last_peek_offset);
1973 return;
1976 track_id3->elapsed = 0;
1977 offset = track_id3->offset;
1979 enum data_type type = TYPE_PACKET_AUDIO;
1981 switch (track_id3->codectype) {
1982 case AFMT_MPA_L1:
1983 case AFMT_MPA_L2:
1984 case AFMT_MPA_L3:
1985 if (offset > 0) {
1986 file_offset = offset;
1987 track_id3->offset = offset;
1989 break;
1991 case AFMT_WAVPACK:
1992 if (offset > 0) {
1993 file_offset = offset;
1994 track_id3->offset = offset;
1995 track_id3->elapsed = track_id3->length / 2;
1997 break;
1999 case AFMT_OGG_VORBIS:
2000 case AFMT_SPEEX:
2001 case AFMT_FLAC:
2002 case AFMT_PCM_WAV:
2003 case AFMT_A52:
2004 case AFMT_MP4_AAC:
2005 case AFMT_MPC:
2006 case AFMT_APE:
2007 case AFMT_WMA:
2008 if (offset > 0)
2009 track_id3->offset = offset;
2010 break;
2012 case AFMT_NSF:
2013 case AFMT_SPC:
2014 case AFMT_SID:
2015 logf("Loading atomic %d",track_id3->codectype);
2016 type = TYPE_ATOMIC_AUDIO;
2017 break;
2020 logf("alt:%s", track_id3->path);
2022 if (file_offset > AUDIO_REBUFFER_GUESS_SIZE)
2023 file_offset -= AUDIO_REBUFFER_GUESS_SIZE;
2024 else if (track_id3->first_frame_offset)
2025 file_offset = track_id3->first_frame_offset;
2026 else
2027 file_offset = 0;
2029 tracks[track_widx].audio_hid = bufopen(track_id3->path, file_offset, type,
2030 NULL);
2032 /* No space left, not an error */
2033 if (tracks[track_widx].audio_hid == ERR_BUFFER_FULL)
2035 filling = STATE_FULL;
2036 logf("buffer is full for now");
2037 return;
2039 else if (tracks[track_widx].audio_hid < 0)
2041 /* another error, do not continue either */
2042 logf("Could not add audio data handle");
2043 return;
2046 /* All required data is now available for the codec. */
2047 tracks[track_widx].taginfo_ready = true;
2049 if (start_play)
2051 ci.curpos=file_offset;
2052 buf_request_buffer_handle(tracks[track_widx].audio_hid);
2055 track_widx = (track_widx + 1) & MAX_TRACK_MASK;
2057 send_event(PLAYBACK_EVENT_TRACK_BUFFER, track_id3);
2059 /* load next track */
2060 LOGFQUEUE("audio > audio Q_AUDIO_FILL_BUFFER");
2061 queue_post(&audio_queue, Q_AUDIO_FILL_BUFFER, 0);
2063 return;
2066 static void audio_fill_file_buffer(bool start_play, size_t offset)
2068 trigger_cpu_boost();
2070 /* No need to rebuffer if there are track skips pending,
2071 * however don't cancel buffering on skipping while filling. */
2072 if (ci.new_track != 0 && filling != STATE_FILLING)
2073 return;
2074 filling = STATE_FILLING;
2076 /* Must reset the buffer before use if trashed or voice only - voice
2077 file size shouldn't have changed so we can go straight from
2078 AUDIOBUF_STATE_VOICED_ONLY to AUDIOBUF_STATE_INITIALIZED */
2079 if (buffer_state != AUDIOBUF_STATE_INITIALIZED)
2080 audio_reset_buffer();
2082 logf("Starting buffer fill");
2084 if (!start_play)
2085 audio_clear_track_entries();
2087 /* Save the current resume position once. */
2088 playlist_update_resume_info(audio_current_track());
2090 audio_load_track(offset, start_play);
2093 static void audio_rebuffer(void)
2095 logf("Forcing rebuffer");
2097 clear_track_info(CUR_TI);
2099 /* Reset track pointers */
2100 track_widx = track_ridx;
2101 audio_clear_track_entries();
2103 /* Reset a possibly interrupted track load */
2104 track_load_started = false;
2106 /* Fill the buffer */
2107 last_peek_offset = -1;
2108 ci.curpos = 0;
2110 if (!CUR_TI->taginfo_ready)
2111 memset(thistrack_id3, 0, sizeof(struct mp3entry));
2113 audio_fill_file_buffer(false, 0);
2116 /* Called on request from the codec to get a new track. This is the codec part
2117 of the track transition. */
2118 static int audio_check_new_track(void)
2120 int track_count = audio_track_count();
2121 int old_track_ridx = track_ridx;
2122 int i, idx;
2123 bool forward;
2124 struct mp3entry *temp = thistrack_id3;
2126 /* Now it's good time to send track finish events. */
2127 send_event(PLAYBACK_EVENT_TRACK_FINISH, thistrack_id3);
2128 /* swap the mp3entry pointers */
2129 thistrack_id3 = othertrack_id3;
2130 othertrack_id3 = temp;
2131 ci.id3 = thistrack_id3;
2132 memset(thistrack_id3, 0, sizeof(struct mp3entry));
2134 if (dir_skip)
2136 dir_skip = false;
2137 /* regardless of the return value we need to rebuffer.
2138 if it fails the old playlist will resume, else the
2139 next dir will start playing */
2140 playlist_next_dir(ci.new_track);
2141 ci.new_track = 0;
2142 audio_rebuffer();
2143 goto skip_done;
2146 if (new_playlist)
2147 ci.new_track = 0;
2149 /* If the playlist isn't that big */
2150 if (automatic_skip)
2152 while (!playlist_check(ci.new_track))
2154 if (ci.new_track >= 0)
2156 LOGFQUEUE("audio >|= codec Q_CODEC_REQUEST_FAILED");
2157 return Q_CODEC_REQUEST_FAILED;
2159 ci.new_track++;
2163 /* Update the playlist */
2164 last_peek_offset -= ci.new_track;
2166 if (playlist_next(ci.new_track) < 0)
2168 LOGFQUEUE("audio >|= codec Q_CODEC_REQUEST_FAILED");
2169 return Q_CODEC_REQUEST_FAILED;
2172 if (new_playlist)
2174 ci.new_track = 1;
2175 new_playlist = false;
2178 /* Save a pointer to the old track to allow later clearing */
2179 prev_ti = CUR_TI;
2181 for (i = 0; i < ci.new_track; i++)
2183 idx = (track_ridx + i) & MAX_TRACK_MASK;
2184 struct mp3entry *id3 = bufgetid3(tracks[idx].id3_hid);
2185 ssize_t offset = buf_handle_offset(tracks[idx].audio_hid);
2186 if (!id3 || offset < 0 || (unsigned)offset > id3->first_frame_offset)
2188 /* We don't have all the audio data for that track, so clear it,
2189 but keep the metadata. */
2190 if (tracks[idx].audio_hid >= 0 && bufclose(tracks[idx].audio_hid))
2192 tracks[idx].audio_hid = -1;
2193 tracks[idx].filesize = 0;
2198 /* Move to the new track */
2199 track_ridx = (track_ridx + ci.new_track) & MAX_TRACK_MASK;
2201 buf_set_base_handle(CUR_TI->audio_hid);
2203 if (automatic_skip)
2205 wps_offset = -ci.new_track;
2208 /* If it is not safe to even skip this many track entries */
2209 if (ci.new_track >= track_count || ci.new_track <= track_count - MAX_TRACK)
2211 ci.new_track = 0;
2212 audio_rebuffer();
2213 goto skip_done;
2216 forward = ci.new_track > 0;
2217 ci.new_track = 0;
2219 /* If the target track is clearly not in memory */
2220 if (CUR_TI->filesize == 0 || !CUR_TI->taginfo_ready)
2222 audio_rebuffer();
2223 goto skip_done;
2226 /* When skipping backwards, it is possible that we've found a track that's
2227 * buffered, but which is around the track-wrap and therefore not the track
2228 * we are looking for */
2229 if (!forward)
2231 int cur_idx = track_ridx;
2232 bool taginfo_ready = true;
2233 /* We've wrapped the buffer backwards if new > old */
2234 bool wrap = track_ridx > old_track_ridx;
2236 while (1)
2238 cur_idx = (cur_idx + 1) & MAX_TRACK_MASK;
2240 /* if we've advanced past the wrap when cur_idx is zeroed */
2241 if (!cur_idx)
2242 wrap = false;
2244 /* if we aren't still on the wrap and we've caught the old track */
2245 if (!(wrap || cur_idx < old_track_ridx))
2246 break;
2248 /* If we hit a track in between without valid tag info, bail */
2249 if (!tracks[cur_idx].taginfo_ready)
2251 taginfo_ready = false;
2252 break;
2255 if (!taginfo_ready)
2257 audio_rebuffer();
2261 skip_done:
2262 audio_update_trackinfo();
2263 LOGFQUEUE("audio >|= codec Q_CODEC_REQUEST_COMPLETE");
2264 return Q_CODEC_REQUEST_COMPLETE;
2267 unsigned long audio_prev_elapsed(void)
2269 return prev_track_elapsed;
2272 static void audio_stop_codec_flush(void)
2274 ci.stop_codec = true;
2275 pcmbuf_pause(true);
2277 while (audio_codec_loaded)
2278 yield();
2280 /* If the audio codec is not loaded any more, and the audio is still
2281 * playing, it is now and _only_ now safe to call this function from the
2282 * audio thread */
2283 if (pcm_is_playing())
2285 pcmbuf_play_stop();
2286 pcmbuf_queue_clear();
2288 pcmbuf_pause(paused);
2291 static void audio_stop_playback(void)
2293 if (playing)
2295 /* If still actively playing here, play out the last samples in the track
2296 * before stopping. A manual stop is actually paused at this point, so
2297 * don't continue playback.
2299 if (!paused)
2300 pcmbuf_play_remainder();
2302 /* If we were playing, save resume information */
2303 struct mp3entry *id3 = NULL;
2305 if (!ci.stop_codec)
2307 /* Set this early, the outside code yields and may allow the codec
2308 to try to wait for a reply on a buffer wait */
2309 ci.stop_codec = true;
2310 id3 = audio_current_track();
2313 /* Save the current playing spot, or NULL if the playlist has ended */
2314 playlist_update_resume_info(id3);
2316 /* TODO: Create auto bookmark too? */
2318 prev_track_elapsed = othertrack_id3->elapsed;
2320 remove_event(BUFFER_EVENT_BUFFER_LOW, buffering_low_buffer_callback);
2323 audio_stop_codec_flush();
2324 paused = false;
2325 playing = false;
2326 track_load_started = false;
2328 filling = STATE_IDLE;
2330 /* Mark all entries null. */
2331 audio_clear_track_entries();
2333 /* Close all tracks */
2334 audio_release_tracks();
2337 static void audio_play_start(size_t offset)
2339 int i;
2341 #if INPUT_SRC_CAPS != 0
2342 audio_set_input_source(AUDIO_SRC_PLAYBACK, SRCF_PLAYBACK);
2343 audio_set_output_source(AUDIO_SRC_PLAYBACK);
2344 #endif
2346 /* Wait for any previously playing audio to flush - TODO: Not necessary? */
2347 paused = false;
2348 audio_stop_codec_flush();
2350 playing = true;
2351 track_load_started = false;
2353 ci.new_track = 0;
2354 ci.seek_time = 0;
2355 wps_offset = 0;
2357 sound_set_volume(global_settings.volume);
2358 track_widx = track_ridx = 0;
2360 /* Clear all track entries. */
2361 for (i = 0; i < MAX_TRACK; i++) {
2362 clear_track_info(&tracks[i]);
2365 last_peek_offset = -1;
2367 /* Officially playing */
2368 queue_reply(&audio_queue, 1);
2370 audio_fill_file_buffer(true, offset);
2372 add_event(BUFFER_EVENT_BUFFER_LOW, false, buffering_low_buffer_callback);
2374 LOGFQUEUE("audio > audio Q_AUDIO_TRACK_CHANGED");
2375 queue_post(&audio_queue, Q_AUDIO_TRACK_CHANGED, 0);
2379 /* Invalidates all but currently playing track. */
2380 static void audio_invalidate_tracks(void)
2382 if (audio_have_tracks())
2384 last_peek_offset = 0;
2385 track_widx = track_ridx;
2387 /* Mark all other entries null (also buffered wrong metadata). */
2388 audio_clear_track_entries();
2390 track_widx = (track_widx + 1) & MAX_TRACK_MASK;
2392 audio_fill_file_buffer(false, 0);
2396 static void audio_new_playlist(void)
2398 /* Prepare to start a new fill from the beginning of the playlist */
2399 last_peek_offset = -1;
2400 if (audio_have_tracks())
2402 if (paused)
2403 skipped_during_pause = true;
2404 track_widx = track_ridx;
2405 audio_clear_track_entries();
2407 track_widx = (track_widx + 1) & MAX_TRACK_MASK;
2409 /* Mark the current track as invalid to prevent skipping back to it */
2410 CUR_TI->taginfo_ready = false;
2413 /* Signal the codec to initiate a track change forward */
2414 new_playlist = true;
2415 ci.new_track = 1;
2417 /* Officially playing */
2418 queue_reply(&audio_queue, 1);
2420 audio_fill_file_buffer(false, 0);
2423 /* Called on manual track skip */
2424 static void audio_initiate_track_change(long direction)
2426 logf("audio_initiate_track_change(%ld)", direction);
2428 ci.new_track += direction;
2429 wps_offset -= direction;
2430 if (paused)
2431 skipped_during_pause = true;
2434 /* Called on manual dir skip */
2435 static void audio_initiate_dir_change(long direction)
2437 dir_skip = true;
2438 ci.new_track = direction;
2439 if (paused)
2440 skipped_during_pause = true;
2443 /* Called when PCM track change is complete */
2444 static void audio_finalise_track_change(void)
2446 logf("audio_finalise_track_change");
2448 if (automatic_skip)
2450 wps_offset = 0;
2451 automatic_skip = false;
2453 /* Invalidate prevtrack_id3 */
2454 memset(othertrack_id3, 0, sizeof(struct mp3entry));
2456 if (prev_ti && prev_ti->audio_hid < 0)
2458 /* No audio left so we clear all the track info. */
2459 clear_track_info(prev_ti);
2462 send_event(PLAYBACK_EVENT_TRACK_CHANGE, thistrack_id3);
2463 playlist_update_resume_info(audio_current_track());
2467 * Layout audio buffer as follows - iram buffer depends on target:
2468 * [|SWAP:iram][|TALK]|FILE|GUARD|PCM|[SWAP:dram[|iram]|]
2470 static void audio_reset_buffer(void)
2472 /* see audio_get_recording_buffer if this is modified */
2473 logf("audio_reset_buffer");
2475 /* If the setup of anything allocated before the file buffer is
2476 changed, do check the adjustments after the buffer_alloc call
2477 as it will likely be affected and need sliding over */
2479 /* Initially set up file buffer as all space available */
2480 malloc_buf = audiobuf + talk_get_bufsize();
2481 /* Align the malloc buf to line size. Especially important to cf
2482 targets that do line reads/writes. */
2483 malloc_buf = (unsigned char *)(((uintptr_t)malloc_buf + 15) & ~15);
2484 filebuf = malloc_buf; /* filebuf line align implied */
2485 filebuflen = audiobufend - filebuf;
2487 filebuflen &= ~15;
2489 /* Subtract whatever the pcm buffer says it used plus the guard buffer */
2490 const size_t pcmbuf_size = pcmbuf_init(filebuf + filebuflen) +GUARD_BUFSIZE;
2492 #ifdef DEBUG
2493 if(pcmbuf_size > filebuflen)
2494 panicf("Not enough memory for pcmbuf_init() : %d > %d",
2495 (int)pcmbuf_size, (int)filebuflen);
2496 #endif
2498 filebuflen -= pcmbuf_size;
2500 /* Make sure filebuflen is a longword multiple after adjustment - filebuf
2501 will already be line aligned */
2502 filebuflen &= ~3;
2504 buffering_reset(filebuf, filebuflen);
2506 /* Clear any references to the file buffer */
2507 buffer_state = AUDIOBUF_STATE_INITIALIZED;
2509 #if defined(ROCKBOX_HAS_LOGF) && defined(LOGF_ENABLE)
2510 /* Make sure everything adds up - yes, some info is a bit redundant but
2511 aids viewing and the sumation of certain variables should add up to
2512 the location of others. */
2514 size_t pcmbufsize;
2515 const unsigned char *pcmbuf = pcmbuf_get_meminfo(&pcmbufsize);
2516 logf("mabuf: %08X", (unsigned)malloc_buf);
2517 logf("fbuf: %08X", (unsigned)filebuf);
2518 logf("fbufe: %08X", (unsigned)(filebuf + filebuflen));
2519 logf("gbuf: %08X", (unsigned)(filebuf + filebuflen));
2520 logf("gbufe: %08X", (unsigned)(filebuf + filebuflen + GUARD_BUFSIZE));
2521 logf("pcmb: %08X", (unsigned)pcmbuf);
2522 logf("pcmbe: %08X", (unsigned)(pcmbuf + pcmbufsize));
2524 #endif
2527 static void audio_thread(void)
2529 struct queue_event ev;
2531 pcm_postinit();
2533 audio_thread_ready = true;
2535 while (1)
2537 if (filling != STATE_FILLING) {
2538 /* End of buffering, let's calculate the watermark and unboost */
2539 set_filebuf_watermark();
2540 cancel_cpu_boost();
2543 if (!pcmbuf_queue_scan(&ev))
2544 queue_wait_w_tmo(&audio_queue, &ev, HZ/2);
2546 switch (ev.id) {
2548 case Q_AUDIO_FILL_BUFFER:
2549 LOGFQUEUE("audio < Q_AUDIO_FILL_BUFFER %d", (int)ev.data);
2550 audio_fill_file_buffer((bool)ev.data, 0);
2551 break;
2553 case Q_AUDIO_FINISH_LOAD:
2554 LOGFQUEUE("audio < Q_AUDIO_FINISH_LOAD");
2555 audio_finish_load_track();
2556 break;
2558 case Q_AUDIO_PLAY:
2559 LOGFQUEUE("audio < Q_AUDIO_PLAY");
2560 if (playing && ev.data <= 0)
2561 audio_new_playlist();
2562 else
2564 audio_stop_playback();
2565 audio_play_start((size_t)ev.data);
2567 break;
2569 case Q_AUDIO_STOP:
2570 LOGFQUEUE("audio < Q_AUDIO_STOP");
2571 if (playing)
2572 audio_stop_playback();
2573 if (ev.data != 0)
2574 queue_clear(&audio_queue);
2575 break;
2577 case Q_AUDIO_PAUSE:
2578 LOGFQUEUE("audio < Q_AUDIO_PAUSE");
2579 if (!(bool) ev.data && skipped_during_pause && !pcmbuf_is_crossfade_active())
2580 pcmbuf_play_stop(); /* Flush old track on resume after skip */
2581 skipped_during_pause = false;
2582 if (!playing)
2583 break;
2584 pcmbuf_pause((bool)ev.data);
2585 paused = (bool)ev.data;
2586 break;
2588 case Q_AUDIO_SKIP:
2589 LOGFQUEUE("audio < Q_AUDIO_SKIP");
2590 audio_initiate_track_change((long)ev.data);
2591 break;
2593 case Q_AUDIO_PRE_FF_REWIND:
2594 LOGFQUEUE("audio < Q_AUDIO_PRE_FF_REWIND");
2595 if (!playing)
2596 break;
2597 pcmbuf_pause(true);
2598 break;
2600 case Q_AUDIO_FF_REWIND:
2601 LOGFQUEUE("audio < Q_AUDIO_FF_REWIND");
2602 if (!playing)
2603 break;
2604 if (automatic_skip)
2606 /* An automatic track skip is in progress. Finalize it,
2607 then go back to the previous track */
2608 audio_finalise_track_change();
2609 ci.new_track = -1;
2611 ci.seek_time = (long)ev.data+1;
2612 break;
2614 case Q_AUDIO_CHECK_NEW_TRACK:
2615 LOGFQUEUE("audio < Q_AUDIO_CHECK_NEW_TRACK");
2616 queue_reply(&audio_queue, audio_check_new_track());
2617 break;
2619 case Q_AUDIO_DIR_SKIP:
2620 LOGFQUEUE("audio < Q_AUDIO_DIR_SKIP");
2621 audio_initiate_dir_change(ev.data);
2622 break;
2624 case Q_AUDIO_FLUSH:
2625 LOGFQUEUE("audio < Q_AUDIO_FLUSH");
2626 audio_invalidate_tracks();
2627 break;
2629 case Q_AUDIO_TRACK_CHANGED:
2630 /* PCM track change done */
2631 LOGFQUEUE("audio < Q_AUDIO_TRACK_CHANGED");
2632 audio_finalise_track_change();
2633 break;
2634 #ifndef SIMULATOR
2635 case SYS_USB_CONNECTED:
2636 LOGFQUEUE("audio < SYS_USB_CONNECTED");
2637 if (playing)
2638 audio_stop_playback();
2639 #ifdef PLAYBACK_VOICE
2640 voice_stop();
2641 #endif
2642 usb_acknowledge(SYS_USB_CONNECTED_ACK);
2643 usb_wait_for_disconnect(&audio_queue);
2645 /* Mark all entries null. */
2646 audio_clear_track_entries();
2648 /* release tracks to make sure all handles are closed */
2649 audio_release_tracks();
2650 break;
2651 #endif
2653 case SYS_TIMEOUT:
2654 LOGFQUEUE_SYS_TIMEOUT("audio < SYS_TIMEOUT");
2655 break;
2657 default:
2658 LOGFQUEUE("audio < default");
2659 break;
2660 } /* end switch */
2661 } /* end while */
2664 /* Initialize the audio system - called from init() in main.c.
2665 * Last function because of all the references to internal symbols
2667 void audio_init(void)
2669 unsigned int audio_thread_id;
2671 /* Can never do this twice */
2672 if (audio_is_initialized)
2674 logf("audio: already initialized");
2675 return;
2678 logf("audio: initializing");
2680 /* Initialize queues before giving control elsewhere in case it likes
2681 to send messages. Thread creation will be delayed however so nothing
2682 starts running until ready if something yields such as talk_init. */
2683 queue_init(&audio_queue, true);
2684 queue_init(&codec_queue, false);
2685 queue_init(&pcmbuf_queue, false);
2687 pcm_init();
2689 /* Initialize codec api. */
2690 ci.read_filebuf = codec_filebuf_callback;
2691 ci.pcmbuf_insert = codec_pcmbuf_insert_callback;
2692 ci.codec_get_buffer = codec_get_buffer;
2693 ci.request_buffer = codec_request_buffer_callback;
2694 ci.advance_buffer = codec_advance_buffer_callback;
2695 ci.advance_buffer_loc = codec_advance_buffer_loc_callback;
2696 ci.request_next_track = codec_request_next_track_callback;
2697 ci.seek_buffer = codec_seek_buffer_callback;
2698 ci.seek_complete = codec_seek_complete_callback;
2699 ci.set_elapsed = codec_set_elapsed_callback;
2700 ci.set_offset = codec_set_offset_callback;
2701 ci.configure = codec_configure_callback;
2702 ci.discard_codec = codec_discard_codec_callback;
2703 ci.dsp = (struct dsp_config *)dsp_configure(NULL, DSP_MYDSP,
2704 CODEC_IDX_AUDIO);
2706 thistrack_id3 = &mp3entry_buf[0];
2707 othertrack_id3 = &mp3entry_buf[1];
2709 /* cuesheet support */
2710 if (global_settings.cuesheet)
2711 curr_cue = (struct cuesheet*)buffer_alloc(sizeof(struct cuesheet));
2713 /* initialize the buffer */
2714 filebuf = audiobuf;
2716 /* audio_reset_buffer must to know the size of voice buffer so init
2717 talk first */
2718 talk_init();
2720 codec_thread_id = create_thread(
2721 codec_thread, codec_stack, sizeof(codec_stack),
2722 CREATE_THREAD_FROZEN,
2723 codec_thread_name IF_PRIO(, PRIORITY_PLAYBACK)
2724 IF_COP(, CPU));
2726 queue_enable_queue_send(&codec_queue, &codec_queue_sender_list,
2727 codec_thread_id);
2729 audio_thread_id = create_thread(audio_thread, audio_stack,
2730 sizeof(audio_stack), CREATE_THREAD_FROZEN,
2731 audio_thread_name IF_PRIO(, PRIORITY_USER_INTERFACE)
2732 IF_COP(, CPU));
2734 queue_enable_queue_send(&audio_queue, &audio_queue_sender_list,
2735 audio_thread_id);
2737 #ifdef PLAYBACK_VOICE
2738 voice_thread_init();
2739 #endif
2741 /* Set crossfade setting for next buffer init which should be about... */
2742 pcmbuf_crossfade_enable(global_settings.crossfade);
2744 /* initialize the buffering system */
2746 buffering_init();
2747 /* ...now! Set up the buffers */
2748 audio_reset_buffer();
2750 int i;
2751 for(i = 0; i < MAX_TRACK; i++)
2753 tracks[i].audio_hid = -1;
2754 tracks[i].id3_hid = -1;
2755 tracks[i].codec_hid = -1;
2756 tracks[i].cuesheet_hid = -1;
2758 #ifdef HAVE_ALBUMART
2759 FOREACH_ALBUMART(i)
2761 int j;
2762 for (j = 0; j < MAX_TRACK; j++)
2764 tracks[j].aa_hid[i] = -1;
2767 #endif
2769 add_event(BUFFER_EVENT_REBUFFER, false, buffering_handle_rebuffer_callback);
2770 add_event(BUFFER_EVENT_FINISHED, false, buffering_handle_finished_callback);
2772 /* Probably safe to say */
2773 audio_is_initialized = true;
2775 sound_settings_apply();
2776 #ifdef HAVE_DISK_STORAGE
2777 audio_set_buffer_margin(global_settings.buffer_margin);
2778 #endif
2780 /* it's safe to let the threads run now */
2781 #ifdef PLAYBACK_VOICE
2782 voice_thread_resume();
2783 #endif
2784 thread_thaw(codec_thread_id);
2785 thread_thaw(audio_thread_id);
2787 } /* audio_init */
2789 bool audio_is_thread_ready(void)
2791 return audio_thread_ready;