Make sd_present() and mmc_present() look only at the actual presence of a card, not...
[kugel-rb.git] / apps / playback.c
blob7bd3f252ae673c1a73679bef919a802714011443
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 #include "albumart.h"
68 #endif
69 #include "lang.h"
70 #include "bookmark.h"
71 #include "misc.h"
72 #include "sound.h"
73 #include "metadata.h"
74 #include "splash.h"
75 #include "talk.h"
76 #include "ata_idle_notify.h"
78 #ifdef HAVE_RECORDING
79 #include "recording.h"
80 #include "pcm_record.h"
81 #endif
83 #ifdef IPOD_ACCESSORY_PROTOCOL
84 #include "iap.h"
85 #endif
87 #define PLAYBACK_VOICE
89 /* amount of guess-space to allow for codecs that must hunt and peck
90 * for their correct seeek target, 32k seems a good size */
91 #define AUDIO_REBUFFER_GUESS_SIZE (1024*32)
93 /* Define LOGF_ENABLE to enable logf output in this file */
94 /*#define LOGF_ENABLE*/
95 #include "logf.h"
97 /* macros to enable logf for queues
98 logging on SYS_TIMEOUT can be disabled */
99 #ifdef SIMULATOR
100 /* Define this for logf output of all queuing except SYS_TIMEOUT */
101 #define PLAYBACK_LOGQUEUES
102 /* Define this to logf SYS_TIMEOUT messages */
103 /*#define PLAYBACK_LOGQUEUES_SYS_TIMEOUT*/
104 #endif
106 #ifdef PLAYBACK_LOGQUEUES
107 #define LOGFQUEUE logf
108 #else
109 #define LOGFQUEUE(...)
110 #endif
112 #ifdef PLAYBACK_LOGQUEUES_SYS_TIMEOUT
113 #define LOGFQUEUE_SYS_TIMEOUT logf
114 #else
115 #define LOGFQUEUE_SYS_TIMEOUT(...)
116 #endif
119 /* Define one constant that includes recording related functionality */
120 #if defined(HAVE_RECORDING) && !defined(SIMULATOR)
121 #define AUDIO_HAVE_RECORDING
122 #endif
124 enum {
125 Q_NULL = 0,
126 Q_AUDIO_PLAY = 1,
127 Q_AUDIO_STOP,
128 Q_AUDIO_PAUSE,
129 Q_AUDIO_SKIP,
130 Q_AUDIO_PRE_FF_REWIND,
131 Q_AUDIO_FF_REWIND,
132 Q_AUDIO_CHECK_NEW_TRACK,
133 Q_AUDIO_FLUSH,
134 Q_AUDIO_TRACK_CHANGED,
135 Q_AUDIO_DIR_SKIP,
136 Q_AUDIO_POSTINIT,
137 Q_AUDIO_FILL_BUFFER,
138 Q_AUDIO_FINISH_LOAD,
139 Q_CODEC_REQUEST_COMPLETE,
140 Q_CODEC_REQUEST_FAILED,
142 Q_CODEC_LOAD,
143 Q_CODEC_LOAD_DISK,
145 #ifdef AUDIO_HAVE_RECORDING
146 Q_ENCODER_LOAD_DISK,
147 Q_ENCODER_RECORD,
148 #endif
150 Q_CODEC_DO_CALLBACK,
153 enum filling_state {
154 STATE_IDLE, /* audio is stopped: nothing to do */
155 STATE_FILLING, /* adding tracks to the buffer */
156 STATE_FULL, /* can't add any more tracks */
157 STATE_END_OF_PLAYLIST, /* all remaining tracks have been added */
158 STATE_FINISHED, /* all remaining tracks are fully buffered */
161 #define MAX_TRACK 128
163 #define MAX_TRACK_MASK (MAX_TRACK-1)
165 /* As defined in plugins/lib/xxx2wav.h */
166 #define GUARD_BUFSIZE (32*1024)
168 /* As defined in plugin.lds */
169 #if defined(CPU_PP)
170 #define CODEC_IRAM_ORIGIN ((unsigned char *)0x4000c000)
171 #define CODEC_IRAM_SIZE ((size_t)0xc000)
172 #elif defined(IAUDIO_X5) || defined(IAUDIO_M5)
173 #define CODEC_IRAM_ORIGIN ((unsigned char *)0x10010000)
174 #define CODEC_IRAM_SIZE ((size_t)0x10000)
175 #else
176 #define CODEC_IRAM_ORIGIN ((unsigned char *)0x1000c000)
177 #define CODEC_IRAM_SIZE ((size_t)0xc000)
178 #endif
180 bool audio_is_initialized = false;
181 static bool audio_thread_ready SHAREDBSS_ATTR = false;
183 /* Variables are commented with the threads that use them: *
184 * A=audio, C=codec, V=voice. A suffix of - indicates that *
185 * the variable is read but not updated on that thread. */
186 /* TBD: Split out "audio" and "playback" (ie. calling) threads */
188 /* Main state control */
189 static volatile bool audio_codec_loaded SHAREDBSS_ATTR = false; /* Codec loaded? (C/A-) */
190 static volatile bool playing SHAREDBSS_ATTR = false; /* Is audio playing? (A) */
191 static volatile bool paused SHAREDBSS_ATTR = false; /* Is audio paused? (A/C-) */
193 /* Ring buffer where compressed audio and codecs are loaded */
194 static unsigned char *filebuf = NULL; /* Start of buffer (A/C-) */
195 static unsigned char *malloc_buf = NULL; /* Start of malloc buffer (A/C-) */
196 /* FIXME: make filebuflen static */
197 size_t filebuflen = 0; /* Size of buffer (A/C-) */
198 /* FIXME: make buf_ridx (C/A-) */
200 /* Possible arrangements of the buffer */
201 static int buffer_state = AUDIOBUF_STATE_TRASHED; /* Buffer state */
203 /* These are used to store the current and next (or prev if the current is the last)
204 * mp3entry's in a round-robin system. This guarentees that the pointer returned
205 * by audio_current/next_track will be valid for the full duration of the
206 * currently playing track */
207 static struct mp3entry mp3entry_buf[2];
208 static struct mp3entry *thistrack_id3, /* the currently playing track */
209 *othertrack_id3; /* prev track during track-change-transition, or end of playlist,
210 * next track otherwise */
211 static struct mp3entry unbuffered_id3; /* the id3 for the first unbuffered track */
213 /* for cuesheet support */
214 static struct cuesheet *curr_cue = NULL;
216 /* Track info structure about songs in the file buffer (A/C-) */
217 struct track_info {
218 int audio_hid; /* The ID for the track's buffer handle */
219 int id3_hid; /* The ID for the track's metadata handle */
220 int codec_hid; /* The ID for the track's codec handle */
221 #ifdef HAVE_ALBUMART
222 int aa_hid; /* The ID for the track's album art handle */
223 #endif
224 int cuesheet_hid; /* The ID for the track's parsed cueesheet handle */
226 size_t filesize; /* File total length */
228 bool taginfo_ready; /* Is metadata read */
231 static struct track_info tracks[MAX_TRACK];
232 static volatile int track_ridx = 0; /* Track being decoded (A/C-) */
233 static int track_widx = 0; /* Track being buffered (A) */
235 #define CUR_TI (&tracks[track_ridx]) /* Playing track info pointer (A/C-) */
236 static struct track_info *prev_ti = NULL; /* Pointer to the previously played
237 track */
239 /* Information used only for filling the buffer */
240 /* Playlist steps from playing track to next track to be buffered (A) */
241 static int last_peek_offset = 0;
243 /* Scrobbler support */
244 static unsigned long prev_track_elapsed = 0; /* Previous track elapsed time (C/A-)*/
246 static enum filling_state filling;
248 /* Track change controls */
249 static bool automatic_skip = false; /* Who initiated in-progress skip? (C/A-) */
250 static bool dir_skip = false; /* Is a directory skip pending? (A) */
251 static bool new_playlist = false; /* Are we starting a new playlist? (A) */
252 static int wps_offset = 0; /* Pending track change offset, to keep WPS responsive (A) */
253 static bool skipped_during_pause = false; /* Do we need to clear the PCM buffer when playback resumes (A) */
255 static bool start_play_g = false; /* Used by audio_load_track to notify
256 audio_finish_load_track about start_play */
258 /* True when a track load is in progress, i.e. audio_load_track() has returned
259 * but audio_finish_load_track() hasn't been called yet. Used to avoid allowing
260 * audio_load_track() to get called twice in a row, which would cause problems.
262 static bool track_load_started = false;
264 /* Set to true if the codec thread should send an audio stop request
265 * (typically because the end of the playlist has been reached).
267 static bool codec_requested_stop = false;
269 #ifdef HAVE_DISK_STORAGE
270 static size_t buffer_margin = 5; /* Buffer margin aka anti-skip buffer (A/C-) */
271 #endif
273 /* Multiple threads */
274 /* Set the watermark to trigger buffer fill (A/C) */
275 static void set_filebuf_watermark(void);
277 /* Audio thread */
278 static struct event_queue audio_queue SHAREDBSS_ATTR;
279 static struct queue_sender_list audio_queue_sender_list SHAREDBSS_ATTR;
280 static long audio_stack[(DEFAULT_STACK_SIZE + 0x1000)/sizeof(long)];
281 static const char audio_thread_name[] = "audio";
283 static void audio_thread(void);
284 static void audio_initiate_track_change(long direction);
285 static bool audio_have_tracks(void);
286 static void audio_reset_buffer(void);
287 static void audio_stop_playback(void);
289 /* Codec thread */
290 extern struct codec_api ci;
291 static struct event_queue codec_queue SHAREDBSS_ATTR;
292 static struct queue_sender_list codec_queue_sender_list;
293 static long codec_stack[(DEFAULT_STACK_SIZE + 0x2000)/sizeof(long)]
294 IBSS_ATTR;
295 static const char codec_thread_name[] = "codec";
296 unsigned int codec_thread_id; /* For modifying thread priority later. */
298 /* PCM buffer messaging */
299 static struct event_queue pcmbuf_queue SHAREDBSS_ATTR;
301 /* Function to be called by pcm buffer callbacks.
302 * Permissible Context(s): Audio interrupt
304 static void pcmbuf_callback_queue_post(long id, intptr_t data)
306 /* No lock since we're already in audio interrupt context */
307 queue_post(&pcmbuf_queue, id, data);
310 /* Scan the pcmbuf queue and return true if a message pulled.
311 * Permissible Context(s): Thread
313 static bool pcmbuf_queue_scan(struct queue_event *ev)
315 if (!queue_empty(&pcmbuf_queue))
317 /* Transfer message to audio queue */
318 pcm_play_lock();
319 /* Pull message - never, ever any blocking call! */
320 queue_wait_w_tmo(&pcmbuf_queue, ev, 0);
321 pcm_play_unlock();
322 return true;
325 return false;
328 /* Clear the pcmbuf queue of messages
329 * Permissible Context(s): Thread
331 static void pcmbuf_queue_clear(void)
333 pcm_play_lock();
334 queue_clear(&pcmbuf_queue);
335 pcm_play_unlock();
338 /* --- Helper functions --- */
340 static struct mp3entry *bufgetid3(int handle_id)
342 if (handle_id < 0)
343 return NULL;
345 struct mp3entry *id3;
346 ssize_t ret = bufgetdata(handle_id, 0, (void *)&id3);
348 if (ret < 0 || ret != sizeof(struct mp3entry))
349 return NULL;
351 return id3;
354 static bool clear_track_info(struct track_info *track)
356 /* bufclose returns true if the handle is not found, or if it is closed
357 * successfully, so these checks are safe on non-existant handles */
358 if (!track)
359 return false;
361 if (track->codec_hid >= 0) {
362 if (bufclose(track->codec_hid))
363 track->codec_hid = -1;
364 else
365 return false;
368 if (track->id3_hid >= 0) {
369 if (bufclose(track->id3_hid))
370 track->id3_hid = -1;
371 else
372 return false;
375 if (track->audio_hid >= 0) {
376 if (bufclose(track->audio_hid))
377 track->audio_hid = -1;
378 else
379 return false;
382 #ifdef HAVE_ALBUMART
383 if (track->aa_hid >= 0) {
384 if (bufclose(track->aa_hid))
385 track->aa_hid = -1;
386 else
387 return false;
389 #endif
391 if (track->cuesheet_hid >= 0) {
392 if (bufclose(track->cuesheet_hid))
393 track->cuesheet_hid = -1;
394 else
395 return false;
398 track->filesize = 0;
399 track->taginfo_ready = false;
401 return true;
404 /* --- External interfaces --- */
406 /* This sends a stop message and the audio thread will dump all it's
407 subsequenct messages */
408 void audio_hard_stop(void)
410 /* Stop playback */
411 LOGFQUEUE("audio >| audio Q_AUDIO_STOP: 1");
412 queue_send(&audio_queue, Q_AUDIO_STOP, 1);
413 #ifdef PLAYBACK_VOICE
414 voice_stop();
415 #endif
418 bool audio_restore_playback(int type)
420 switch (type)
422 case AUDIO_WANT_PLAYBACK:
423 if (buffer_state != AUDIOBUF_STATE_INITIALIZED)
424 audio_reset_buffer();
425 return true;
426 case AUDIO_WANT_VOICE:
427 if (buffer_state == AUDIOBUF_STATE_TRASHED)
428 audio_reset_buffer();
429 return true;
430 default:
431 return false;
435 unsigned char *audio_get_buffer(bool talk_buf, size_t *buffer_size)
437 unsigned char *buf, *end;
439 if (audio_is_initialized)
441 audio_hard_stop();
443 /* else buffer_state will be AUDIOBUF_STATE_TRASHED at this point */
445 /* Reset the buffering thread so that it doesn't try to use the data */
446 buffering_reset(filebuf, filebuflen);
448 if (buffer_size == NULL)
450 /* Special case for talk_init to use since it already knows it's
451 trashed */
452 buffer_state = AUDIOBUF_STATE_TRASHED;
453 return NULL;
456 if (talk_buf || buffer_state == AUDIOBUF_STATE_TRASHED
457 || !talk_voice_required())
459 logf("get buffer: talk, audio");
460 /* Ok to use everything from audiobuf to audiobufend - voice is loaded,
461 the talk buffer is not needed because voice isn't being used, or
462 could be AUDIOBUF_STATE_TRASHED already. If state is
463 AUDIOBUF_STATE_VOICED_ONLY, no problem as long as memory isn't written
464 without the caller knowing what's going on. Changing certain settings
465 may move it to a worse condition but the memory in use by something
466 else will remain undisturbed.
468 if (buffer_state != AUDIOBUF_STATE_TRASHED)
470 talk_buffer_steal();
471 buffer_state = AUDIOBUF_STATE_TRASHED;
474 buf = audiobuf;
475 end = audiobufend;
477 else
479 /* Safe to just return this if already AUDIOBUF_STATE_VOICED_ONLY or
480 still AUDIOBUF_STATE_INITIALIZED */
481 /* Skip talk buffer and move pcm buffer to end to maximize available
482 contiguous memory - no audio running means voice will not need the
483 swap space */
484 logf("get buffer: audio");
485 buf = audiobuf + talk_get_bufsize();
486 end = audiobufend - pcmbuf_init(audiobufend);
487 buffer_state = AUDIOBUF_STATE_VOICED_ONLY;
490 *buffer_size = end - buf;
492 return buf;
495 int audio_buffer_state(void)
497 return buffer_state;
500 #ifdef HAVE_RECORDING
501 unsigned char *audio_get_recording_buffer(size_t *buffer_size)
503 /* Stop audio, voice and obtain all available buffer space */
504 audio_hard_stop();
505 talk_buffer_steal();
507 unsigned char *end = audiobufend;
508 buffer_state = AUDIOBUF_STATE_TRASHED;
509 *buffer_size = end - audiobuf;
511 return (unsigned char *)audiobuf;
514 bool audio_load_encoder(int afmt)
516 #ifndef SIMULATOR
517 const char *enc_fn = get_codec_filename(afmt | CODEC_TYPE_ENCODER);
518 if (!enc_fn)
519 return false;
521 audio_remove_encoder();
522 ci.enc_codec_loaded = 0; /* clear any previous error condition */
524 LOGFQUEUE("codec > Q_ENCODER_LOAD_DISK");
525 queue_post(&codec_queue, Q_ENCODER_LOAD_DISK, (intptr_t)enc_fn);
527 while (ci.enc_codec_loaded == 0)
528 yield();
530 logf("codec loaded: %d", ci.enc_codec_loaded);
532 return ci.enc_codec_loaded > 0;
533 #else
534 (void)afmt;
535 return true;
536 #endif
537 } /* audio_load_encoder */
539 void audio_remove_encoder(void)
541 #ifndef SIMULATOR
542 /* force encoder codec unload (if currently loaded) */
543 if (ci.enc_codec_loaded <= 0)
544 return;
546 ci.stop_encoder = true;
547 while (ci.enc_codec_loaded > 0)
548 yield();
549 #endif
550 } /* audio_remove_encoder */
552 #endif /* HAVE_RECORDING */
554 #ifdef HAVE_ALBUMART
555 int audio_current_aa_hid(void)
557 int cur_idx;
558 int offset = ci.new_track + wps_offset;
560 cur_idx = track_ridx + offset;
561 cur_idx &= MAX_TRACK_MASK;
563 return tracks[cur_idx].aa_hid;
565 #endif
567 struct mp3entry* audio_current_track(void)
569 const char *filename;
570 struct playlist_track_info trackinfo;
571 int cur_idx;
572 int offset = ci.new_track + wps_offset;
573 struct mp3entry *write_id3;
575 cur_idx = (track_ridx + offset) & MAX_TRACK_MASK;
577 if (cur_idx == track_ridx && *thistrack_id3->path)
579 /* The usual case */
580 if (tracks[cur_idx].cuesheet_hid >= 0)
582 bufread(tracks[cur_idx].cuesheet_hid, sizeof(struct cuesheet), curr_cue);
583 thistrack_id3->cuesheet = curr_cue;
584 cue_spoof_id3(thistrack_id3->cuesheet, thistrack_id3);
586 return thistrack_id3;
588 else if (automatic_skip && offset == -1 && *othertrack_id3->path)
590 /* We're in a track transition. The codec has moved on to the next track,
591 but the audio being played is still the same (now previous) track.
592 othertrack_id3.elapsed is being updated in an ISR by
593 codec_pcmbuf_position_callback */
594 if (tracks[cur_idx].cuesheet_hid >= 0)
596 bufread(tracks[cur_idx].cuesheet_hid, sizeof(struct cuesheet), curr_cue);
597 othertrack_id3->cuesheet = curr_cue;
598 cue_spoof_id3(othertrack_id3->cuesheet, othertrack_id3);
600 return othertrack_id3;
603 if (offset != 0)
605 /* Codec may be using thistrack_id3, so it must not be overwritten.
606 If this is a manual skip, othertrack_id3 will become
607 thistrack_id3 in audio_check_new_track().
608 FIXME: If this is an automatic skip, it probably means multiple
609 short tracks fit in the PCM buffer. Overwriting othertrack_id3
610 can lead to an incorrect value later.
611 Note that othertrack_id3 may also be used for next track.
613 write_id3 = othertrack_id3;
615 else
617 write_id3 = thistrack_id3;
620 if (tracks[cur_idx].id3_hid >= 0)
622 /* The current track's info has been buffered but not read yet, so get it */
623 if (bufread(tracks[cur_idx].id3_hid, sizeof(struct mp3entry), write_id3)
624 == sizeof(struct mp3entry))
625 return write_id3;
628 /* We didn't find the ID3 metadata, so we fill temp_id3 with the little info
629 we have and return that. */
631 memset(write_id3, 0, sizeof(struct mp3entry));
633 playlist_get_track_info(NULL, playlist_next(0)+wps_offset, &trackinfo);
634 filename = trackinfo.filename;
635 if (!filename)
636 filename = "No file!";
638 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
639 if (tagcache_fill_tags(write_id3, filename))
640 return write_id3;
641 #endif
643 strlcpy(write_id3->path, filename, sizeof(write_id3->path));
644 write_id3->title = strrchr(write_id3->path, '/');
645 if (!write_id3->title)
646 write_id3->title = &write_id3->path[0];
647 else
648 write_id3->title++;
650 return write_id3;
653 struct mp3entry* audio_next_track(void)
655 int next_idx;
656 int offset = ci.new_track + wps_offset;
658 if (!audio_have_tracks())
659 return NULL;
661 if (wps_offset == -1 && *thistrack_id3->path)
663 /* We're in a track transition. The next track for the WPS is the one
664 currently being decoded. */
665 return thistrack_id3;
668 next_idx = (track_ridx + offset + 1) & MAX_TRACK_MASK;
670 if (tracks[next_idx].id3_hid >= 0)
672 if (bufread(tracks[next_idx].id3_hid, sizeof(struct mp3entry), othertrack_id3)
673 == sizeof(struct mp3entry))
674 return othertrack_id3;
675 else
676 return NULL;
679 if (next_idx == track_widx)
681 /* The next track hasn't been buffered yet, so we return the static
682 version of its metadata. */
683 return &unbuffered_id3;
686 return NULL;
689 void audio_play(long offset)
691 logf("audio_play");
693 #ifdef PLAYBACK_VOICE
694 /* Truncate any existing voice output so we don't have spelling
695 * etc. over the first part of the played track */
696 talk_force_shutup();
697 #endif
699 /* Start playback */
700 LOGFQUEUE("audio >| audio Q_AUDIO_PLAY: %ld", offset);
701 /* Don't return until playback has actually started */
702 queue_send(&audio_queue, Q_AUDIO_PLAY, offset);
705 void audio_stop(void)
707 /* Stop playback */
708 LOGFQUEUE("audio >| audio Q_AUDIO_STOP");
709 /* Don't return until playback has actually stopped */
710 queue_send(&audio_queue, Q_AUDIO_STOP, 0);
713 void audio_pause(void)
715 LOGFQUEUE("audio >| audio Q_AUDIO_PAUSE");
716 /* Don't return until playback has actually paused */
717 queue_send(&audio_queue, Q_AUDIO_PAUSE, true);
720 void audio_resume(void)
722 LOGFQUEUE("audio >| audio Q_AUDIO_PAUSE resume");
723 /* Don't return until playback has actually resumed */
724 queue_send(&audio_queue, Q_AUDIO_PAUSE, false);
727 void audio_skip(int direction)
729 if (playlist_check(ci.new_track + wps_offset + direction))
731 if (global_settings.beep)
732 pcmbuf_beep(2000, 100, 2500*global_settings.beep);
734 LOGFQUEUE("audio > audio Q_AUDIO_SKIP %d", direction);
735 queue_post(&audio_queue, Q_AUDIO_SKIP, direction);
736 /* Update wps while our message travels inside deep playback queues. */
737 wps_offset += direction;
739 else
741 /* No more tracks. */
742 if (global_settings.beep)
743 pcmbuf_beep(1000, 100, 1500*global_settings.beep);
747 void audio_next(void)
749 audio_skip(1);
752 void audio_prev(void)
754 audio_skip(-1);
757 void audio_next_dir(void)
759 LOGFQUEUE("audio > audio Q_AUDIO_DIR_SKIP 1");
760 queue_post(&audio_queue, Q_AUDIO_DIR_SKIP, 1);
763 void audio_prev_dir(void)
765 LOGFQUEUE("audio > audio Q_AUDIO_DIR_SKIP -1");
766 queue_post(&audio_queue, Q_AUDIO_DIR_SKIP, -1);
769 void audio_pre_ff_rewind(void)
771 LOGFQUEUE("audio > audio Q_AUDIO_PRE_FF_REWIND");
772 queue_post(&audio_queue, Q_AUDIO_PRE_FF_REWIND, 0);
775 void audio_ff_rewind(long newpos)
777 LOGFQUEUE("audio > audio Q_AUDIO_FF_REWIND");
778 queue_post(&audio_queue, Q_AUDIO_FF_REWIND, newpos);
781 void audio_flush_and_reload_tracks(void)
783 LOGFQUEUE("audio > audio Q_AUDIO_FLUSH");
784 queue_post(&audio_queue, Q_AUDIO_FLUSH, 0);
787 void audio_error_clear(void)
789 #ifdef AUDIO_HAVE_RECORDING
790 pcm_rec_error_clear();
791 #endif
794 int audio_status(void)
796 int ret = 0;
798 if (playing)
799 ret |= AUDIO_STATUS_PLAY;
801 if (paused)
802 ret |= AUDIO_STATUS_PAUSE;
804 #ifdef HAVE_RECORDING
805 /* Do this here for constitency with mpeg.c version */
806 ret |= pcm_rec_status();
807 #endif
809 return ret;
812 int audio_get_file_pos(void)
814 return 0;
817 #ifdef HAVE_DISK_STORAGE
818 void audio_set_buffer_margin(int setting)
820 static const unsigned short lookup[] = {5, 15, 30, 60, 120, 180, 300, 600};
821 buffer_margin = lookup[setting];
822 logf("buffer margin: %ld", (long)buffer_margin);
823 set_filebuf_watermark();
825 #endif
827 /* Take necessary steps to enable or disable the crossfade setting */
828 void audio_set_crossfade(int enable)
830 size_t offset;
831 bool was_playing;
832 size_t size;
834 /* Tell it the next setting to use */
835 pcmbuf_crossfade_enable(enable);
837 /* Return if size hasn't changed or this is too early to determine
838 which in the second case there's no way we could be playing
839 anything at all */
840 if (pcmbuf_is_same_size())
842 /* This function is a copout and just syncs some variables -
843 to be removed at a later date */
844 pcmbuf_crossfade_enable_finished();
845 return;
848 offset = 0;
849 was_playing = playing;
851 /* Playback has to be stopped before changing the buffer size */
852 if (was_playing)
854 /* Store the track resume position */
855 offset = thistrack_id3->offset;
858 /* Blast it - audio buffer will have to be setup again next time
859 something plays */
860 audio_get_buffer(true, &size);
862 /* Restart playback if audio was running previously */
863 if (was_playing)
864 audio_play(offset);
867 /* --- Routines called from multiple threads --- */
869 static void set_filebuf_watermark(void)
871 if (!filebuf)
872 return; /* Audio buffers not yet set up */
874 #ifdef HAVE_DISK_STORAGE
875 int seconds;
876 int spinup = ata_spinup_time();
877 if (spinup)
878 seconds = (spinup / HZ) + 1;
879 else
880 seconds = 5;
882 seconds += buffer_margin;
883 #else
884 /* flash storage */
885 int seconds = 1;
886 #endif
888 /* bitrate of last track in buffer dictates watermark */
889 struct mp3entry* id3 = NULL;
890 if (tracks[track_widx].taginfo_ready)
891 id3 = bufgetid3(tracks[track_widx].id3_hid);
892 else
893 id3 = bufgetid3(tracks[track_widx-1].id3_hid);
894 if (!id3) {
895 logf("fwmark: No id3 for last track (r%d/w%d), aborting!", track_ridx, track_widx);
896 return;
898 size_t bytes = id3->bitrate * (1000/8) * seconds;
899 buf_set_watermark(bytes);
900 logf("fwmark: %d", bytes);
903 const char *get_codec_filename(int cod_spec)
905 const char *fname;
907 #ifdef HAVE_RECORDING
908 /* Can choose decoder or encoder if one available */
909 int type = cod_spec & CODEC_TYPE_MASK;
910 int afmt = cod_spec & CODEC_AFMT_MASK;
912 if ((unsigned)afmt >= AFMT_NUM_CODECS)
913 type = AFMT_UNKNOWN | (type & CODEC_TYPE_MASK);
915 fname = (type == CODEC_TYPE_ENCODER) ?
916 audio_formats[afmt].codec_enc_root_fn :
917 audio_formats[afmt].codec_root_fn;
919 logf("%s: %d - %s",
920 (type == CODEC_TYPE_ENCODER) ? "Encoder" : "Decoder",
921 afmt, fname ? fname : "<unknown>");
922 #else /* !HAVE_RECORDING */
923 /* Always decoder */
924 if ((unsigned)cod_spec >= AFMT_NUM_CODECS)
925 cod_spec = AFMT_UNKNOWN;
926 fname = audio_formats[cod_spec].codec_root_fn;
927 logf("Codec: %d - %s", cod_spec, fname ? fname : "<unknown>");
928 #endif /* HAVE_RECORDING */
930 return fname;
931 } /* get_codec_filename */
933 /* --- Codec thread --- */
934 static bool codec_pcmbuf_insert_callback(
935 const void *ch1, const void *ch2, int count)
937 const char *src[2] = { ch1, ch2 };
939 while (count > 0)
941 int out_count = dsp_output_count(ci.dsp, count);
942 int inp_count;
943 char *dest;
945 /* Prevent audio from a previous track from playing */
946 if (ci.new_track || ci.stop_codec)
947 return true;
949 while ((dest = pcmbuf_request_buffer(&out_count)) == NULL)
951 cancel_cpu_boost();
952 sleep(1);
953 if (ci.seek_time || ci.new_track || ci.stop_codec)
954 return true;
957 /* Get the real input_size for output_size bytes, guarding
958 * against resampling buffer overflows. */
959 inp_count = dsp_input_count(ci.dsp, out_count);
961 if (inp_count <= 0)
962 return true;
964 /* Input size has grown, no error, just don't write more than length */
965 if (inp_count > count)
966 inp_count = count;
968 out_count = dsp_process(ci.dsp, dest, src, inp_count);
970 if (out_count <= 0)
971 return true;
973 pcmbuf_write_complete(out_count);
975 count -= inp_count;
978 return true;
979 } /* codec_pcmbuf_insert_callback */
981 static void* codec_get_buffer(size_t *size)
983 if (codec_size >= CODEC_SIZE)
984 return NULL;
985 *size = CODEC_SIZE - codec_size;
986 return &codecbuf[codec_size];
989 /* Between the codec and PCM track change, we need to keep updating the
990 "elapsed" value of the previous (to the codec, but current to the
991 user/PCM/WPS) track, so that the progressbar reaches the end.
992 During that transition, the WPS will display prevtrack_id3. */
993 static void codec_pcmbuf_position_callback(size_t size) ICODE_ATTR;
994 static void codec_pcmbuf_position_callback(size_t size)
996 /* This is called from an ISR, so be quick */
997 unsigned int time = size * 1000 / 4 / NATIVE_FREQUENCY +
998 othertrack_id3->elapsed;
1000 if (time >= othertrack_id3->length)
1002 pcmbuf_set_position_callback(NULL);
1003 othertrack_id3->elapsed = othertrack_id3->length;
1005 else
1006 othertrack_id3->elapsed = time;
1009 static void codec_set_elapsed_callback(unsigned int value)
1011 unsigned int latency;
1012 if (ci.seek_time)
1013 return;
1015 #ifdef AB_REPEAT_ENABLE
1016 ab_position_report(value);
1017 #endif
1019 latency = pcmbuf_get_latency();
1020 if (value < latency)
1021 thistrack_id3->elapsed = 0;
1022 else if (value - latency > thistrack_id3->elapsed ||
1023 value - latency < thistrack_id3->elapsed - 2)
1025 thistrack_id3->elapsed = value - latency;
1029 static void codec_set_offset_callback(size_t value)
1031 unsigned int latency;
1033 if (ci.seek_time)
1034 return;
1036 latency = pcmbuf_get_latency() * thistrack_id3->bitrate / 8;
1037 if (value < latency)
1038 thistrack_id3->offset = 0;
1039 else
1040 thistrack_id3->offset = value - latency;
1043 static void codec_advance_buffer_counters(size_t amount)
1045 bufadvance(CUR_TI->audio_hid, amount);
1046 ci.curpos += amount;
1049 /* copy up-to size bytes into ptr and return the actual size copied */
1050 static size_t codec_filebuf_callback(void *ptr, size_t size)
1052 ssize_t copy_n;
1054 if (ci.stop_codec || !playing)
1055 return 0;
1057 copy_n = bufread(CUR_TI->audio_hid, size, ptr);
1059 /* Nothing requested OR nothing left */
1060 if (copy_n == 0)
1061 return 0;
1063 /* Update read and other position pointers */
1064 codec_advance_buffer_counters(copy_n);
1066 /* Return the actual amount of data copied to the buffer */
1067 return copy_n;
1068 } /* codec_filebuf_callback */
1070 static void* codec_request_buffer_callback(size_t *realsize, size_t reqsize)
1072 size_t copy_n = reqsize;
1073 ssize_t ret;
1074 void *ptr;
1076 if (!playing)
1078 *realsize = 0;
1079 return NULL;
1082 ret = bufgetdata(CUR_TI->audio_hid, reqsize, &ptr);
1083 if (ret >= 0)
1084 copy_n = MIN((size_t)ret, reqsize);
1086 if (copy_n == 0)
1088 *realsize = 0;
1089 return NULL;
1092 *realsize = copy_n;
1094 return ptr;
1095 } /* codec_request_buffer_callback */
1097 static int get_codec_base_type(int type)
1099 switch (type) {
1100 case AFMT_MPA_L1:
1101 case AFMT_MPA_L2:
1102 case AFMT_MPA_L3:
1103 return AFMT_MPA_L3;
1106 return type;
1109 static void codec_advance_buffer_callback(size_t amount)
1111 codec_advance_buffer_counters(amount);
1112 codec_set_offset_callback(ci.curpos);
1115 static void codec_advance_buffer_loc_callback(void *ptr)
1117 size_t amount = buf_get_offset(CUR_TI->audio_hid, ptr);
1118 codec_advance_buffer_callback(amount);
1121 static void codec_seek_complete_callback(void)
1123 logf("seek_complete");
1124 /* If seeking-while-playing, pcm playback is actually paused (pcm_is_paused())
1125 * but the paused flag is not set. If seeking-while-paused, the (paused) flag is
1126 * set, but pcm playback may have actually stopped due to a previous buffer clear.
1127 * The buffer clear below occurs with either condition. A seemless seek skips
1128 * this section and no buffer clear occurs.
1130 if (pcm_is_paused() || paused)
1132 /* Clear the buffer */
1133 pcmbuf_play_stop();
1134 dsp_configure(ci.dsp, DSP_FLUSH, 0);
1136 /* If seeking-while-playing, resume pcm playback */
1137 if (!paused)
1138 pcmbuf_pause(false);
1140 ci.seek_time = 0;
1143 static bool codec_seek_buffer_callback(size_t newpos)
1145 logf("codec_seek_buffer_callback");
1147 int ret = bufseek(CUR_TI->audio_hid, newpos);
1148 if (ret == 0) {
1149 ci.curpos = newpos;
1150 return true;
1152 else {
1153 return false;
1157 static void codec_configure_callback(int setting, intptr_t value)
1159 switch (setting) {
1160 default:
1161 if (!dsp_configure(ci.dsp, setting, value))
1162 { logf("Illegal key:%d", setting); }
1166 static void codec_track_changed(void)
1168 LOGFQUEUE("codec > audio Q_AUDIO_TRACK_CHANGED");
1169 queue_post(&audio_queue, Q_AUDIO_TRACK_CHANGED, 0);
1172 static void codec_pcmbuf_track_changed_callback(void)
1174 pcmbuf_set_position_callback(NULL);
1175 pcmbuf_callback_queue_post(Q_AUDIO_TRACK_CHANGED, 0);
1178 static void codec_discard_codec_callback(void)
1180 if (CUR_TI->codec_hid >= 0)
1182 bufclose(CUR_TI->codec_hid);
1183 CUR_TI->codec_hid = -1;
1187 static inline void codec_gapless_track_change(void)
1189 /* callback keeps the progress bar moving while the pcmbuf empties */
1190 pcmbuf_set_position_callback(codec_pcmbuf_position_callback);
1191 /* set the pcmbuf callback for when the track really changes */
1192 pcmbuf_set_event_handler(codec_pcmbuf_track_changed_callback);
1195 static inline void codec_crossfade_track_change(void)
1197 /* Initiate automatic crossfade mode */
1198 pcmbuf_crossfade_init(false);
1199 /* Notify the wps that the track change starts now */
1200 codec_track_changed();
1203 static void codec_track_skip_done(bool was_manual)
1205 /* Manual track change (always crossfade or flush audio). */
1206 if (was_manual)
1208 pcmbuf_crossfade_init(true);
1209 LOGFQUEUE("codec > audio Q_AUDIO_TRACK_CHANGED");
1210 queue_post(&audio_queue, Q_AUDIO_TRACK_CHANGED, 0);
1212 /* Automatic track change w/crossfade, if not in "Track Skip Only" mode. */
1213 else if (pcmbuf_is_crossfade_enabled() && !pcmbuf_is_crossfade_active()
1214 && global_settings.crossfade != CROSSFADE_ENABLE_TRACKSKIP)
1216 if (global_settings.crossfade == CROSSFADE_ENABLE_SHUFFLE_AND_TRACKSKIP)
1218 if (global_settings.playlist_shuffle)
1219 /* shuffle mode is on, so crossfade: */
1220 codec_crossfade_track_change();
1221 else
1222 /* shuffle mode is off, so do a gapless track change */
1223 codec_gapless_track_change();
1225 else
1226 /* normal crossfade: */
1227 codec_crossfade_track_change();
1229 else
1230 /* normal gapless playback. */
1231 codec_gapless_track_change();
1234 static bool codec_load_next_track(void)
1236 intptr_t result = Q_CODEC_REQUEST_FAILED;
1238 prev_track_elapsed = thistrack_id3->elapsed;
1240 #ifdef AB_REPEAT_ENABLE
1241 ab_end_of_track_report();
1242 #endif
1244 logf("Request new track");
1246 if (ci.new_track == 0)
1248 ci.new_track++;
1249 automatic_skip = true;
1252 if (!ci.stop_codec)
1254 trigger_cpu_boost();
1255 LOGFQUEUE("codec >| audio Q_AUDIO_CHECK_NEW_TRACK");
1256 result = queue_send(&audio_queue, Q_AUDIO_CHECK_NEW_TRACK, 0);
1259 switch (result)
1261 case Q_CODEC_REQUEST_COMPLETE:
1262 LOGFQUEUE("codec |< Q_CODEC_REQUEST_COMPLETE");
1263 codec_track_skip_done(!automatic_skip);
1264 return true;
1266 case Q_CODEC_REQUEST_FAILED:
1267 LOGFQUEUE("codec |< Q_CODEC_REQUEST_FAILED");
1268 ci.new_track = 0;
1269 ci.stop_codec = true;
1270 codec_requested_stop = true;
1271 return false;
1273 default:
1274 LOGFQUEUE("codec |< default");
1275 ci.stop_codec = true;
1276 codec_requested_stop = true;
1277 return false;
1281 static bool codec_request_next_track_callback(void)
1283 int prev_codectype;
1285 if (ci.stop_codec || !playing)
1286 return false;
1288 prev_codectype = get_codec_base_type(thistrack_id3->codectype);
1289 if (!codec_load_next_track())
1290 return false;
1292 /* Seek to the beginning of the new track because if the struct
1293 mp3entry was buffered, "elapsed" might not be zero (if the track has
1294 been played already but not unbuffered) */
1295 codec_seek_buffer_callback(thistrack_id3->first_frame_offset);
1296 /* Check if the next codec is the same file. */
1297 if (prev_codectype == get_codec_base_type(thistrack_id3->codectype))
1299 logf("New track loaded");
1300 codec_discard_codec_callback();
1301 return true;
1303 else
1305 logf("New codec:%d/%d", thistrack_id3->codectype, prev_codectype);
1306 return false;
1310 static void codec_thread(void)
1312 struct queue_event ev;
1313 int status;
1315 while (1) {
1316 status = 0;
1318 if (!pcmbuf_is_crossfade_active()) {
1319 cancel_cpu_boost();
1322 queue_wait(&codec_queue, &ev);
1323 codec_requested_stop = false;
1325 switch (ev.id) {
1326 case Q_CODEC_LOAD_DISK:
1327 LOGFQUEUE("codec < Q_CODEC_LOAD_DISK");
1328 queue_reply(&codec_queue, 1);
1329 audio_codec_loaded = true;
1330 ci.stop_codec = false;
1331 status = codec_load_file((const char *)ev.data, &ci);
1332 LOGFQUEUE("codec_load_file %s %d\n", (const char *)ev.data, status);
1333 break;
1335 case Q_CODEC_LOAD:
1336 LOGFQUEUE("codec < Q_CODEC_LOAD");
1337 if (CUR_TI->codec_hid < 0) {
1338 logf("Codec slot is empty!");
1339 /* Wait for the pcm buffer to go empty */
1340 while (pcm_is_playing())
1341 yield();
1342 /* This must be set to prevent an infinite loop */
1343 ci.stop_codec = true;
1344 LOGFQUEUE("codec > codec Q_AUDIO_PLAY");
1345 queue_post(&codec_queue, Q_AUDIO_PLAY, 0);
1346 break;
1349 audio_codec_loaded = true;
1350 ci.stop_codec = false;
1351 status = codec_load_buf(CUR_TI->codec_hid, &ci);
1352 LOGFQUEUE("codec_load_buf %d\n", status);
1353 break;
1355 case Q_CODEC_DO_CALLBACK:
1356 LOGFQUEUE("codec < Q_CODEC_DO_CALLBACK");
1357 queue_reply(&codec_queue, 1);
1358 if ((void*)ev.data != NULL)
1360 cpucache_invalidate();
1361 ((void (*)(void))ev.data)();
1362 cpucache_flush();
1364 break;
1366 #ifdef AUDIO_HAVE_RECORDING
1367 case Q_ENCODER_LOAD_DISK:
1368 LOGFQUEUE("codec < Q_ENCODER_LOAD_DISK");
1369 audio_codec_loaded = false; /* Not audio codec! */
1370 logf("loading encoder");
1371 ci.stop_encoder = false;
1372 status = codec_load_file((const char *)ev.data, &ci);
1373 logf("encoder stopped");
1374 break;
1375 #endif /* AUDIO_HAVE_RECORDING */
1377 default:
1378 LOGFQUEUE("codec < default");
1381 if (audio_codec_loaded)
1383 if (ci.stop_codec)
1385 status = CODEC_OK;
1386 if (!playing)
1387 pcmbuf_play_stop();
1390 audio_codec_loaded = false;
1393 switch (ev.id) {
1394 case Q_CODEC_LOAD_DISK:
1395 case Q_CODEC_LOAD:
1396 LOGFQUEUE("codec < Q_CODEC_LOAD");
1397 if (playing)
1399 if (ci.new_track || status != CODEC_OK)
1401 if (!ci.new_track)
1403 logf("Codec failure, %d %d", ci.new_track, status);
1404 splash(HZ*2, "Codec failure");
1407 if (!codec_load_next_track())
1409 LOGFQUEUE("codec > audio Q_AUDIO_STOP");
1410 /* End of playlist */
1411 queue_post(&audio_queue, Q_AUDIO_STOP, 0);
1412 break;
1415 else
1417 logf("Codec finished");
1418 if (ci.stop_codec)
1420 /* Wait for the audio to stop playing before
1421 * triggering the WPS exit */
1422 while(pcm_is_playing())
1424 /* There has been one too many struct pointer swaps by now
1425 * so even though it says othertrack_id3, its the correct one! */
1426 othertrack_id3->elapsed =
1427 othertrack_id3->length - pcmbuf_get_latency();
1428 sleep(1);
1431 if (codec_requested_stop)
1433 LOGFQUEUE("codec > audio Q_AUDIO_STOP");
1434 queue_post(&audio_queue, Q_AUDIO_STOP, 0);
1436 break;
1440 if (CUR_TI->codec_hid >= 0)
1442 LOGFQUEUE("codec > codec Q_CODEC_LOAD");
1443 queue_post(&codec_queue, Q_CODEC_LOAD, 0);
1445 else
1447 const char *codec_fn =
1448 get_codec_filename(thistrack_id3->codectype);
1449 if (codec_fn)
1451 LOGFQUEUE("codec > codec Q_CODEC_LOAD_DISK");
1452 queue_post(&codec_queue, Q_CODEC_LOAD_DISK,
1453 (intptr_t)codec_fn);
1457 break;
1459 #ifdef AUDIO_HAVE_RECORDING
1460 case Q_ENCODER_LOAD_DISK:
1461 LOGFQUEUE("codec < Q_ENCODER_LOAD_DISK");
1463 if (status == CODEC_OK)
1464 break;
1466 logf("Encoder failure");
1467 splash(HZ*2, "Encoder failure");
1469 if (ci.enc_codec_loaded < 0)
1470 break;
1472 logf("Encoder failed to load");
1473 ci.enc_codec_loaded = -1;
1474 break;
1475 #endif /* AUDIO_HAVE_RECORDING */
1477 default:
1478 LOGFQUEUE("codec < default");
1480 } /* end switch */
1484 /* Borrow the codec thread and return the ID */
1485 void codec_thread_do_callback(void (*fn)(void), unsigned int *id)
1487 /* Set id before telling thread to call something; it may be
1488 * needed before this function returns. */
1489 if (id != NULL)
1490 *id = codec_thread_id;
1492 /* Codec thread will signal just before entering callback */
1493 LOGFQUEUE("codec >| Q_CODEC_DO_CALLBACK");
1494 queue_send(&codec_queue, Q_CODEC_DO_CALLBACK, (intptr_t)fn);
1497 /* --- Buffering callbacks --- */
1499 static void buffering_low_buffer_callback(void *data)
1501 (void)data;
1502 logf("low buffer callback");
1504 if (filling == STATE_FULL || filling == STATE_END_OF_PLAYLIST) {
1505 /* force a refill */
1506 LOGFQUEUE("buffering > audio Q_AUDIO_FILL_BUFFER");
1507 queue_post(&audio_queue, Q_AUDIO_FILL_BUFFER, 0);
1511 static void buffering_handle_rebuffer_callback(void *data)
1513 (void)data;
1514 LOGFQUEUE("audio >| audio Q_AUDIO_FLUSH");
1515 queue_post(&audio_queue, Q_AUDIO_FLUSH, 0);
1518 static void buffering_handle_finished_callback(int *data)
1520 logf("handle %d finished buffering", *data);
1522 if (*data == tracks[track_widx].id3_hid)
1524 int offset = ci.new_track + wps_offset;
1525 int next_idx = (track_ridx + offset + 1) & MAX_TRACK_MASK;
1526 /* The metadata handle for the last loaded track has been buffered.
1527 We can ask the audio thread to load the rest of the track's data. */
1528 LOGFQUEUE("audio >| audio Q_AUDIO_FINISH_LOAD");
1529 queue_post(&audio_queue, Q_AUDIO_FINISH_LOAD, 0);
1530 if (tracks[next_idx].id3_hid == *data)
1531 send_event(PLAYBACK_EVENT_NEXTTRACKID3_AVAILABLE, NULL);
1533 else
1535 /* This is most likely an audio handle, so we strip the useless
1536 trailing tags that are left. */
1537 strip_tags(*data);
1539 if (*data == tracks[track_widx-1].audio_hid
1540 && filling == STATE_END_OF_PLAYLIST)
1542 /* This was the last track in the playlist.
1543 We now have all the data we need. */
1544 logf("last track finished buffering");
1545 filling = STATE_FINISHED;
1551 /* --- Audio thread --- */
1553 static bool audio_have_tracks(void)
1555 return (audio_track_count() != 0);
1558 static int audio_free_track_count(void)
1560 /* Used tracks + free tracks adds up to MAX_TRACK - 1 */
1561 return MAX_TRACK - 1 - audio_track_count();
1564 int audio_track_count(void)
1566 /* Calculate difference from track_ridx to track_widx
1567 * taking into account a possible wrap-around. */
1568 return (MAX_TRACK + track_widx - track_ridx) & MAX_TRACK_MASK;
1571 long audio_filebufused(void)
1573 return (long) buf_used();
1576 /* Update track info after successful a codec track change */
1577 static void audio_update_trackinfo(void)
1579 /* Load the curent track's metadata into curtrack_id3 */
1580 if (CUR_TI->id3_hid >= 0)
1581 copy_mp3entry(thistrack_id3, bufgetid3(CUR_TI->id3_hid));
1583 /* Reset current position */
1584 thistrack_id3->elapsed = 0;
1585 thistrack_id3->offset = 0;
1587 /* Update the codec API */
1588 ci.filesize = CUR_TI->filesize;
1589 ci.id3 = thistrack_id3;
1590 ci.curpos = 0;
1591 ci.taginfo_ready = &CUR_TI->taginfo_ready;
1594 /* Clear tracks between write and read, non inclusive */
1595 static void audio_clear_track_entries(void)
1597 int cur_idx = track_widx;
1599 logf("Clearing tracks:%d/%d", track_ridx, track_widx);
1601 /* Loop over all tracks from write-to-read */
1602 while (1)
1604 cur_idx = (cur_idx + 1) & MAX_TRACK_MASK;
1606 if (cur_idx == track_ridx)
1607 break;
1609 clear_track_info(&tracks[cur_idx]);
1613 /* Clear all tracks */
1614 static bool audio_release_tracks(void)
1616 int i, cur_idx;
1618 logf("releasing all tracks");
1620 for(i = 0; i < MAX_TRACK; i++)
1622 cur_idx = (track_ridx + i) & MAX_TRACK_MASK;
1623 if (!clear_track_info(&tracks[cur_idx]))
1624 return false;
1627 return true;
1630 static bool audio_loadcodec(bool start_play)
1632 int prev_track;
1633 char codec_path[MAX_PATH]; /* Full path to codec */
1634 const struct mp3entry *id3, *prev_id3;
1636 if (tracks[track_widx].id3_hid < 0) {
1637 return false;
1640 id3 = bufgetid3(tracks[track_widx].id3_hid);
1641 if (!id3)
1642 return false;
1644 const char *codec_fn = get_codec_filename(id3->codectype);
1645 if (codec_fn == NULL)
1646 return false;
1648 tracks[track_widx].codec_hid = -1;
1650 if (start_play)
1652 /* Load the codec directly from disk and save some memory. */
1653 track_ridx = track_widx;
1654 ci.filesize = CUR_TI->filesize;
1655 ci.id3 = thistrack_id3;
1656 ci.taginfo_ready = &CUR_TI->taginfo_ready;
1657 ci.curpos = 0;
1658 LOGFQUEUE("codec > codec Q_CODEC_LOAD_DISK");
1659 queue_post(&codec_queue, Q_CODEC_LOAD_DISK, (intptr_t)codec_fn);
1660 return true;
1662 else
1664 /* If we already have another track than this one buffered */
1665 if (track_widx != track_ridx)
1667 prev_track = (track_widx - 1) & MAX_TRACK_MASK;
1669 id3 = bufgetid3(tracks[track_widx].id3_hid);
1670 prev_id3 = bufgetid3(tracks[prev_track].id3_hid);
1672 /* If the previous codec is the same as this one, there is no need
1673 * to put another copy of it on the file buffer */
1674 if (id3 && prev_id3 &&
1675 get_codec_base_type(id3->codectype) ==
1676 get_codec_base_type(prev_id3->codectype)
1677 && audio_codec_loaded)
1679 logf("Reusing prev. codec");
1680 return true;
1685 codec_get_full_path(codec_path, codec_fn);
1687 tracks[track_widx].codec_hid = bufopen(codec_path, 0, TYPE_CODEC);
1688 if (tracks[track_widx].codec_hid < 0)
1689 return false;
1691 logf("Loaded codec");
1693 return true;
1696 /* Load metadata for the next track (with bufopen). The rest of the track
1697 loading will be handled by audio_finish_load_track once the metadata has been
1698 actually loaded by the buffering thread. */
1699 static bool audio_load_track(size_t offset, bool start_play)
1701 const char *trackname;
1702 int fd = -1;
1704 if (track_load_started) {
1705 /* There is already a track load in progress, so track_widx hasn't been
1706 incremented yet. Loading another track would overwrite the one that
1707 hasn't finished loading. */
1708 logf("audio_load_track(): a track load is already in progress");
1709 return false;
1712 start_play_g = start_play; /* will be read by audio_finish_load_track */
1714 /* Stop buffer filling if there is no free track entries.
1715 Don't fill up the last track entry (we wan't to store next track
1716 metadata there). */
1717 if (!audio_free_track_count())
1719 logf("No free tracks");
1720 return false;
1723 last_peek_offset++;
1724 tracks[track_widx].taginfo_ready = false;
1726 logf("Buffering track:%d/%d", track_widx, track_ridx);
1727 /* Get track name from current playlist read position. */
1728 while ((trackname = playlist_peek(last_peek_offset)) != NULL)
1730 /* Handle broken playlists. */
1731 fd = open(trackname, O_RDONLY);
1732 if (fd < 0)
1734 logf("Open failed");
1735 /* Skip invalid entry from playlist. */
1736 playlist_skip_entry(NULL, last_peek_offset);
1738 else
1739 break;
1742 if (!trackname)
1744 logf("End-of-playlist");
1745 memset(&unbuffered_id3, 0, sizeof(struct mp3entry));
1746 filling = STATE_END_OF_PLAYLIST;
1748 if (thistrack_id3->length == 0 && thistrack_id3->filesize == 0)
1750 /* Stop playback if no valid track was found. */
1751 audio_stop_playback();
1754 return false;
1757 tracks[track_widx].filesize = filesize(fd);
1759 if (offset > tracks[track_widx].filesize)
1760 offset = 0;
1762 /* Set default values */
1763 if (start_play)
1765 buf_set_watermark(filebuflen/2);
1766 dsp_configure(ci.dsp, DSP_RESET, 0);
1767 playlist_update_resume_info(audio_current_track());
1770 /* Get track metadata if we don't already have it. */
1771 if (tracks[track_widx].id3_hid < 0)
1773 tracks[track_widx].id3_hid = bufopen(trackname, 0, TYPE_ID3);
1775 if (tracks[track_widx].id3_hid < 0)
1777 /* Buffer is full. */
1778 get_metadata(&unbuffered_id3, fd, trackname);
1779 last_peek_offset--;
1780 close(fd);
1781 logf("buffer is full for now");
1782 filling = STATE_FULL;
1783 return false;
1786 if (track_widx == track_ridx)
1788 /* TODO: Superfluos buffering call? */
1789 buf_request_buffer_handle(tracks[track_widx].id3_hid);
1790 struct mp3entry *id3 = bufgetid3(tracks[track_widx].id3_hid);
1791 if (id3)
1793 copy_mp3entry(thistrack_id3, id3);
1794 thistrack_id3->offset = offset;
1796 else
1797 memset(thistrack_id3, 0, sizeof(struct mp3entry));
1800 if (start_play)
1802 playlist_update_resume_info(audio_current_track());
1806 close(fd);
1807 track_load_started = true; /* Remember that we've started loading a track */
1808 return true;
1811 /* Second part of the track loading: We now have the metadata available, so we
1812 can load the codec, the album art and finally the audio data.
1813 This is called on the audio thread after the buffering thread calls the
1814 buffering_handle_finished_callback callback. */
1815 static void audio_finish_load_track(void)
1817 size_t file_offset = 0;
1818 size_t offset = 0;
1819 bool start_play = start_play_g;
1821 track_load_started = false;
1823 if (tracks[track_widx].id3_hid < 0) {
1824 logf("no metatdata");
1825 return;
1828 struct mp3entry *track_id3;
1830 if (track_widx == track_ridx)
1831 track_id3 = thistrack_id3;
1832 else
1833 track_id3 = bufgetid3(tracks[track_widx].id3_hid);
1835 if (track_id3->length == 0 && track_id3->filesize == 0)
1837 logf("audio_finish_load_track: invalid metadata");
1839 /* Invalid metadata */
1840 bufclose(tracks[track_widx].id3_hid);
1841 tracks[track_widx].id3_hid = -1;
1843 /* Skip invalid entry from playlist. */
1844 playlist_skip_entry(NULL, last_peek_offset--);
1846 /* load next track */
1847 LOGFQUEUE("audio > audio Q_AUDIO_FILL_BUFFER %d", (int)start_play);
1848 queue_post(&audio_queue, Q_AUDIO_FILL_BUFFER, start_play);
1850 return;
1852 /* Try to load a cuesheet for the track */
1853 if (curr_cue)
1855 char cuepath[MAX_PATH];
1857 struct cuesheet temp_cue;
1859 if (look_for_cuesheet_file(track_id3->path, cuepath) &&
1860 parse_cuesheet(cuepath, &temp_cue))
1862 strcpy(temp_cue.audio_filename, track_id3->path);
1863 tracks[track_widx].cuesheet_hid =
1864 bufalloc(&temp_cue, sizeof(struct cuesheet), TYPE_CUESHEET);
1867 #ifdef HAVE_ALBUMART
1868 if (tracks[track_widx].aa_hid < 0 && gui_sync_wps_uses_albumart())
1870 char aa_path[MAX_PATH];
1871 if (find_albumart(track_id3, aa_path, sizeof(aa_path)))
1873 tracks[track_widx].aa_hid = bufopen(aa_path, 0, TYPE_BITMAP);
1875 if(tracks[track_widx].aa_hid == ERR_BUFFER_FULL)
1877 filling = STATE_FULL;
1878 logf("buffer is full for now");
1879 return; /* No space for track's album art, not an error */
1881 else if (tracks[track_widx].aa_hid < 0)
1883 /* another error, ignore AlbumArt */
1884 logf("Album art loading failed");
1888 #endif
1890 /* Load the codec. */
1891 if (!audio_loadcodec(start_play))
1893 if (tracks[track_widx].codec_hid == ERR_BUFFER_FULL)
1895 /* No space for codec on buffer, not an error */
1896 filling = STATE_FULL;
1897 return;
1900 /* This is an error condition, either no codec was found, or reading
1901 * the codec file failed part way through, either way, skip the track */
1902 /* FIXME: We should not use splashf from audio thread! */
1903 splashf(HZ*2, "No codec for: %s", track_id3->path);
1904 /* Skip invalid entry from playlist. */
1905 playlist_skip_entry(NULL, last_peek_offset);
1906 return;
1909 track_id3->elapsed = 0;
1910 offset = track_id3->offset;
1912 enum data_type type = TYPE_PACKET_AUDIO;
1914 switch (track_id3->codectype) {
1915 case AFMT_MPA_L1:
1916 case AFMT_MPA_L2:
1917 case AFMT_MPA_L3:
1918 if (offset > 0) {
1919 file_offset = offset;
1920 track_id3->offset = offset;
1922 break;
1924 case AFMT_WAVPACK:
1925 if (offset > 0) {
1926 file_offset = offset;
1927 track_id3->offset = offset;
1928 track_id3->elapsed = track_id3->length / 2;
1930 break;
1932 case AFMT_OGG_VORBIS:
1933 case AFMT_SPEEX:
1934 case AFMT_FLAC:
1935 case AFMT_PCM_WAV:
1936 case AFMT_A52:
1937 case AFMT_AAC:
1938 case AFMT_MPC:
1939 case AFMT_APE:
1940 case AFMT_WMA:
1941 if (offset > 0)
1942 track_id3->offset = offset;
1943 break;
1945 case AFMT_NSF:
1946 case AFMT_SPC:
1947 case AFMT_SID:
1948 logf("Loading atomic %d",track_id3->codectype);
1949 type = TYPE_ATOMIC_AUDIO;
1950 break;
1953 logf("alt:%s", track_id3->path);
1955 if (file_offset > AUDIO_REBUFFER_GUESS_SIZE)
1956 file_offset -= AUDIO_REBUFFER_GUESS_SIZE;
1957 else if (track_id3->first_frame_offset)
1958 file_offset = track_id3->first_frame_offset;
1959 else
1960 file_offset = 0;
1962 tracks[track_widx].audio_hid = bufopen(track_id3->path, file_offset, type);
1964 /* No space left, not an error */
1965 if (tracks[track_widx].audio_hid == ERR_BUFFER_FULL)
1967 filling = STATE_FULL;
1968 logf("buffer is full for now");
1969 return;
1971 else if (tracks[track_widx].audio_hid < 0)
1973 /* another error, do not continue either */
1974 logf("Could not add audio data handle");
1975 return;
1978 /* All required data is now available for the codec. */
1979 tracks[track_widx].taginfo_ready = true;
1981 if (start_play)
1983 ci.curpos=file_offset;
1984 buf_request_buffer_handle(tracks[track_widx].audio_hid);
1987 track_widx = (track_widx + 1) & MAX_TRACK_MASK;
1989 send_event(PLAYBACK_EVENT_TRACK_BUFFER, track_id3);
1991 /* load next track */
1992 LOGFQUEUE("audio > audio Q_AUDIO_FILL_BUFFER");
1993 queue_post(&audio_queue, Q_AUDIO_FILL_BUFFER, 0);
1995 return;
1998 static void audio_fill_file_buffer(bool start_play, size_t offset)
2000 trigger_cpu_boost();
2002 /* No need to rebuffer if there are track skips pending,
2003 * however don't cancel buffering on skipping while filling. */
2004 if (ci.new_track != 0 && filling != STATE_FILLING)
2005 return;
2006 filling = STATE_FILLING;
2008 /* Must reset the buffer before use if trashed or voice only - voice
2009 file size shouldn't have changed so we can go straight from
2010 AUDIOBUF_STATE_VOICED_ONLY to AUDIOBUF_STATE_INITIALIZED */
2011 if (buffer_state != AUDIOBUF_STATE_INITIALIZED)
2012 audio_reset_buffer();
2014 logf("Starting buffer fill");
2016 if (!start_play)
2017 audio_clear_track_entries();
2019 /* Save the current resume position once. */
2020 playlist_update_resume_info(audio_current_track());
2022 audio_load_track(offset, start_play);
2025 static void audio_rebuffer(void)
2027 logf("Forcing rebuffer");
2029 clear_track_info(CUR_TI);
2031 /* Reset track pointers */
2032 track_widx = track_ridx;
2033 audio_clear_track_entries();
2035 /* Reset a possibly interrupted track load */
2036 track_load_started = false;
2038 /* Fill the buffer */
2039 last_peek_offset = -1;
2040 ci.curpos = 0;
2042 if (!CUR_TI->taginfo_ready)
2043 memset(thistrack_id3, 0, sizeof(struct mp3entry));
2045 audio_fill_file_buffer(false, 0);
2048 /* Called on request from the codec to get a new track. This is the codec part
2049 of the track transition. */
2050 static int audio_check_new_track(void)
2052 int track_count = audio_track_count();
2053 int old_track_ridx = track_ridx;
2054 int i, idx;
2055 bool forward;
2056 struct mp3entry *temp = thistrack_id3;
2058 /* Now it's good time to send track finish events. */
2059 send_event(PLAYBACK_EVENT_TRACK_FINISH, thistrack_id3);
2060 /* swap the mp3entry pointers */
2061 thistrack_id3 = othertrack_id3;
2062 othertrack_id3 = temp;
2063 ci.id3 = thistrack_id3;
2064 memset(thistrack_id3, 0, sizeof(struct mp3entry));
2066 if (dir_skip)
2068 dir_skip = false;
2069 /* regardless of the return value we need to rebuffer.
2070 if it fails the old playlist will resume, else the
2071 next dir will start playing */
2072 playlist_next_dir(ci.new_track);
2073 ci.new_track = 0;
2074 audio_rebuffer();
2075 goto skip_done;
2078 if (new_playlist)
2079 ci.new_track = 0;
2081 /* If the playlist isn't that big */
2082 if (automatic_skip)
2084 while (!playlist_check(ci.new_track))
2086 if (ci.new_track >= 0)
2088 LOGFQUEUE("audio >|= codec Q_CODEC_REQUEST_FAILED");
2089 return Q_CODEC_REQUEST_FAILED;
2091 ci.new_track++;
2095 /* Update the playlist */
2096 last_peek_offset -= ci.new_track;
2098 if (playlist_next(ci.new_track) < 0)
2100 LOGFQUEUE("audio >|= codec Q_CODEC_REQUEST_FAILED");
2101 return Q_CODEC_REQUEST_FAILED;
2104 if (new_playlist)
2106 ci.new_track = 1;
2107 new_playlist = false;
2110 /* Save a pointer to the old track to allow later clearing */
2111 prev_ti = CUR_TI;
2113 for (i = 0; i < ci.new_track; i++)
2115 idx = (track_ridx + i) & MAX_TRACK_MASK;
2116 struct mp3entry *id3 = bufgetid3(tracks[idx].id3_hid);
2117 ssize_t offset = buf_handle_offset(tracks[idx].audio_hid);
2118 if (!id3 || offset < 0 || (unsigned)offset > id3->first_frame_offset)
2120 /* We don't have all the audio data for that track, so clear it,
2121 but keep the metadata. */
2122 if (tracks[idx].audio_hid >= 0 && bufclose(tracks[idx].audio_hid))
2124 tracks[idx].audio_hid = -1;
2125 tracks[idx].filesize = 0;
2130 /* Move to the new track */
2131 track_ridx = (track_ridx + ci.new_track) & MAX_TRACK_MASK;
2133 buf_set_base_handle(CUR_TI->audio_hid);
2135 if (automatic_skip)
2137 wps_offset = -ci.new_track;
2140 /* If it is not safe to even skip this many track entries */
2141 if (ci.new_track >= track_count || ci.new_track <= track_count - MAX_TRACK)
2143 ci.new_track = 0;
2144 audio_rebuffer();
2145 goto skip_done;
2148 forward = ci.new_track > 0;
2149 ci.new_track = 0;
2151 /* If the target track is clearly not in memory */
2152 if (CUR_TI->filesize == 0 || !CUR_TI->taginfo_ready)
2154 audio_rebuffer();
2155 goto skip_done;
2158 /* When skipping backwards, it is possible that we've found a track that's
2159 * buffered, but which is around the track-wrap and therefore not the track
2160 * we are looking for */
2161 if (!forward)
2163 int cur_idx = track_ridx;
2164 bool taginfo_ready = true;
2165 /* We've wrapped the buffer backwards if new > old */
2166 bool wrap = track_ridx > old_track_ridx;
2168 while (1)
2170 cur_idx = (cur_idx + 1) & MAX_TRACK_MASK;
2172 /* if we've advanced past the wrap when cur_idx is zeroed */
2173 if (!cur_idx)
2174 wrap = false;
2176 /* if we aren't still on the wrap and we've caught the old track */
2177 if (!(wrap || cur_idx < old_track_ridx))
2178 break;
2180 /* If we hit a track in between without valid tag info, bail */
2181 if (!tracks[cur_idx].taginfo_ready)
2183 taginfo_ready = false;
2184 break;
2187 if (!taginfo_ready)
2189 audio_rebuffer();
2193 skip_done:
2194 audio_update_trackinfo();
2195 LOGFQUEUE("audio >|= codec Q_CODEC_REQUEST_COMPLETE");
2196 return Q_CODEC_REQUEST_COMPLETE;
2199 unsigned long audio_prev_elapsed(void)
2201 return prev_track_elapsed;
2204 static void audio_stop_codec_flush(void)
2206 ci.stop_codec = true;
2207 pcmbuf_pause(true);
2209 while (audio_codec_loaded)
2210 yield();
2212 /* If the audio codec is not loaded any more, and the audio is still
2213 * playing, it is now and _only_ now safe to call this function from the
2214 * audio thread */
2215 if (pcm_is_playing())
2217 pcmbuf_play_stop();
2218 pcmbuf_queue_clear();
2220 pcmbuf_pause(paused);
2223 static void audio_stop_playback(void)
2225 if (playing)
2227 /* If still actively playing here, play out the last samples in the track
2228 * before stopping. A manual stop is actually paused at this point, so
2229 * don't continue playback.
2231 if (!paused)
2232 pcmbuf_play_remainder();
2234 /* If we were playing, save resume information */
2235 struct mp3entry *id3 = NULL;
2237 if (!ci.stop_codec)
2239 /* Set this early, the outside code yields and may allow the codec
2240 to try to wait for a reply on a buffer wait */
2241 ci.stop_codec = true;
2242 id3 = audio_current_track();
2245 /* Save the current playing spot, or NULL if the playlist has ended */
2246 playlist_update_resume_info(id3);
2248 /* TODO: Create auto bookmark too? */
2250 prev_track_elapsed = othertrack_id3->elapsed;
2252 remove_event(BUFFER_EVENT_BUFFER_LOW, buffering_low_buffer_callback);
2255 audio_stop_codec_flush();
2256 paused = false;
2257 playing = false;
2258 track_load_started = false;
2260 filling = STATE_IDLE;
2262 /* Mark all entries null. */
2263 audio_clear_track_entries();
2265 /* Close all tracks */
2266 audio_release_tracks();
2269 static void audio_play_start(size_t offset)
2271 int i;
2273 #if INPUT_SRC_CAPS != 0
2274 audio_set_input_source(AUDIO_SRC_PLAYBACK, SRCF_PLAYBACK);
2275 audio_set_output_source(AUDIO_SRC_PLAYBACK);
2276 #endif
2278 /* Wait for any previously playing audio to flush - TODO: Not necessary? */
2279 paused = false;
2280 audio_stop_codec_flush();
2282 playing = true;
2283 track_load_started = false;
2285 ci.new_track = 0;
2286 ci.seek_time = 0;
2287 wps_offset = 0;
2289 sound_set_volume(global_settings.volume);
2290 track_widx = track_ridx = 0;
2292 /* Clear all track entries. */
2293 for (i = 0; i < MAX_TRACK; i++) {
2294 clear_track_info(&tracks[i]);
2297 last_peek_offset = -1;
2299 /* Officially playing */
2300 queue_reply(&audio_queue, 1);
2302 audio_fill_file_buffer(true, offset);
2304 add_event(BUFFER_EVENT_BUFFER_LOW, false, buffering_low_buffer_callback);
2306 LOGFQUEUE("audio > audio Q_AUDIO_TRACK_CHANGED");
2307 queue_post(&audio_queue, Q_AUDIO_TRACK_CHANGED, 0);
2311 /* Invalidates all but currently playing track. */
2312 static void audio_invalidate_tracks(void)
2314 if (audio_have_tracks())
2316 last_peek_offset = 0;
2317 track_widx = track_ridx;
2319 /* Mark all other entries null (also buffered wrong metadata). */
2320 audio_clear_track_entries();
2322 track_widx = (track_widx + 1) & MAX_TRACK_MASK;
2324 audio_fill_file_buffer(false, 0);
2328 static void audio_new_playlist(void)
2330 /* Prepare to start a new fill from the beginning of the playlist */
2331 last_peek_offset = -1;
2332 if (audio_have_tracks())
2334 if (paused)
2335 skipped_during_pause = true;
2336 track_widx = track_ridx;
2337 audio_clear_track_entries();
2339 track_widx = (track_widx + 1) & MAX_TRACK_MASK;
2341 /* Mark the current track as invalid to prevent skipping back to it */
2342 CUR_TI->taginfo_ready = false;
2345 /* Signal the codec to initiate a track change forward */
2346 new_playlist = true;
2347 ci.new_track = 1;
2349 /* Officially playing */
2350 queue_reply(&audio_queue, 1);
2352 audio_fill_file_buffer(false, 0);
2355 /* Called on manual track skip */
2356 static void audio_initiate_track_change(long direction)
2358 logf("audio_initiate_track_change(%ld)", direction);
2360 ci.new_track += direction;
2361 wps_offset -= direction;
2362 if (paused)
2363 skipped_during_pause = true;
2366 /* Called on manual dir skip */
2367 static void audio_initiate_dir_change(long direction)
2369 dir_skip = true;
2370 ci.new_track = direction;
2371 if (paused)
2372 skipped_during_pause = true;
2375 /* Called when PCM track change is complete */
2376 static void audio_finalise_track_change(void)
2378 logf("audio_finalise_track_change");
2380 if (automatic_skip)
2382 wps_offset = 0;
2383 automatic_skip = false;
2385 /* Invalidate prevtrack_id3 */
2386 memset(othertrack_id3, 0, sizeof(struct mp3entry));
2388 if (prev_ti && prev_ti->audio_hid < 0)
2390 /* No audio left so we clear all the track info. */
2391 clear_track_info(prev_ti);
2394 send_event(PLAYBACK_EVENT_TRACK_CHANGE, thistrack_id3);
2395 playlist_update_resume_info(audio_current_track());
2399 * Layout audio buffer as follows - iram buffer depends on target:
2400 * [|SWAP:iram][|TALK]|FILE|GUARD|PCM|[SWAP:dram[|iram]|]
2402 static void audio_reset_buffer(void)
2404 /* see audio_get_recording_buffer if this is modified */
2405 logf("audio_reset_buffer");
2407 /* If the setup of anything allocated before the file buffer is
2408 changed, do check the adjustments after the buffer_alloc call
2409 as it will likely be affected and need sliding over */
2411 /* Initially set up file buffer as all space available */
2412 malloc_buf = audiobuf + talk_get_bufsize();
2413 /* Align the malloc buf to line size. Especially important to cf
2414 targets that do line reads/writes. */
2415 malloc_buf = (unsigned char *)(((uintptr_t)malloc_buf + 15) & ~15);
2416 filebuf = malloc_buf; /* filebuf line align implied */
2417 filebuflen = audiobufend - filebuf;
2419 filebuflen &= ~15;
2421 /* Subtract whatever the pcm buffer says it used plus the guard buffer */
2422 const size_t pcmbuf_size = pcmbuf_init(filebuf + filebuflen) +GUARD_BUFSIZE;
2424 #ifdef DEBUG
2425 if(pcmbuf_size > filebuflen)
2426 panicf("Not enough memory for pcmbuf_init() : %d > %d",
2427 (int)pcmbuf_size, (int)filebuflen);
2428 #endif
2430 filebuflen -= pcmbuf_size;
2432 /* Make sure filebuflen is a longword multiple after adjustment - filebuf
2433 will already be line aligned */
2434 filebuflen &= ~3;
2436 buffering_reset(filebuf, filebuflen);
2438 /* Clear any references to the file buffer */
2439 buffer_state = AUDIOBUF_STATE_INITIALIZED;
2441 #if defined(ROCKBOX_HAS_LOGF) && defined(LOGF_ENABLE)
2442 /* Make sure everything adds up - yes, some info is a bit redundant but
2443 aids viewing and the sumation of certain variables should add up to
2444 the location of others. */
2446 size_t pcmbufsize;
2447 const unsigned char *pcmbuf = pcmbuf_get_meminfo(&pcmbufsize);
2448 logf("mabuf: %08X", (unsigned)malloc_buf);
2449 logf("fbuf: %08X", (unsigned)filebuf);
2450 logf("fbufe: %08X", (unsigned)(filebuf + filebuflen));
2451 logf("gbuf: %08X", (unsigned)(filebuf + filebuflen));
2452 logf("gbufe: %08X", (unsigned)(filebuf + filebuflen + GUARD_BUFSIZE));
2453 logf("pcmb: %08X", (unsigned)pcmbuf);
2454 logf("pcmbe: %08X", (unsigned)(pcmbuf + pcmbufsize));
2456 #endif
2459 static void audio_thread(void)
2461 struct queue_event ev;
2463 pcm_postinit();
2465 audio_thread_ready = true;
2467 while (1)
2469 if (filling != STATE_FILLING) {
2470 /* End of buffering, let's calculate the watermark and unboost */
2471 set_filebuf_watermark();
2472 cancel_cpu_boost();
2475 if (!pcmbuf_queue_scan(&ev))
2476 queue_wait_w_tmo(&audio_queue, &ev, HZ/2);
2478 switch (ev.id) {
2480 case Q_AUDIO_FILL_BUFFER:
2481 LOGFQUEUE("audio < Q_AUDIO_FILL_BUFFER %d", (int)ev.data);
2482 audio_fill_file_buffer((bool)ev.data, 0);
2483 break;
2485 case Q_AUDIO_FINISH_LOAD:
2486 LOGFQUEUE("audio < Q_AUDIO_FINISH_LOAD");
2487 audio_finish_load_track();
2488 break;
2490 case Q_AUDIO_PLAY:
2491 LOGFQUEUE("audio < Q_AUDIO_PLAY");
2492 if (playing && ev.data <= 0)
2493 audio_new_playlist();
2494 else
2496 audio_stop_playback();
2497 audio_play_start((size_t)ev.data);
2499 break;
2501 case Q_AUDIO_STOP:
2502 LOGFQUEUE("audio < Q_AUDIO_STOP");
2503 if (playing)
2504 audio_stop_playback();
2505 if (ev.data != 0)
2506 queue_clear(&audio_queue);
2507 break;
2509 case Q_AUDIO_PAUSE:
2510 LOGFQUEUE("audio < Q_AUDIO_PAUSE");
2511 if (!(bool) ev.data && skipped_during_pause && !pcmbuf_is_crossfade_active())
2512 pcmbuf_play_stop(); /* Flush old track on resume after skip */
2513 skipped_during_pause = false;
2514 if (!playing)
2515 break;
2516 pcmbuf_pause((bool)ev.data);
2517 paused = (bool)ev.data;
2518 break;
2520 case Q_AUDIO_SKIP:
2521 LOGFQUEUE("audio < Q_AUDIO_SKIP");
2522 audio_initiate_track_change((long)ev.data);
2523 break;
2525 case Q_AUDIO_PRE_FF_REWIND:
2526 LOGFQUEUE("audio < Q_AUDIO_PRE_FF_REWIND");
2527 if (!playing)
2528 break;
2529 pcmbuf_pause(true);
2530 break;
2532 case Q_AUDIO_FF_REWIND:
2533 LOGFQUEUE("audio < Q_AUDIO_FF_REWIND");
2534 if (!playing)
2535 break;
2536 if (automatic_skip)
2538 /* An automatic track skip is in progress. Finalize it,
2539 then go back to the previous track */
2540 audio_finalise_track_change();
2541 ci.new_track = -1;
2543 ci.seek_time = (long)ev.data+1;
2544 break;
2546 case Q_AUDIO_CHECK_NEW_TRACK:
2547 LOGFQUEUE("audio < Q_AUDIO_CHECK_NEW_TRACK");
2548 queue_reply(&audio_queue, audio_check_new_track());
2549 break;
2551 case Q_AUDIO_DIR_SKIP:
2552 LOGFQUEUE("audio < Q_AUDIO_DIR_SKIP");
2553 audio_initiate_dir_change(ev.data);
2554 break;
2556 case Q_AUDIO_FLUSH:
2557 LOGFQUEUE("audio < Q_AUDIO_FLUSH");
2558 audio_invalidate_tracks();
2559 break;
2561 case Q_AUDIO_TRACK_CHANGED:
2562 /* PCM track change done */
2563 LOGFQUEUE("audio < Q_AUDIO_TRACK_CHANGED");
2564 audio_finalise_track_change();
2565 break;
2567 #ifndef SIMULATOR
2568 case SYS_USB_CONNECTED:
2569 LOGFQUEUE("audio < SYS_USB_CONNECTED");
2570 if (playing)
2571 audio_stop_playback();
2572 #ifdef PLAYBACK_VOICE
2573 voice_stop();
2574 #endif
2575 usb_acknowledge(SYS_USB_CONNECTED_ACK);
2576 usb_wait_for_disconnect(&audio_queue);
2578 /* Mark all entries null. */
2579 audio_clear_track_entries();
2581 /* release tracks to make sure all handles are closed */
2582 audio_release_tracks();
2583 break;
2584 #endif
2586 case SYS_TIMEOUT:
2587 LOGFQUEUE_SYS_TIMEOUT("audio < SYS_TIMEOUT");
2588 break;
2590 default:
2591 LOGFQUEUE("audio < default");
2592 break;
2593 } /* end switch */
2594 } /* end while */
2597 /* Initialize the audio system - called from init() in main.c.
2598 * Last function because of all the references to internal symbols
2600 void audio_init(void)
2602 unsigned int audio_thread_id;
2604 /* Can never do this twice */
2605 if (audio_is_initialized)
2607 logf("audio: already initialized");
2608 return;
2611 logf("audio: initializing");
2613 /* Initialize queues before giving control elsewhere in case it likes
2614 to send messages. Thread creation will be delayed however so nothing
2615 starts running until ready if something yields such as talk_init. */
2616 queue_init(&audio_queue, true);
2617 queue_init(&codec_queue, false);
2618 queue_init(&pcmbuf_queue, false);
2620 pcm_init();
2622 /* Initialize codec api. */
2623 ci.read_filebuf = codec_filebuf_callback;
2624 ci.pcmbuf_insert = codec_pcmbuf_insert_callback;
2625 ci.codec_get_buffer = codec_get_buffer;
2626 ci.request_buffer = codec_request_buffer_callback;
2627 ci.advance_buffer = codec_advance_buffer_callback;
2628 ci.advance_buffer_loc = codec_advance_buffer_loc_callback;
2629 ci.request_next_track = codec_request_next_track_callback;
2630 ci.seek_buffer = codec_seek_buffer_callback;
2631 ci.seek_complete = codec_seek_complete_callback;
2632 ci.set_elapsed = codec_set_elapsed_callback;
2633 ci.set_offset = codec_set_offset_callback;
2634 ci.configure = codec_configure_callback;
2635 ci.discard_codec = codec_discard_codec_callback;
2636 ci.dsp = (struct dsp_config *)dsp_configure(NULL, DSP_MYDSP,
2637 CODEC_IDX_AUDIO);
2639 thistrack_id3 = &mp3entry_buf[0];
2640 othertrack_id3 = &mp3entry_buf[1];
2642 /* cuesheet support */
2643 if (global_settings.cuesheet)
2644 curr_cue = (struct cuesheet*)buffer_alloc(sizeof(struct cuesheet));
2646 /* initialize the buffer */
2647 filebuf = audiobuf;
2649 /* audio_reset_buffer must to know the size of voice buffer so init
2650 talk first */
2651 talk_init();
2653 codec_thread_id = create_thread(
2654 codec_thread, codec_stack, sizeof(codec_stack),
2655 CREATE_THREAD_FROZEN,
2656 codec_thread_name IF_PRIO(, PRIORITY_PLAYBACK)
2657 IF_COP(, CPU));
2659 queue_enable_queue_send(&codec_queue, &codec_queue_sender_list,
2660 codec_thread_id);
2662 audio_thread_id = create_thread(audio_thread, audio_stack,
2663 sizeof(audio_stack), CREATE_THREAD_FROZEN,
2664 audio_thread_name IF_PRIO(, PRIORITY_USER_INTERFACE)
2665 IF_COP(, CPU));
2667 queue_enable_queue_send(&audio_queue, &audio_queue_sender_list,
2668 audio_thread_id);
2670 #ifdef PLAYBACK_VOICE
2671 voice_thread_init();
2672 #endif
2674 /* Set crossfade setting for next buffer init which should be about... */
2675 pcmbuf_crossfade_enable(global_settings.crossfade);
2677 /* initialize the buffering system */
2679 buffering_init();
2680 /* ...now! Set up the buffers */
2681 audio_reset_buffer();
2683 int i;
2684 for(i = 0; i < MAX_TRACK; i++)
2686 tracks[i].audio_hid = -1;
2687 tracks[i].id3_hid = -1;
2688 tracks[i].codec_hid = -1;
2689 #ifdef HAVE_ALBUMART
2690 tracks[i].aa_hid = -1;
2691 #endif
2692 tracks[i].cuesheet_hid = -1;
2695 add_event(BUFFER_EVENT_REBUFFER, false, buffering_handle_rebuffer_callback);
2696 add_event(BUFFER_EVENT_FINISHED, false, buffering_handle_finished_callback);
2698 /* Probably safe to say */
2699 audio_is_initialized = true;
2701 sound_settings_apply();
2702 #ifdef HAVE_DISK_STORAGE
2703 audio_set_buffer_margin(global_settings.buffer_margin);
2704 #endif
2706 /* it's safe to let the threads run now */
2707 #ifdef PLAYBACK_VOICE
2708 voice_thread_resume();
2709 #endif
2710 thread_thaw(codec_thread_id);
2711 thread_thaw(audio_thread_id);
2713 } /* audio_init */
2715 bool audio_is_thread_ready(void)
2717 return audio_thread_ready;