Don't recalculate the array length during the loop, use the ARRAYLEN macro and correc...
[kugel-rb.git] / apps / playback.c
blob2a015da4c5b54a009501bb214cf6f548fb3e6bf0
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 && !thistrack_id3->cuesheet)
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 && !thistrack_id3->cuesheet)
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];
1856 if (look_for_cuesheet_file(track_id3->path, cuepath))
1858 void *temp;
1859 tracks[track_widx].cuesheet_hid =
1860 bufalloc(NULL, sizeof(struct cuesheet), TYPE_CUESHEET);
1861 if (tracks[track_widx].cuesheet_hid >= 0)
1863 bufgetdata(tracks[track_widx].cuesheet_hid,
1864 sizeof(struct cuesheet), &temp);
1865 struct cuesheet *cuesheet = (struct cuesheet*)temp;
1866 if (!parse_cuesheet(cuepath, cuesheet))
1868 bufclose(tracks[track_widx].cuesheet_hid);
1869 track_id3->cuesheet = NULL;
1874 #ifdef HAVE_ALBUMART
1875 if (tracks[track_widx].aa_hid < 0 && gui_sync_wps_uses_albumart())
1877 char aa_path[MAX_PATH];
1878 if (find_albumart(track_id3, aa_path, sizeof(aa_path)))
1880 tracks[track_widx].aa_hid = bufopen(aa_path, 0, TYPE_BITMAP);
1882 if(tracks[track_widx].aa_hid == ERR_BUFFER_FULL)
1884 filling = STATE_FULL;
1885 logf("buffer is full for now");
1886 return; /* No space for track's album art, not an error */
1888 else if (tracks[track_widx].aa_hid < 0)
1890 /* another error, ignore AlbumArt */
1891 logf("Album art loading failed");
1895 #endif
1897 /* Load the codec. */
1898 if (!audio_loadcodec(start_play))
1900 if (tracks[track_widx].codec_hid == ERR_BUFFER_FULL)
1902 /* No space for codec on buffer, not an error */
1903 filling = STATE_FULL;
1904 return;
1907 /* This is an error condition, either no codec was found, or reading
1908 * the codec file failed part way through, either way, skip the track */
1909 /* FIXME: We should not use splashf from audio thread! */
1910 splashf(HZ*2, "No codec for: %s", track_id3->path);
1911 /* Skip invalid entry from playlist. */
1912 playlist_skip_entry(NULL, last_peek_offset);
1913 return;
1916 track_id3->elapsed = 0;
1917 offset = track_id3->offset;
1919 enum data_type type = TYPE_PACKET_AUDIO;
1921 switch (track_id3->codectype) {
1922 case AFMT_MPA_L1:
1923 case AFMT_MPA_L2:
1924 case AFMT_MPA_L3:
1925 if (offset > 0) {
1926 file_offset = offset;
1927 track_id3->offset = offset;
1929 break;
1931 case AFMT_WAVPACK:
1932 if (offset > 0) {
1933 file_offset = offset;
1934 track_id3->offset = offset;
1935 track_id3->elapsed = track_id3->length / 2;
1937 break;
1939 case AFMT_OGG_VORBIS:
1940 case AFMT_SPEEX:
1941 case AFMT_FLAC:
1942 case AFMT_PCM_WAV:
1943 case AFMT_A52:
1944 case AFMT_MP4_AAC:
1945 case AFMT_MPC:
1946 case AFMT_APE:
1947 case AFMT_WMA:
1948 if (offset > 0)
1949 track_id3->offset = offset;
1950 break;
1952 case AFMT_NSF:
1953 case AFMT_SPC:
1954 case AFMT_SID:
1955 logf("Loading atomic %d",track_id3->codectype);
1956 type = TYPE_ATOMIC_AUDIO;
1957 break;
1960 logf("alt:%s", track_id3->path);
1962 if (file_offset > AUDIO_REBUFFER_GUESS_SIZE)
1963 file_offset -= AUDIO_REBUFFER_GUESS_SIZE;
1964 else if (track_id3->first_frame_offset)
1965 file_offset = track_id3->first_frame_offset;
1966 else
1967 file_offset = 0;
1969 tracks[track_widx].audio_hid = bufopen(track_id3->path, file_offset, type);
1971 /* No space left, not an error */
1972 if (tracks[track_widx].audio_hid == ERR_BUFFER_FULL)
1974 filling = STATE_FULL;
1975 logf("buffer is full for now");
1976 return;
1978 else if (tracks[track_widx].audio_hid < 0)
1980 /* another error, do not continue either */
1981 logf("Could not add audio data handle");
1982 return;
1985 /* All required data is now available for the codec. */
1986 tracks[track_widx].taginfo_ready = true;
1988 if (start_play)
1990 ci.curpos=file_offset;
1991 buf_request_buffer_handle(tracks[track_widx].audio_hid);
1994 track_widx = (track_widx + 1) & MAX_TRACK_MASK;
1996 send_event(PLAYBACK_EVENT_TRACK_BUFFER, track_id3);
1998 /* load next track */
1999 LOGFQUEUE("audio > audio Q_AUDIO_FILL_BUFFER");
2000 queue_post(&audio_queue, Q_AUDIO_FILL_BUFFER, 0);
2002 return;
2005 static void audio_fill_file_buffer(bool start_play, size_t offset)
2007 trigger_cpu_boost();
2009 /* No need to rebuffer if there are track skips pending,
2010 * however don't cancel buffering on skipping while filling. */
2011 if (ci.new_track != 0 && filling != STATE_FILLING)
2012 return;
2013 filling = STATE_FILLING;
2015 /* Must reset the buffer before use if trashed or voice only - voice
2016 file size shouldn't have changed so we can go straight from
2017 AUDIOBUF_STATE_VOICED_ONLY to AUDIOBUF_STATE_INITIALIZED */
2018 if (buffer_state != AUDIOBUF_STATE_INITIALIZED)
2019 audio_reset_buffer();
2021 logf("Starting buffer fill");
2023 if (!start_play)
2024 audio_clear_track_entries();
2026 /* Save the current resume position once. */
2027 playlist_update_resume_info(audio_current_track());
2029 audio_load_track(offset, start_play);
2032 static void audio_rebuffer(void)
2034 logf("Forcing rebuffer");
2036 clear_track_info(CUR_TI);
2038 /* Reset track pointers */
2039 track_widx = track_ridx;
2040 audio_clear_track_entries();
2042 /* Reset a possibly interrupted track load */
2043 track_load_started = false;
2045 /* Fill the buffer */
2046 last_peek_offset = -1;
2047 ci.curpos = 0;
2049 if (!CUR_TI->taginfo_ready)
2050 memset(thistrack_id3, 0, sizeof(struct mp3entry));
2052 audio_fill_file_buffer(false, 0);
2055 /* Called on request from the codec to get a new track. This is the codec part
2056 of the track transition. */
2057 static int audio_check_new_track(void)
2059 int track_count = audio_track_count();
2060 int old_track_ridx = track_ridx;
2061 int i, idx;
2062 bool forward;
2063 struct mp3entry *temp = thistrack_id3;
2065 /* Now it's good time to send track finish events. */
2066 send_event(PLAYBACK_EVENT_TRACK_FINISH, thistrack_id3);
2067 /* swap the mp3entry pointers */
2068 thistrack_id3 = othertrack_id3;
2069 othertrack_id3 = temp;
2070 ci.id3 = thistrack_id3;
2071 memset(thistrack_id3, 0, sizeof(struct mp3entry));
2073 if (dir_skip)
2075 dir_skip = false;
2076 /* regardless of the return value we need to rebuffer.
2077 if it fails the old playlist will resume, else the
2078 next dir will start playing */
2079 playlist_next_dir(ci.new_track);
2080 ci.new_track = 0;
2081 audio_rebuffer();
2082 goto skip_done;
2085 if (new_playlist)
2086 ci.new_track = 0;
2088 /* If the playlist isn't that big */
2089 if (automatic_skip)
2091 while (!playlist_check(ci.new_track))
2093 if (ci.new_track >= 0)
2095 LOGFQUEUE("audio >|= codec Q_CODEC_REQUEST_FAILED");
2096 return Q_CODEC_REQUEST_FAILED;
2098 ci.new_track++;
2102 /* Update the playlist */
2103 last_peek_offset -= ci.new_track;
2105 if (playlist_next(ci.new_track) < 0)
2107 LOGFQUEUE("audio >|= codec Q_CODEC_REQUEST_FAILED");
2108 return Q_CODEC_REQUEST_FAILED;
2111 if (new_playlist)
2113 ci.new_track = 1;
2114 new_playlist = false;
2117 /* Save a pointer to the old track to allow later clearing */
2118 prev_ti = CUR_TI;
2120 for (i = 0; i < ci.new_track; i++)
2122 idx = (track_ridx + i) & MAX_TRACK_MASK;
2123 struct mp3entry *id3 = bufgetid3(tracks[idx].id3_hid);
2124 ssize_t offset = buf_handle_offset(tracks[idx].audio_hid);
2125 if (!id3 || offset < 0 || (unsigned)offset > id3->first_frame_offset)
2127 /* We don't have all the audio data for that track, so clear it,
2128 but keep the metadata. */
2129 if (tracks[idx].audio_hid >= 0 && bufclose(tracks[idx].audio_hid))
2131 tracks[idx].audio_hid = -1;
2132 tracks[idx].filesize = 0;
2137 /* Move to the new track */
2138 track_ridx = (track_ridx + ci.new_track) & MAX_TRACK_MASK;
2140 buf_set_base_handle(CUR_TI->audio_hid);
2142 if (automatic_skip)
2144 wps_offset = -ci.new_track;
2147 /* If it is not safe to even skip this many track entries */
2148 if (ci.new_track >= track_count || ci.new_track <= track_count - MAX_TRACK)
2150 ci.new_track = 0;
2151 audio_rebuffer();
2152 goto skip_done;
2155 forward = ci.new_track > 0;
2156 ci.new_track = 0;
2158 /* If the target track is clearly not in memory */
2159 if (CUR_TI->filesize == 0 || !CUR_TI->taginfo_ready)
2161 audio_rebuffer();
2162 goto skip_done;
2165 /* When skipping backwards, it is possible that we've found a track that's
2166 * buffered, but which is around the track-wrap and therefore not the track
2167 * we are looking for */
2168 if (!forward)
2170 int cur_idx = track_ridx;
2171 bool taginfo_ready = true;
2172 /* We've wrapped the buffer backwards if new > old */
2173 bool wrap = track_ridx > old_track_ridx;
2175 while (1)
2177 cur_idx = (cur_idx + 1) & MAX_TRACK_MASK;
2179 /* if we've advanced past the wrap when cur_idx is zeroed */
2180 if (!cur_idx)
2181 wrap = false;
2183 /* if we aren't still on the wrap and we've caught the old track */
2184 if (!(wrap || cur_idx < old_track_ridx))
2185 break;
2187 /* If we hit a track in between without valid tag info, bail */
2188 if (!tracks[cur_idx].taginfo_ready)
2190 taginfo_ready = false;
2191 break;
2194 if (!taginfo_ready)
2196 audio_rebuffer();
2200 skip_done:
2201 audio_update_trackinfo();
2202 LOGFQUEUE("audio >|= codec Q_CODEC_REQUEST_COMPLETE");
2203 return Q_CODEC_REQUEST_COMPLETE;
2206 unsigned long audio_prev_elapsed(void)
2208 return prev_track_elapsed;
2211 static void audio_stop_codec_flush(void)
2213 ci.stop_codec = true;
2214 pcmbuf_pause(true);
2216 while (audio_codec_loaded)
2217 yield();
2219 /* If the audio codec is not loaded any more, and the audio is still
2220 * playing, it is now and _only_ now safe to call this function from the
2221 * audio thread */
2222 if (pcm_is_playing())
2224 pcmbuf_play_stop();
2225 pcmbuf_queue_clear();
2227 pcmbuf_pause(paused);
2230 static void audio_stop_playback(void)
2232 if (playing)
2234 /* If still actively playing here, play out the last samples in the track
2235 * before stopping. A manual stop is actually paused at this point, so
2236 * don't continue playback.
2238 if (!paused)
2239 pcmbuf_play_remainder();
2241 /* If we were playing, save resume information */
2242 struct mp3entry *id3 = NULL;
2244 if (!ci.stop_codec)
2246 /* Set this early, the outside code yields and may allow the codec
2247 to try to wait for a reply on a buffer wait */
2248 ci.stop_codec = true;
2249 id3 = audio_current_track();
2252 /* Save the current playing spot, or NULL if the playlist has ended */
2253 playlist_update_resume_info(id3);
2255 /* TODO: Create auto bookmark too? */
2257 prev_track_elapsed = othertrack_id3->elapsed;
2259 remove_event(BUFFER_EVENT_BUFFER_LOW, buffering_low_buffer_callback);
2262 audio_stop_codec_flush();
2263 paused = false;
2264 playing = false;
2265 track_load_started = false;
2267 filling = STATE_IDLE;
2269 /* Mark all entries null. */
2270 audio_clear_track_entries();
2272 /* Close all tracks */
2273 audio_release_tracks();
2276 static void audio_play_start(size_t offset)
2278 int i;
2280 #if INPUT_SRC_CAPS != 0
2281 audio_set_input_source(AUDIO_SRC_PLAYBACK, SRCF_PLAYBACK);
2282 audio_set_output_source(AUDIO_SRC_PLAYBACK);
2283 #endif
2285 /* Wait for any previously playing audio to flush - TODO: Not necessary? */
2286 paused = false;
2287 audio_stop_codec_flush();
2289 playing = true;
2290 track_load_started = false;
2292 ci.new_track = 0;
2293 ci.seek_time = 0;
2294 wps_offset = 0;
2296 sound_set_volume(global_settings.volume);
2297 track_widx = track_ridx = 0;
2299 /* Clear all track entries. */
2300 for (i = 0; i < MAX_TRACK; i++) {
2301 clear_track_info(&tracks[i]);
2304 last_peek_offset = -1;
2306 /* Officially playing */
2307 queue_reply(&audio_queue, 1);
2309 audio_fill_file_buffer(true, offset);
2311 add_event(BUFFER_EVENT_BUFFER_LOW, false, buffering_low_buffer_callback);
2313 LOGFQUEUE("audio > audio Q_AUDIO_TRACK_CHANGED");
2314 queue_post(&audio_queue, Q_AUDIO_TRACK_CHANGED, 0);
2318 /* Invalidates all but currently playing track. */
2319 static void audio_invalidate_tracks(void)
2321 if (audio_have_tracks())
2323 last_peek_offset = 0;
2324 track_widx = track_ridx;
2326 /* Mark all other entries null (also buffered wrong metadata). */
2327 audio_clear_track_entries();
2329 track_widx = (track_widx + 1) & MAX_TRACK_MASK;
2331 audio_fill_file_buffer(false, 0);
2335 static void audio_new_playlist(void)
2337 /* Prepare to start a new fill from the beginning of the playlist */
2338 last_peek_offset = -1;
2339 if (audio_have_tracks())
2341 if (paused)
2342 skipped_during_pause = true;
2343 track_widx = track_ridx;
2344 audio_clear_track_entries();
2346 track_widx = (track_widx + 1) & MAX_TRACK_MASK;
2348 /* Mark the current track as invalid to prevent skipping back to it */
2349 CUR_TI->taginfo_ready = false;
2352 /* Signal the codec to initiate a track change forward */
2353 new_playlist = true;
2354 ci.new_track = 1;
2356 /* Officially playing */
2357 queue_reply(&audio_queue, 1);
2359 audio_fill_file_buffer(false, 0);
2362 /* Called on manual track skip */
2363 static void audio_initiate_track_change(long direction)
2365 logf("audio_initiate_track_change(%ld)", direction);
2367 ci.new_track += direction;
2368 wps_offset -= direction;
2369 if (paused)
2370 skipped_during_pause = true;
2373 /* Called on manual dir skip */
2374 static void audio_initiate_dir_change(long direction)
2376 dir_skip = true;
2377 ci.new_track = direction;
2378 if (paused)
2379 skipped_during_pause = true;
2382 /* Called when PCM track change is complete */
2383 static void audio_finalise_track_change(void)
2385 logf("audio_finalise_track_change");
2387 if (automatic_skip)
2389 wps_offset = 0;
2390 automatic_skip = false;
2392 /* Invalidate prevtrack_id3 */
2393 memset(othertrack_id3, 0, sizeof(struct mp3entry));
2395 if (prev_ti && prev_ti->audio_hid < 0)
2397 /* No audio left so we clear all the track info. */
2398 clear_track_info(prev_ti);
2401 send_event(PLAYBACK_EVENT_TRACK_CHANGE, thistrack_id3);
2402 playlist_update_resume_info(audio_current_track());
2406 * Layout audio buffer as follows - iram buffer depends on target:
2407 * [|SWAP:iram][|TALK]|FILE|GUARD|PCM|[SWAP:dram[|iram]|]
2409 static void audio_reset_buffer(void)
2411 /* see audio_get_recording_buffer if this is modified */
2412 logf("audio_reset_buffer");
2414 /* If the setup of anything allocated before the file buffer is
2415 changed, do check the adjustments after the buffer_alloc call
2416 as it will likely be affected and need sliding over */
2418 /* Initially set up file buffer as all space available */
2419 malloc_buf = audiobuf + talk_get_bufsize();
2420 /* Align the malloc buf to line size. Especially important to cf
2421 targets that do line reads/writes. */
2422 malloc_buf = (unsigned char *)(((uintptr_t)malloc_buf + 15) & ~15);
2423 filebuf = malloc_buf; /* filebuf line align implied */
2424 filebuflen = audiobufend - filebuf;
2426 filebuflen &= ~15;
2428 /* Subtract whatever the pcm buffer says it used plus the guard buffer */
2429 const size_t pcmbuf_size = pcmbuf_init(filebuf + filebuflen) +GUARD_BUFSIZE;
2431 #ifdef DEBUG
2432 if(pcmbuf_size > filebuflen)
2433 panicf("Not enough memory for pcmbuf_init() : %d > %d",
2434 (int)pcmbuf_size, (int)filebuflen);
2435 #endif
2437 filebuflen -= pcmbuf_size;
2439 /* Make sure filebuflen is a longword multiple after adjustment - filebuf
2440 will already be line aligned */
2441 filebuflen &= ~3;
2443 buffering_reset(filebuf, filebuflen);
2445 /* Clear any references to the file buffer */
2446 buffer_state = AUDIOBUF_STATE_INITIALIZED;
2448 #if defined(ROCKBOX_HAS_LOGF) && defined(LOGF_ENABLE)
2449 /* Make sure everything adds up - yes, some info is a bit redundant but
2450 aids viewing and the sumation of certain variables should add up to
2451 the location of others. */
2453 size_t pcmbufsize;
2454 const unsigned char *pcmbuf = pcmbuf_get_meminfo(&pcmbufsize);
2455 logf("mabuf: %08X", (unsigned)malloc_buf);
2456 logf("fbuf: %08X", (unsigned)filebuf);
2457 logf("fbufe: %08X", (unsigned)(filebuf + filebuflen));
2458 logf("gbuf: %08X", (unsigned)(filebuf + filebuflen));
2459 logf("gbufe: %08X", (unsigned)(filebuf + filebuflen + GUARD_BUFSIZE));
2460 logf("pcmb: %08X", (unsigned)pcmbuf);
2461 logf("pcmbe: %08X", (unsigned)(pcmbuf + pcmbufsize));
2463 #endif
2466 static void audio_thread(void)
2468 struct queue_event ev;
2470 pcm_postinit();
2472 audio_thread_ready = true;
2474 while (1)
2476 if (filling != STATE_FILLING) {
2477 /* End of buffering, let's calculate the watermark and unboost */
2478 set_filebuf_watermark();
2479 cancel_cpu_boost();
2482 if (!pcmbuf_queue_scan(&ev))
2483 queue_wait_w_tmo(&audio_queue, &ev, HZ/2);
2485 switch (ev.id) {
2487 case Q_AUDIO_FILL_BUFFER:
2488 LOGFQUEUE("audio < Q_AUDIO_FILL_BUFFER %d", (int)ev.data);
2489 audio_fill_file_buffer((bool)ev.data, 0);
2490 break;
2492 case Q_AUDIO_FINISH_LOAD:
2493 LOGFQUEUE("audio < Q_AUDIO_FINISH_LOAD");
2494 audio_finish_load_track();
2495 break;
2497 case Q_AUDIO_PLAY:
2498 LOGFQUEUE("audio < Q_AUDIO_PLAY");
2499 if (playing && ev.data <= 0)
2500 audio_new_playlist();
2501 else
2503 audio_stop_playback();
2504 audio_play_start((size_t)ev.data);
2506 break;
2508 case Q_AUDIO_STOP:
2509 LOGFQUEUE("audio < Q_AUDIO_STOP");
2510 if (playing)
2511 audio_stop_playback();
2512 if (ev.data != 0)
2513 queue_clear(&audio_queue);
2514 break;
2516 case Q_AUDIO_PAUSE:
2517 LOGFQUEUE("audio < Q_AUDIO_PAUSE");
2518 if (!(bool) ev.data && skipped_during_pause && !pcmbuf_is_crossfade_active())
2519 pcmbuf_play_stop(); /* Flush old track on resume after skip */
2520 skipped_during_pause = false;
2521 if (!playing)
2522 break;
2523 pcmbuf_pause((bool)ev.data);
2524 paused = (bool)ev.data;
2525 break;
2527 case Q_AUDIO_SKIP:
2528 LOGFQUEUE("audio < Q_AUDIO_SKIP");
2529 audio_initiate_track_change((long)ev.data);
2530 break;
2532 case Q_AUDIO_PRE_FF_REWIND:
2533 LOGFQUEUE("audio < Q_AUDIO_PRE_FF_REWIND");
2534 if (!playing)
2535 break;
2536 pcmbuf_pause(true);
2537 break;
2539 case Q_AUDIO_FF_REWIND:
2540 LOGFQUEUE("audio < Q_AUDIO_FF_REWIND");
2541 if (!playing)
2542 break;
2543 if (automatic_skip)
2545 /* An automatic track skip is in progress. Finalize it,
2546 then go back to the previous track */
2547 audio_finalise_track_change();
2548 ci.new_track = -1;
2550 ci.seek_time = (long)ev.data+1;
2551 break;
2553 case Q_AUDIO_CHECK_NEW_TRACK:
2554 LOGFQUEUE("audio < Q_AUDIO_CHECK_NEW_TRACK");
2555 queue_reply(&audio_queue, audio_check_new_track());
2556 break;
2558 case Q_AUDIO_DIR_SKIP:
2559 LOGFQUEUE("audio < Q_AUDIO_DIR_SKIP");
2560 audio_initiate_dir_change(ev.data);
2561 break;
2563 case Q_AUDIO_FLUSH:
2564 LOGFQUEUE("audio < Q_AUDIO_FLUSH");
2565 audio_invalidate_tracks();
2566 break;
2568 case Q_AUDIO_TRACK_CHANGED:
2569 /* PCM track change done */
2570 LOGFQUEUE("audio < Q_AUDIO_TRACK_CHANGED");
2571 audio_finalise_track_change();
2572 break;
2574 #ifndef SIMULATOR
2575 case SYS_USB_CONNECTED:
2576 LOGFQUEUE("audio < SYS_USB_CONNECTED");
2577 if (playing)
2578 audio_stop_playback();
2579 #ifdef PLAYBACK_VOICE
2580 voice_stop();
2581 #endif
2582 usb_acknowledge(SYS_USB_CONNECTED_ACK);
2583 usb_wait_for_disconnect(&audio_queue);
2585 /* Mark all entries null. */
2586 audio_clear_track_entries();
2588 /* release tracks to make sure all handles are closed */
2589 audio_release_tracks();
2590 break;
2591 #endif
2593 case SYS_TIMEOUT:
2594 LOGFQUEUE_SYS_TIMEOUT("audio < SYS_TIMEOUT");
2595 break;
2597 default:
2598 LOGFQUEUE("audio < default");
2599 break;
2600 } /* end switch */
2601 } /* end while */
2604 /* Initialize the audio system - called from init() in main.c.
2605 * Last function because of all the references to internal symbols
2607 void audio_init(void)
2609 unsigned int audio_thread_id;
2611 /* Can never do this twice */
2612 if (audio_is_initialized)
2614 logf("audio: already initialized");
2615 return;
2618 logf("audio: initializing");
2620 /* Initialize queues before giving control elsewhere in case it likes
2621 to send messages. Thread creation will be delayed however so nothing
2622 starts running until ready if something yields such as talk_init. */
2623 queue_init(&audio_queue, true);
2624 queue_init(&codec_queue, false);
2625 queue_init(&pcmbuf_queue, false);
2627 pcm_init();
2629 /* Initialize codec api. */
2630 ci.read_filebuf = codec_filebuf_callback;
2631 ci.pcmbuf_insert = codec_pcmbuf_insert_callback;
2632 ci.codec_get_buffer = codec_get_buffer;
2633 ci.request_buffer = codec_request_buffer_callback;
2634 ci.advance_buffer = codec_advance_buffer_callback;
2635 ci.advance_buffer_loc = codec_advance_buffer_loc_callback;
2636 ci.request_next_track = codec_request_next_track_callback;
2637 ci.seek_buffer = codec_seek_buffer_callback;
2638 ci.seek_complete = codec_seek_complete_callback;
2639 ci.set_elapsed = codec_set_elapsed_callback;
2640 ci.set_offset = codec_set_offset_callback;
2641 ci.configure = codec_configure_callback;
2642 ci.discard_codec = codec_discard_codec_callback;
2643 ci.dsp = (struct dsp_config *)dsp_configure(NULL, DSP_MYDSP,
2644 CODEC_IDX_AUDIO);
2646 thistrack_id3 = &mp3entry_buf[0];
2647 othertrack_id3 = &mp3entry_buf[1];
2649 /* cuesheet support */
2650 if (global_settings.cuesheet)
2651 curr_cue = (struct cuesheet*)buffer_alloc(sizeof(struct cuesheet));
2653 /* initialize the buffer */
2654 filebuf = audiobuf;
2656 /* audio_reset_buffer must to know the size of voice buffer so init
2657 talk first */
2658 talk_init();
2660 codec_thread_id = create_thread(
2661 codec_thread, codec_stack, sizeof(codec_stack),
2662 CREATE_THREAD_FROZEN,
2663 codec_thread_name IF_PRIO(, PRIORITY_PLAYBACK)
2664 IF_COP(, CPU));
2666 queue_enable_queue_send(&codec_queue, &codec_queue_sender_list,
2667 codec_thread_id);
2669 audio_thread_id = create_thread(audio_thread, audio_stack,
2670 sizeof(audio_stack), CREATE_THREAD_FROZEN,
2671 audio_thread_name IF_PRIO(, PRIORITY_USER_INTERFACE)
2672 IF_COP(, CPU));
2674 queue_enable_queue_send(&audio_queue, &audio_queue_sender_list,
2675 audio_thread_id);
2677 #ifdef PLAYBACK_VOICE
2678 voice_thread_init();
2679 #endif
2681 /* Set crossfade setting for next buffer init which should be about... */
2682 pcmbuf_crossfade_enable(global_settings.crossfade);
2684 /* initialize the buffering system */
2686 buffering_init();
2687 /* ...now! Set up the buffers */
2688 audio_reset_buffer();
2690 int i;
2691 for(i = 0; i < MAX_TRACK; i++)
2693 tracks[i].audio_hid = -1;
2694 tracks[i].id3_hid = -1;
2695 tracks[i].codec_hid = -1;
2696 #ifdef HAVE_ALBUMART
2697 tracks[i].aa_hid = -1;
2698 #endif
2699 tracks[i].cuesheet_hid = -1;
2702 add_event(BUFFER_EVENT_REBUFFER, false, buffering_handle_rebuffer_callback);
2703 add_event(BUFFER_EVENT_FINISHED, false, buffering_handle_finished_callback);
2705 /* Probably safe to say */
2706 audio_is_initialized = true;
2708 sound_settings_apply();
2709 #ifdef HAVE_DISK_STORAGE
2710 audio_set_buffer_margin(global_settings.buffer_margin);
2711 #endif
2713 /* it's safe to let the threads run now */
2714 #ifdef PLAYBACK_VOICE
2715 voice_thread_resume();
2716 #endif
2717 thread_thaw(codec_thread_id);
2718 thread_thaw(audio_thread_id);
2720 } /* audio_init */
2722 bool audio_is_thread_ready(void)
2724 return audio_thread_ready;