* Onda VX747: add browse screen, pitchscreen, context menu, quickscreen, rewind...
[kugel-rb.git] / apps / playback.c
blobbe8377be14df1db90528d78ba6e6dc0eaa40d9a8
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 "misc.h"
71 #include "sound.h"
72 #include "metadata.h"
73 #include "splash.h"
74 #include "talk.h"
75 #include "ata_idle_notify.h"
77 #ifdef HAVE_RECORDING
78 #include "recording.h"
79 #include "pcm_record.h"
80 #endif
82 #ifdef IPOD_ACCESSORY_PROTOCOL
83 #include "iap.h"
84 #endif
86 #define PLAYBACK_VOICE
88 /* amount of guess-space to allow for codecs that must hunt and peck
89 * for their correct seeek target, 32k seems a good size */
90 #define AUDIO_REBUFFER_GUESS_SIZE (1024*32)
92 /* Define LOGF_ENABLE to enable logf output in this file */
93 /*#define LOGF_ENABLE*/
94 #include "logf.h"
96 /* macros to enable logf for queues
97 logging on SYS_TIMEOUT can be disabled */
98 #ifdef SIMULATOR
99 /* Define this for logf output of all queuing except SYS_TIMEOUT */
100 #define PLAYBACK_LOGQUEUES
101 /* Define this to logf SYS_TIMEOUT messages */
102 /*#define PLAYBACK_LOGQUEUES_SYS_TIMEOUT*/
103 #endif
105 #ifdef PLAYBACK_LOGQUEUES
106 #define LOGFQUEUE logf
107 #else
108 #define LOGFQUEUE(...)
109 #endif
111 #ifdef PLAYBACK_LOGQUEUES_SYS_TIMEOUT
112 #define LOGFQUEUE_SYS_TIMEOUT logf
113 #else
114 #define LOGFQUEUE_SYS_TIMEOUT(...)
115 #endif
118 /* Define one constant that includes recording related functionality */
119 #if defined(HAVE_RECORDING) && !defined(SIMULATOR)
120 #define AUDIO_HAVE_RECORDING
121 #endif
123 enum {
124 Q_NULL = 0,
125 Q_AUDIO_PLAY = 1,
126 Q_AUDIO_STOP,
127 Q_AUDIO_PAUSE,
128 Q_AUDIO_SKIP,
129 Q_AUDIO_PRE_FF_REWIND,
130 Q_AUDIO_FF_REWIND,
131 Q_AUDIO_CHECK_NEW_TRACK,
132 Q_AUDIO_FLUSH,
133 Q_AUDIO_TRACK_CHANGED,
134 Q_AUDIO_DIR_SKIP,
135 Q_AUDIO_POSTINIT,
136 Q_AUDIO_FILL_BUFFER,
137 Q_AUDIO_FINISH_LOAD,
138 Q_CODEC_REQUEST_COMPLETE,
139 Q_CODEC_REQUEST_FAILED,
141 Q_CODEC_LOAD,
142 Q_CODEC_LOAD_DISK,
144 #ifdef AUDIO_HAVE_RECORDING
145 Q_ENCODER_LOAD_DISK,
146 Q_ENCODER_RECORD,
147 #endif
149 Q_CODEC_DO_CALLBACK,
152 enum filling_state {
153 STATE_IDLE, /* audio is stopped: nothing to do */
154 STATE_FILLING, /* adding tracks to the buffer */
155 STATE_FULL, /* can't add any more tracks */
156 STATE_END_OF_PLAYLIST, /* all remaining tracks have been added */
157 STATE_FINISHED, /* all remaining tracks are fully buffered */
160 #define MAX_TRACK 128
162 #define MAX_TRACK_MASK (MAX_TRACK-1)
164 /* As defined in plugins/lib/xxx2wav.h */
165 #define GUARD_BUFSIZE (32*1024)
167 /* As defined in plugin.lds */
168 #if defined(CPU_PP)
169 #define CODEC_IRAM_ORIGIN ((unsigned char *)0x4000c000)
170 #define CODEC_IRAM_SIZE ((size_t)0xc000)
171 #elif defined(IAUDIO_X5) || defined(IAUDIO_M5)
172 #define CODEC_IRAM_ORIGIN ((unsigned char *)0x10010000)
173 #define CODEC_IRAM_SIZE ((size_t)0x10000)
174 #else
175 #define CODEC_IRAM_ORIGIN ((unsigned char *)0x1000c000)
176 #define CODEC_IRAM_SIZE ((size_t)0xc000)
177 #endif
179 bool audio_is_initialized = false;
180 static bool audio_thread_ready SHAREDBSS_ATTR = false;
182 /* Variables are commented with the threads that use them: *
183 * A=audio, C=codec, V=voice. A suffix of - indicates that *
184 * the variable is read but not updated on that thread. */
185 /* TBD: Split out "audio" and "playback" (ie. calling) threads */
187 /* Main state control */
188 static volatile bool audio_codec_loaded SHAREDBSS_ATTR = false; /* Codec loaded? (C/A-) */
189 static volatile bool playing SHAREDBSS_ATTR = false; /* Is audio playing? (A) */
190 static volatile bool paused SHAREDBSS_ATTR = false; /* Is audio paused? (A/C-) */
192 /* Ring buffer where compressed audio and codecs are loaded */
193 static unsigned char *filebuf = NULL; /* Start of buffer (A/C-) */
194 static unsigned char *malloc_buf = NULL; /* Start of malloc buffer (A/C-) */
195 /* FIXME: make filebuflen static */
196 size_t filebuflen = 0; /* Size of buffer (A/C-) */
197 /* FIXME: make buf_ridx (C/A-) */
199 /* Possible arrangements of the buffer */
200 static int buffer_state = AUDIOBUF_STATE_TRASHED; /* Buffer state */
202 /* These are used to store the current and next (or prev if the current is the last)
203 * mp3entry's in a round-robin system. This guarentees that the pointer returned
204 * by audio_current/next_track will be valid for the full duration of the
205 * currently playing track */
206 static struct mp3entry mp3entry_buf[2];
207 static struct mp3entry *thistrack_id3, /* the currently playing track */
208 *othertrack_id3; /* prev track during track-change-transition, or end of playlist,
209 * next track otherwise */
210 static struct mp3entry unbuffered_id3; /* the id3 for the first unbuffered track */
212 /* for cuesheet support */
213 static struct cuesheet *curr_cue = NULL;
215 /* Track info structure about songs in the file buffer (A/C-) */
216 struct track_info {
217 int audio_hid; /* The ID for the track's buffer handle */
218 int id3_hid; /* The ID for the track's metadata handle */
219 int codec_hid; /* The ID for the track's codec handle */
220 #ifdef HAVE_ALBUMART
221 int aa_hid; /* The ID for the track's album art handle */
222 #endif
223 int cuesheet_hid; /* The ID for the track's parsed cueesheet handle */
225 size_t filesize; /* File total length */
227 bool taginfo_ready; /* Is metadata read */
230 static struct track_info tracks[MAX_TRACK];
231 static volatile int track_ridx = 0; /* Track being decoded (A/C-) */
232 static int track_widx = 0; /* Track being buffered (A) */
234 #define CUR_TI (&tracks[track_ridx]) /* Playing track info pointer (A/C-) */
235 static struct track_info *prev_ti = NULL; /* Pointer to the previously played
236 track */
238 /* Information used only for filling the buffer */
239 /* Playlist steps from playing track to next track to be buffered (A) */
240 static int last_peek_offset = 0;
242 /* Scrobbler support */
243 static unsigned long prev_track_elapsed = 0; /* Previous track elapsed time (C/A-)*/
245 static enum filling_state filling;
247 /* Track change controls */
248 static bool automatic_skip = false; /* Who initiated in-progress skip? (C/A-) */
249 static bool dir_skip = false; /* Is a directory skip pending? (A) */
250 static bool new_playlist = false; /* Are we starting a new playlist? (A) */
251 static int wps_offset = 0; /* Pending track change offset, to keep WPS responsive (A) */
252 static bool skipped_during_pause = false; /* Do we need to clear the PCM buffer when playback resumes (A) */
254 static bool start_play_g = false; /* Used by audio_load_track to notify
255 audio_finish_load_track about start_play */
257 /* True when a track load is in progress, i.e. audio_load_track() has returned
258 * but audio_finish_load_track() hasn't been called yet. Used to avoid allowing
259 * audio_load_track() to get called twice in a row, which would cause problems.
261 static bool track_load_started = false;
263 /* Set to true if the codec thread should send an audio stop request
264 * (typically because the end of the playlist has been reached).
266 static bool codec_requested_stop = false;
268 #ifdef HAVE_DISK_STORAGE
269 static size_t buffer_margin = 5; /* Buffer margin aka anti-skip buffer (A/C-) */
270 #endif
272 /* Multiple threads */
273 /* Set the watermark to trigger buffer fill (A/C) */
274 static void set_filebuf_watermark(void);
276 /* Audio thread */
277 static struct event_queue audio_queue SHAREDBSS_ATTR;
278 static struct queue_sender_list audio_queue_sender_list SHAREDBSS_ATTR;
279 static long audio_stack[(DEFAULT_STACK_SIZE + 0x1000)/sizeof(long)];
280 static const char audio_thread_name[] = "audio";
282 static void audio_thread(void);
283 static void audio_initiate_track_change(long direction);
284 static bool audio_have_tracks(void);
285 static void audio_reset_buffer(void);
286 static void audio_stop_playback(void);
288 /* Codec thread */
289 extern struct codec_api ci;
290 static struct event_queue codec_queue SHAREDBSS_ATTR;
291 static struct queue_sender_list codec_queue_sender_list;
292 static long codec_stack[(DEFAULT_STACK_SIZE + 0x2000)/sizeof(long)]
293 IBSS_ATTR;
294 static const char codec_thread_name[] = "codec";
295 unsigned int codec_thread_id; /* For modifying thread priority later. */
297 /* PCM buffer messaging */
298 static struct event_queue pcmbuf_queue SHAREDBSS_ATTR;
300 /* Function to be called by pcm buffer callbacks.
301 * Permissible Context(s): Audio interrupt
303 static void pcmbuf_callback_queue_post(long id, intptr_t data)
305 /* No lock since we're already in audio interrupt context */
306 queue_post(&pcmbuf_queue, id, data);
309 /* Scan the pcmbuf queue and return true if a message pulled.
310 * Permissible Context(s): Thread
312 static bool pcmbuf_queue_scan(struct queue_event *ev)
314 if (!queue_empty(&pcmbuf_queue))
316 /* Transfer message to audio queue */
317 pcm_play_lock();
318 /* Pull message - never, ever any blocking call! */
319 queue_wait_w_tmo(&pcmbuf_queue, ev, 0);
320 pcm_play_unlock();
321 return true;
324 return false;
327 /* Clear the pcmbuf queue of messages
328 * Permissible Context(s): Thread
330 static void pcmbuf_queue_clear(void)
332 pcm_play_lock();
333 queue_clear(&pcmbuf_queue);
334 pcm_play_unlock();
337 /* --- Helper functions --- */
339 static struct mp3entry *bufgetid3(int handle_id)
341 if (handle_id < 0)
342 return NULL;
344 struct mp3entry *id3;
345 ssize_t ret = bufgetdata(handle_id, 0, (void *)&id3);
347 if (ret < 0 || ret != sizeof(struct mp3entry))
348 return NULL;
350 return id3;
353 static bool clear_track_info(struct track_info *track)
355 /* bufclose returns true if the handle is not found, or if it is closed
356 * successfully, so these checks are safe on non-existant handles */
357 if (!track)
358 return false;
360 if (track->codec_hid >= 0) {
361 if (bufclose(track->codec_hid))
362 track->codec_hid = -1;
363 else
364 return false;
367 if (track->id3_hid >= 0) {
368 if (bufclose(track->id3_hid))
369 track->id3_hid = -1;
370 else
371 return false;
374 if (track->audio_hid >= 0) {
375 if (bufclose(track->audio_hid))
376 track->audio_hid = -1;
377 else
378 return false;
381 #ifdef HAVE_ALBUMART
382 if (track->aa_hid >= 0) {
383 if (bufclose(track->aa_hid))
384 track->aa_hid = -1;
385 else
386 return false;
388 #endif
390 if (track->cuesheet_hid >= 0) {
391 if (bufclose(track->cuesheet_hid))
392 track->cuesheet_hid = -1;
393 else
394 return false;
397 track->filesize = 0;
398 track->taginfo_ready = false;
400 return true;
403 /* --- External interfaces --- */
405 /* This sends a stop message and the audio thread will dump all it's
406 subsequenct messages */
407 void audio_hard_stop(void)
409 /* Stop playback */
410 LOGFQUEUE("audio >| audio Q_AUDIO_STOP: 1");
411 queue_send(&audio_queue, Q_AUDIO_STOP, 1);
412 #ifdef PLAYBACK_VOICE
413 voice_stop();
414 #endif
417 bool audio_restore_playback(int type)
419 switch (type)
421 case AUDIO_WANT_PLAYBACK:
422 if (buffer_state != AUDIOBUF_STATE_INITIALIZED)
423 audio_reset_buffer();
424 return true;
425 case AUDIO_WANT_VOICE:
426 if (buffer_state == AUDIOBUF_STATE_TRASHED)
427 audio_reset_buffer();
428 return true;
429 default:
430 return false;
434 unsigned char *audio_get_buffer(bool talk_buf, size_t *buffer_size)
436 unsigned char *buf, *end;
438 if (audio_is_initialized)
440 audio_hard_stop();
442 /* else buffer_state will be AUDIOBUF_STATE_TRASHED at this point */
444 /* Reset the buffering thread so that it doesn't try to use the data */
445 buffering_reset(filebuf, filebuflen);
447 if (buffer_size == NULL)
449 /* Special case for talk_init to use since it already knows it's
450 trashed */
451 buffer_state = AUDIOBUF_STATE_TRASHED;
452 return NULL;
455 if (talk_buf || buffer_state == AUDIOBUF_STATE_TRASHED
456 || !talk_voice_required())
458 logf("get buffer: talk, audio");
459 /* Ok to use everything from audiobuf to audiobufend - voice is loaded,
460 the talk buffer is not needed because voice isn't being used, or
461 could be AUDIOBUF_STATE_TRASHED already. If state is
462 AUDIOBUF_STATE_VOICED_ONLY, no problem as long as memory isn't written
463 without the caller knowing what's going on. Changing certain settings
464 may move it to a worse condition but the memory in use by something
465 else will remain undisturbed.
467 if (buffer_state != AUDIOBUF_STATE_TRASHED)
469 talk_buffer_steal();
470 buffer_state = AUDIOBUF_STATE_TRASHED;
473 buf = audiobuf;
474 end = audiobufend;
476 else
478 /* Safe to just return this if already AUDIOBUF_STATE_VOICED_ONLY or
479 still AUDIOBUF_STATE_INITIALIZED */
480 /* Skip talk buffer and move pcm buffer to end to maximize available
481 contiguous memory - no audio running means voice will not need the
482 swap space */
483 logf("get buffer: audio");
484 buf = audiobuf + talk_get_bufsize();
485 end = audiobufend - pcmbuf_init(audiobufend);
486 buffer_state = AUDIOBUF_STATE_VOICED_ONLY;
489 *buffer_size = end - buf;
491 return buf;
494 int audio_buffer_state(void)
496 return buffer_state;
499 #ifdef HAVE_RECORDING
500 unsigned char *audio_get_recording_buffer(size_t *buffer_size)
502 /* Stop audio, voice and obtain all available buffer space */
503 audio_hard_stop();
504 talk_buffer_steal();
506 unsigned char *end = audiobufend;
507 buffer_state = AUDIOBUF_STATE_TRASHED;
508 *buffer_size = end - audiobuf;
510 return (unsigned char *)audiobuf;
513 bool audio_load_encoder(int afmt)
515 #ifndef SIMULATOR
516 const char *enc_fn = get_codec_filename(afmt | CODEC_TYPE_ENCODER);
517 if (!enc_fn)
518 return false;
520 audio_remove_encoder();
521 ci.enc_codec_loaded = 0; /* clear any previous error condition */
523 LOGFQUEUE("codec > Q_ENCODER_LOAD_DISK");
524 queue_post(&codec_queue, Q_ENCODER_LOAD_DISK, (intptr_t)enc_fn);
526 while (ci.enc_codec_loaded == 0)
527 yield();
529 logf("codec loaded: %d", ci.enc_codec_loaded);
531 return ci.enc_codec_loaded > 0;
532 #else
533 (void)afmt;
534 return true;
535 #endif
536 } /* audio_load_encoder */
538 void audio_remove_encoder(void)
540 #ifndef SIMULATOR
541 /* force encoder codec unload (if currently loaded) */
542 if (ci.enc_codec_loaded <= 0)
543 return;
545 ci.stop_encoder = true;
546 while (ci.enc_codec_loaded > 0)
547 yield();
548 #endif
549 } /* audio_remove_encoder */
551 #endif /* HAVE_RECORDING */
553 #ifdef HAVE_ALBUMART
554 int audio_current_aa_hid(void)
556 int cur_idx;
557 int offset = ci.new_track + wps_offset;
559 cur_idx = track_ridx + offset;
560 cur_idx &= MAX_TRACK_MASK;
562 return tracks[cur_idx].aa_hid;
564 #endif
566 struct mp3entry* audio_current_track(void)
568 const char *filename;
569 struct playlist_track_info trackinfo;
570 int cur_idx;
571 int offset = ci.new_track + wps_offset;
572 struct mp3entry *write_id3;
574 cur_idx = (track_ridx + offset) & MAX_TRACK_MASK;
576 if (cur_idx == track_ridx && *thistrack_id3->path)
578 /* The usual case */
579 if (tracks[cur_idx].cuesheet_hid >= 0 && !thistrack_id3->cuesheet)
581 bufread(tracks[cur_idx].cuesheet_hid, sizeof(struct cuesheet), curr_cue);
582 thistrack_id3->cuesheet = curr_cue;
583 cue_spoof_id3(thistrack_id3->cuesheet, thistrack_id3);
585 return thistrack_id3;
587 else if (automatic_skip && offset == -1 && *othertrack_id3->path)
589 /* We're in a track transition. The codec has moved on to the next track,
590 but the audio being played is still the same (now previous) track.
591 othertrack_id3.elapsed is being updated in an ISR by
592 codec_pcmbuf_position_callback */
593 if (tracks[cur_idx].cuesheet_hid >= 0 && !thistrack_id3->cuesheet)
595 bufread(tracks[cur_idx].cuesheet_hid, sizeof(struct cuesheet), curr_cue);
596 othertrack_id3->cuesheet = curr_cue;
597 cue_spoof_id3(othertrack_id3->cuesheet, othertrack_id3);
599 return othertrack_id3;
602 if (offset != 0)
604 /* Codec may be using thistrack_id3, so it must not be overwritten.
605 If this is a manual skip, othertrack_id3 will become
606 thistrack_id3 in audio_check_new_track().
607 FIXME: If this is an automatic skip, it probably means multiple
608 short tracks fit in the PCM buffer. Overwriting othertrack_id3
609 can lead to an incorrect value later.
610 Note that othertrack_id3 may also be used for next track.
612 write_id3 = othertrack_id3;
614 else
616 write_id3 = thistrack_id3;
619 if (tracks[cur_idx].id3_hid >= 0)
621 /* The current track's info has been buffered but not read yet, so get it */
622 if (bufread(tracks[cur_idx].id3_hid, sizeof(struct mp3entry), write_id3)
623 == sizeof(struct mp3entry))
624 return write_id3;
627 /* We didn't find the ID3 metadata, so we fill temp_id3 with the little info
628 we have and return that. */
630 memset(write_id3, 0, sizeof(struct mp3entry));
632 playlist_get_track_info(NULL, playlist_next(0)+wps_offset, &trackinfo);
633 filename = trackinfo.filename;
634 if (!filename)
635 filename = "No file!";
637 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
638 if (tagcache_fill_tags(write_id3, filename))
639 return write_id3;
640 #endif
642 strlcpy(write_id3->path, filename, sizeof(write_id3->path));
643 write_id3->title = strrchr(write_id3->path, '/');
644 if (!write_id3->title)
645 write_id3->title = &write_id3->path[0];
646 else
647 write_id3->title++;
649 return write_id3;
652 struct mp3entry* audio_next_track(void)
654 int next_idx;
655 int offset = ci.new_track + wps_offset;
657 if (!audio_have_tracks())
658 return NULL;
660 if (wps_offset == -1 && *thistrack_id3->path)
662 /* We're in a track transition. The next track for the WPS is the one
663 currently being decoded. */
664 return thistrack_id3;
667 next_idx = (track_ridx + offset + 1) & MAX_TRACK_MASK;
669 if (tracks[next_idx].id3_hid >= 0)
671 if (bufread(tracks[next_idx].id3_hid, sizeof(struct mp3entry), othertrack_id3)
672 == sizeof(struct mp3entry))
673 return othertrack_id3;
674 else
675 return NULL;
678 if (next_idx == track_widx)
680 /* The next track hasn't been buffered yet, so we return the static
681 version of its metadata. */
682 return &unbuffered_id3;
685 return NULL;
688 void audio_play(long offset)
690 logf("audio_play");
692 #ifdef PLAYBACK_VOICE
693 /* Truncate any existing voice output so we don't have spelling
694 * etc. over the first part of the played track */
695 talk_force_shutup();
696 #endif
698 /* Start playback */
699 LOGFQUEUE("audio >| audio Q_AUDIO_PLAY: %ld", offset);
700 /* Don't return until playback has actually started */
701 queue_send(&audio_queue, Q_AUDIO_PLAY, offset);
704 void audio_stop(void)
706 /* Stop playback */
707 LOGFQUEUE("audio >| audio Q_AUDIO_STOP");
708 /* Don't return until playback has actually stopped */
709 queue_send(&audio_queue, Q_AUDIO_STOP, 0);
712 void audio_pause(void)
714 LOGFQUEUE("audio >| audio Q_AUDIO_PAUSE");
715 /* Don't return until playback has actually paused */
716 queue_send(&audio_queue, Q_AUDIO_PAUSE, true);
719 void audio_resume(void)
721 LOGFQUEUE("audio >| audio Q_AUDIO_PAUSE resume");
722 /* Don't return until playback has actually resumed */
723 queue_send(&audio_queue, Q_AUDIO_PAUSE, false);
726 void audio_skip(int direction)
728 if (playlist_check(ci.new_track + wps_offset + direction))
730 if (global_settings.beep)
731 pcmbuf_beep(2000, 100, 2500*global_settings.beep);
733 LOGFQUEUE("audio > audio Q_AUDIO_SKIP %d", direction);
734 queue_post(&audio_queue, Q_AUDIO_SKIP, direction);
735 /* Update wps while our message travels inside deep playback queues. */
736 wps_offset += direction;
738 else
740 /* No more tracks. */
741 if (global_settings.beep)
742 pcmbuf_beep(1000, 100, 1500*global_settings.beep);
746 void audio_next(void)
748 audio_skip(1);
751 void audio_prev(void)
753 audio_skip(-1);
756 void audio_next_dir(void)
758 LOGFQUEUE("audio > audio Q_AUDIO_DIR_SKIP 1");
759 queue_post(&audio_queue, Q_AUDIO_DIR_SKIP, 1);
762 void audio_prev_dir(void)
764 LOGFQUEUE("audio > audio Q_AUDIO_DIR_SKIP -1");
765 queue_post(&audio_queue, Q_AUDIO_DIR_SKIP, -1);
768 void audio_pre_ff_rewind(void)
770 LOGFQUEUE("audio > audio Q_AUDIO_PRE_FF_REWIND");
771 queue_post(&audio_queue, Q_AUDIO_PRE_FF_REWIND, 0);
774 void audio_ff_rewind(long newpos)
776 LOGFQUEUE("audio > audio Q_AUDIO_FF_REWIND");
777 queue_post(&audio_queue, Q_AUDIO_FF_REWIND, newpos);
780 void audio_flush_and_reload_tracks(void)
782 LOGFQUEUE("audio > audio Q_AUDIO_FLUSH");
783 queue_post(&audio_queue, Q_AUDIO_FLUSH, 0);
786 void audio_error_clear(void)
788 #ifdef AUDIO_HAVE_RECORDING
789 pcm_rec_error_clear();
790 #endif
793 int audio_status(void)
795 int ret = 0;
797 if (playing)
798 ret |= AUDIO_STATUS_PLAY;
800 if (paused)
801 ret |= AUDIO_STATUS_PAUSE;
803 #ifdef HAVE_RECORDING
804 /* Do this here for constitency with mpeg.c version */
805 ret |= pcm_rec_status();
806 #endif
808 return ret;
811 int audio_get_file_pos(void)
813 return 0;
816 #ifdef HAVE_DISK_STORAGE
817 void audio_set_buffer_margin(int setting)
819 static const unsigned short lookup[] = {5, 15, 30, 60, 120, 180, 300, 600};
820 buffer_margin = lookup[setting];
821 logf("buffer margin: %ld", (long)buffer_margin);
822 set_filebuf_watermark();
824 #endif
826 /* Take necessary steps to enable or disable the crossfade setting */
827 void audio_set_crossfade(int enable)
829 size_t offset;
830 bool was_playing;
831 size_t size;
833 /* Tell it the next setting to use */
834 pcmbuf_crossfade_enable(enable);
836 /* Return if size hasn't changed or this is too early to determine
837 which in the second case there's no way we could be playing
838 anything at all */
839 if (pcmbuf_is_same_size())
841 /* This function is a copout and just syncs some variables -
842 to be removed at a later date */
843 pcmbuf_crossfade_enable_finished();
844 return;
847 offset = 0;
848 was_playing = playing;
850 /* Playback has to be stopped before changing the buffer size */
851 if (was_playing)
853 /* Store the track resume position */
854 offset = thistrack_id3->offset;
857 /* Blast it - audio buffer will have to be setup again next time
858 something plays */
859 audio_get_buffer(true, &size);
861 /* Restart playback if audio was running previously */
862 if (was_playing)
863 audio_play(offset);
866 /* --- Routines called from multiple threads --- */
868 static void set_filebuf_watermark(void)
870 if (!filebuf)
871 return; /* Audio buffers not yet set up */
873 #ifdef HAVE_DISK_STORAGE
874 int seconds;
875 int spinup = ata_spinup_time();
876 if (spinup)
877 seconds = (spinup / HZ) + 1;
878 else
879 seconds = 5;
881 seconds += buffer_margin;
882 #else
883 /* flash storage */
884 int seconds = 1;
885 #endif
887 /* bitrate of last track in buffer dictates watermark */
888 struct mp3entry* id3 = NULL;
889 if (tracks[track_widx].taginfo_ready)
890 id3 = bufgetid3(tracks[track_widx].id3_hid);
891 else
892 id3 = bufgetid3(tracks[track_widx-1].id3_hid);
893 if (!id3) {
894 logf("fwmark: No id3 for last track (r%d/w%d), aborting!", track_ridx, track_widx);
895 return;
897 size_t bytes = id3->bitrate * (1000/8) * seconds;
898 buf_set_watermark(bytes);
899 logf("fwmark: %d", bytes);
902 const char *get_codec_filename(int cod_spec)
904 const char *fname;
906 #ifdef HAVE_RECORDING
907 /* Can choose decoder or encoder if one available */
908 int type = cod_spec & CODEC_TYPE_MASK;
909 int afmt = cod_spec & CODEC_AFMT_MASK;
911 if ((unsigned)afmt >= AFMT_NUM_CODECS)
912 type = AFMT_UNKNOWN | (type & CODEC_TYPE_MASK);
914 fname = (type == CODEC_TYPE_ENCODER) ?
915 audio_formats[afmt].codec_enc_root_fn :
916 audio_formats[afmt].codec_root_fn;
918 logf("%s: %d - %s",
919 (type == CODEC_TYPE_ENCODER) ? "Encoder" : "Decoder",
920 afmt, fname ? fname : "<unknown>");
921 #else /* !HAVE_RECORDING */
922 /* Always decoder */
923 if ((unsigned)cod_spec >= AFMT_NUM_CODECS)
924 cod_spec = AFMT_UNKNOWN;
925 fname = audio_formats[cod_spec].codec_root_fn;
926 logf("Codec: %d - %s", cod_spec, fname ? fname : "<unknown>");
927 #endif /* HAVE_RECORDING */
929 return fname;
930 } /* get_codec_filename */
932 /* --- Codec thread --- */
933 static bool codec_pcmbuf_insert_callback(
934 const void *ch1, const void *ch2, int count)
936 const char *src[2] = { ch1, ch2 };
938 while (count > 0)
940 int out_count = dsp_output_count(ci.dsp, count);
941 int inp_count;
942 char *dest;
944 /* Prevent audio from a previous track from playing */
945 if (ci.new_track || ci.stop_codec)
946 return true;
948 while ((dest = pcmbuf_request_buffer(&out_count)) == NULL)
950 cancel_cpu_boost();
951 sleep(1);
952 if (ci.seek_time || ci.new_track || ci.stop_codec)
953 return true;
956 /* Get the real input_size for output_size bytes, guarding
957 * against resampling buffer overflows. */
958 inp_count = dsp_input_count(ci.dsp, out_count);
960 if (inp_count <= 0)
961 return true;
963 /* Input size has grown, no error, just don't write more than length */
964 if (inp_count > count)
965 inp_count = count;
967 out_count = dsp_process(ci.dsp, dest, src, inp_count);
969 if (out_count <= 0)
970 return true;
972 pcmbuf_write_complete(out_count);
974 count -= inp_count;
977 return true;
978 } /* codec_pcmbuf_insert_callback */
980 static void* codec_get_buffer(size_t *size)
982 if (codec_size >= CODEC_SIZE)
983 return NULL;
984 *size = CODEC_SIZE - codec_size;
985 return &codecbuf[codec_size];
988 /* Between the codec and PCM track change, we need to keep updating the
989 "elapsed" value of the previous (to the codec, but current to the
990 user/PCM/WPS) track, so that the progressbar reaches the end.
991 During that transition, the WPS will display prevtrack_id3. */
992 static void codec_pcmbuf_position_callback(size_t size) ICODE_ATTR;
993 static void codec_pcmbuf_position_callback(size_t size)
995 /* This is called from an ISR, so be quick */
996 unsigned int time = size * 1000 / 4 / NATIVE_FREQUENCY +
997 othertrack_id3->elapsed;
999 if (time >= othertrack_id3->length)
1001 pcmbuf_set_position_callback(NULL);
1002 othertrack_id3->elapsed = othertrack_id3->length;
1004 else
1005 othertrack_id3->elapsed = time;
1008 static void codec_set_elapsed_callback(unsigned int value)
1010 unsigned int latency;
1011 if (ci.seek_time)
1012 return;
1014 #ifdef AB_REPEAT_ENABLE
1015 ab_position_report(value);
1016 #endif
1018 latency = pcmbuf_get_latency();
1019 if (value < latency)
1020 thistrack_id3->elapsed = 0;
1021 else if (value - latency > thistrack_id3->elapsed ||
1022 value - latency < thistrack_id3->elapsed - 2)
1024 thistrack_id3->elapsed = value - latency;
1028 static void codec_set_offset_callback(size_t value)
1030 unsigned int latency;
1032 if (ci.seek_time)
1033 return;
1035 latency = pcmbuf_get_latency() * thistrack_id3->bitrate / 8;
1036 if (value < latency)
1037 thistrack_id3->offset = 0;
1038 else
1039 thistrack_id3->offset = value - latency;
1042 static void codec_advance_buffer_counters(size_t amount)
1044 bufadvance(CUR_TI->audio_hid, amount);
1045 ci.curpos += amount;
1048 /* copy up-to size bytes into ptr and return the actual size copied */
1049 static size_t codec_filebuf_callback(void *ptr, size_t size)
1051 ssize_t copy_n;
1053 if (ci.stop_codec || !playing)
1054 return 0;
1056 copy_n = bufread(CUR_TI->audio_hid, size, ptr);
1058 /* Nothing requested OR nothing left */
1059 if (copy_n == 0)
1060 return 0;
1062 /* Update read and other position pointers */
1063 codec_advance_buffer_counters(copy_n);
1065 /* Return the actual amount of data copied to the buffer */
1066 return copy_n;
1067 } /* codec_filebuf_callback */
1069 static void* codec_request_buffer_callback(size_t *realsize, size_t reqsize)
1071 size_t copy_n = reqsize;
1072 ssize_t ret;
1073 void *ptr;
1075 if (!playing)
1077 *realsize = 0;
1078 return NULL;
1081 ret = bufgetdata(CUR_TI->audio_hid, reqsize, &ptr);
1082 if (ret >= 0)
1083 copy_n = MIN((size_t)ret, reqsize);
1085 if (copy_n == 0)
1087 *realsize = 0;
1088 return NULL;
1091 *realsize = copy_n;
1093 return ptr;
1094 } /* codec_request_buffer_callback */
1096 static int get_codec_base_type(int type)
1098 switch (type) {
1099 case AFMT_MPA_L1:
1100 case AFMT_MPA_L2:
1101 case AFMT_MPA_L3:
1102 return AFMT_MPA_L3;
1105 return type;
1108 static void codec_advance_buffer_callback(size_t amount)
1110 codec_advance_buffer_counters(amount);
1111 codec_set_offset_callback(ci.curpos);
1114 static void codec_advance_buffer_loc_callback(void *ptr)
1116 size_t amount = buf_get_offset(CUR_TI->audio_hid, ptr);
1117 codec_advance_buffer_callback(amount);
1120 static void codec_seek_complete_callback(void)
1122 logf("seek_complete");
1123 /* If seeking-while-playing, pcm playback is actually paused (pcm_is_paused())
1124 * but the paused flag is not set. If seeking-while-paused, the (paused) flag is
1125 * set, but pcm playback may have actually stopped due to a previous buffer clear.
1126 * The buffer clear below occurs with either condition. A seemless seek skips
1127 * this section and no buffer clear occurs.
1129 if (pcm_is_paused() || paused)
1131 /* Clear the buffer */
1132 pcmbuf_play_stop();
1133 dsp_configure(ci.dsp, DSP_FLUSH, 0);
1135 /* If seeking-while-playing, resume pcm playback */
1136 if (!paused)
1137 pcmbuf_pause(false);
1139 ci.seek_time = 0;
1142 static bool codec_seek_buffer_callback(size_t newpos)
1144 logf("codec_seek_buffer_callback");
1146 int ret = bufseek(CUR_TI->audio_hid, newpos);
1147 if (ret == 0) {
1148 ci.curpos = newpos;
1149 return true;
1151 else {
1152 return false;
1156 static void codec_configure_callback(int setting, intptr_t value)
1158 switch (setting) {
1159 default:
1160 if (!dsp_configure(ci.dsp, setting, value))
1161 { logf("Illegal key:%d", setting); }
1165 static void codec_track_changed(void)
1167 LOGFQUEUE("codec > audio Q_AUDIO_TRACK_CHANGED");
1168 queue_post(&audio_queue, Q_AUDIO_TRACK_CHANGED, 0);
1171 static void codec_pcmbuf_track_changed_callback(void)
1173 pcmbuf_set_position_callback(NULL);
1174 pcmbuf_callback_queue_post(Q_AUDIO_TRACK_CHANGED, 0);
1177 static void codec_discard_codec_callback(void)
1179 if (CUR_TI->codec_hid >= 0)
1181 bufclose(CUR_TI->codec_hid);
1182 CUR_TI->codec_hid = -1;
1186 static inline void codec_gapless_track_change(void)
1188 /* callback keeps the progress bar moving while the pcmbuf empties */
1189 pcmbuf_set_position_callback(codec_pcmbuf_position_callback);
1190 /* set the pcmbuf callback for when the track really changes */
1191 pcmbuf_set_event_handler(codec_pcmbuf_track_changed_callback);
1194 static inline void codec_crossfade_track_change(void)
1196 /* Initiate automatic crossfade mode */
1197 pcmbuf_crossfade_init(false);
1198 /* Notify the wps that the track change starts now */
1199 codec_track_changed();
1202 static void codec_track_skip_done(bool was_manual)
1204 /* Manual track change (always crossfade or flush audio). */
1205 if (was_manual)
1207 pcmbuf_crossfade_init(true);
1208 LOGFQUEUE("codec > audio Q_AUDIO_TRACK_CHANGED");
1209 queue_post(&audio_queue, Q_AUDIO_TRACK_CHANGED, 0);
1211 /* Automatic track change w/crossfade, if not in "Track Skip Only" mode. */
1212 else if (pcmbuf_is_crossfade_enabled() && !pcmbuf_is_crossfade_active()
1213 && global_settings.crossfade != CROSSFADE_ENABLE_TRACKSKIP)
1215 if (global_settings.crossfade == CROSSFADE_ENABLE_SHUFFLE_AND_TRACKSKIP)
1217 if (global_settings.playlist_shuffle)
1218 /* shuffle mode is on, so crossfade: */
1219 codec_crossfade_track_change();
1220 else
1221 /* shuffle mode is off, so do a gapless track change */
1222 codec_gapless_track_change();
1224 else
1225 /* normal crossfade: */
1226 codec_crossfade_track_change();
1228 else
1229 /* normal gapless playback. */
1230 codec_gapless_track_change();
1233 static bool codec_load_next_track(void)
1235 intptr_t result = Q_CODEC_REQUEST_FAILED;
1237 prev_track_elapsed = thistrack_id3->elapsed;
1239 #ifdef AB_REPEAT_ENABLE
1240 ab_end_of_track_report();
1241 #endif
1243 logf("Request new track");
1245 if (ci.new_track == 0)
1247 ci.new_track++;
1248 automatic_skip = true;
1251 if (!ci.stop_codec)
1253 trigger_cpu_boost();
1254 LOGFQUEUE("codec >| audio Q_AUDIO_CHECK_NEW_TRACK");
1255 result = queue_send(&audio_queue, Q_AUDIO_CHECK_NEW_TRACK, 0);
1258 switch (result)
1260 case Q_CODEC_REQUEST_COMPLETE:
1261 LOGFQUEUE("codec |< Q_CODEC_REQUEST_COMPLETE");
1262 codec_track_skip_done(!automatic_skip);
1263 return true;
1265 case Q_CODEC_REQUEST_FAILED:
1266 LOGFQUEUE("codec |< Q_CODEC_REQUEST_FAILED");
1267 ci.new_track = 0;
1268 ci.stop_codec = true;
1269 codec_requested_stop = true;
1270 return false;
1272 default:
1273 LOGFQUEUE("codec |< default");
1274 ci.stop_codec = true;
1275 codec_requested_stop = true;
1276 return false;
1280 static bool codec_request_next_track_callback(void)
1282 int prev_codectype;
1284 if (ci.stop_codec || !playing)
1285 return false;
1287 prev_codectype = get_codec_base_type(thistrack_id3->codectype);
1288 if (!codec_load_next_track())
1289 return false;
1291 /* Seek to the beginning of the new track because if the struct
1292 mp3entry was buffered, "elapsed" might not be zero (if the track has
1293 been played already but not unbuffered) */
1294 codec_seek_buffer_callback(thistrack_id3->first_frame_offset);
1295 /* Check if the next codec is the same file. */
1296 if (prev_codectype == get_codec_base_type(thistrack_id3->codectype))
1298 logf("New track loaded");
1299 codec_discard_codec_callback();
1300 return true;
1302 else
1304 logf("New codec:%d/%d", thistrack_id3->codectype, prev_codectype);
1305 return false;
1309 static void codec_thread(void)
1311 struct queue_event ev;
1312 int status;
1314 while (1) {
1315 status = 0;
1317 if (!pcmbuf_is_crossfade_active()) {
1318 cancel_cpu_boost();
1321 queue_wait(&codec_queue, &ev);
1322 codec_requested_stop = false;
1324 switch (ev.id) {
1325 case Q_CODEC_LOAD_DISK:
1326 LOGFQUEUE("codec < Q_CODEC_LOAD_DISK");
1327 queue_reply(&codec_queue, 1);
1328 audio_codec_loaded = true;
1329 ci.stop_codec = false;
1330 status = codec_load_file((const char *)ev.data, &ci);
1331 LOGFQUEUE("codec_load_file %s %d\n", (const char *)ev.data, status);
1332 break;
1334 case Q_CODEC_LOAD:
1335 LOGFQUEUE("codec < Q_CODEC_LOAD");
1336 if (CUR_TI->codec_hid < 0) {
1337 logf("Codec slot is empty!");
1338 /* Wait for the pcm buffer to go empty */
1339 while (pcm_is_playing())
1340 yield();
1341 /* This must be set to prevent an infinite loop */
1342 ci.stop_codec = true;
1343 LOGFQUEUE("codec > codec Q_AUDIO_PLAY");
1344 queue_post(&codec_queue, Q_AUDIO_PLAY, 0);
1345 break;
1348 audio_codec_loaded = true;
1349 ci.stop_codec = false;
1350 status = codec_load_buf(CUR_TI->codec_hid, &ci);
1351 LOGFQUEUE("codec_load_buf %d\n", status);
1352 break;
1354 case Q_CODEC_DO_CALLBACK:
1355 LOGFQUEUE("codec < Q_CODEC_DO_CALLBACK");
1356 queue_reply(&codec_queue, 1);
1357 if ((void*)ev.data != NULL)
1359 cpucache_invalidate();
1360 ((void (*)(void))ev.data)();
1361 cpucache_flush();
1363 break;
1365 #ifdef AUDIO_HAVE_RECORDING
1366 case Q_ENCODER_LOAD_DISK:
1367 LOGFQUEUE("codec < Q_ENCODER_LOAD_DISK");
1368 audio_codec_loaded = false; /* Not audio codec! */
1369 logf("loading encoder");
1370 ci.stop_encoder = false;
1371 status = codec_load_file((const char *)ev.data, &ci);
1372 logf("encoder stopped");
1373 break;
1374 #endif /* AUDIO_HAVE_RECORDING */
1376 default:
1377 LOGFQUEUE("codec < default");
1380 if (audio_codec_loaded)
1382 if (ci.stop_codec)
1384 status = CODEC_OK;
1385 if (!playing)
1386 pcmbuf_play_stop();
1389 audio_codec_loaded = false;
1392 switch (ev.id) {
1393 case Q_CODEC_LOAD_DISK:
1394 case Q_CODEC_LOAD:
1395 LOGFQUEUE("codec < Q_CODEC_LOAD");
1396 if (playing)
1398 if (ci.new_track || status != CODEC_OK)
1400 if (!ci.new_track)
1402 logf("Codec failure, %d %d", ci.new_track, status);
1403 splash(HZ*2, "Codec failure");
1406 if (!codec_load_next_track())
1408 LOGFQUEUE("codec > audio Q_AUDIO_STOP");
1409 /* End of playlist */
1410 queue_post(&audio_queue, Q_AUDIO_STOP, 0);
1411 break;
1414 else
1416 logf("Codec finished");
1417 if (ci.stop_codec)
1419 /* Wait for the audio to stop playing before
1420 * triggering the WPS exit */
1421 while(pcm_is_playing())
1423 /* There has been one too many struct pointer swaps by now
1424 * so even though it says othertrack_id3, its the correct one! */
1425 othertrack_id3->elapsed =
1426 othertrack_id3->length - pcmbuf_get_latency();
1427 sleep(1);
1430 if (codec_requested_stop)
1432 LOGFQUEUE("codec > audio Q_AUDIO_STOP");
1433 queue_post(&audio_queue, Q_AUDIO_STOP, 0);
1435 break;
1439 if (CUR_TI->codec_hid >= 0)
1441 LOGFQUEUE("codec > codec Q_CODEC_LOAD");
1442 queue_post(&codec_queue, Q_CODEC_LOAD, 0);
1444 else
1446 const char *codec_fn =
1447 get_codec_filename(thistrack_id3->codectype);
1448 if (codec_fn)
1450 LOGFQUEUE("codec > codec Q_CODEC_LOAD_DISK");
1451 queue_post(&codec_queue, Q_CODEC_LOAD_DISK,
1452 (intptr_t)codec_fn);
1456 break;
1458 #ifdef AUDIO_HAVE_RECORDING
1459 case Q_ENCODER_LOAD_DISK:
1460 LOGFQUEUE("codec < Q_ENCODER_LOAD_DISK");
1462 if (status == CODEC_OK)
1463 break;
1465 logf("Encoder failure");
1466 splash(HZ*2, "Encoder failure");
1468 if (ci.enc_codec_loaded < 0)
1469 break;
1471 logf("Encoder failed to load");
1472 ci.enc_codec_loaded = -1;
1473 break;
1474 #endif /* AUDIO_HAVE_RECORDING */
1476 default:
1477 LOGFQUEUE("codec < default");
1479 } /* end switch */
1483 /* Borrow the codec thread and return the ID */
1484 void codec_thread_do_callback(void (*fn)(void), unsigned int *id)
1486 /* Set id before telling thread to call something; it may be
1487 * needed before this function returns. */
1488 if (id != NULL)
1489 *id = codec_thread_id;
1491 /* Codec thread will signal just before entering callback */
1492 LOGFQUEUE("codec >| Q_CODEC_DO_CALLBACK");
1493 queue_send(&codec_queue, Q_CODEC_DO_CALLBACK, (intptr_t)fn);
1496 /* --- Buffering callbacks --- */
1498 static void buffering_low_buffer_callback(void *data)
1500 (void)data;
1501 logf("low buffer callback");
1503 if (filling == STATE_FULL || filling == STATE_END_OF_PLAYLIST) {
1504 /* force a refill */
1505 LOGFQUEUE("buffering > audio Q_AUDIO_FILL_BUFFER");
1506 queue_post(&audio_queue, Q_AUDIO_FILL_BUFFER, 0);
1510 static void buffering_handle_rebuffer_callback(void *data)
1512 (void)data;
1513 LOGFQUEUE("audio >| audio Q_AUDIO_FLUSH");
1514 queue_post(&audio_queue, Q_AUDIO_FLUSH, 0);
1517 static void buffering_handle_finished_callback(int *data)
1519 logf("handle %d finished buffering", *data);
1521 if (*data == tracks[track_widx].id3_hid)
1523 int offset = ci.new_track + wps_offset;
1524 int next_idx = (track_ridx + offset + 1) & MAX_TRACK_MASK;
1525 /* The metadata handle for the last loaded track has been buffered.
1526 We can ask the audio thread to load the rest of the track's data. */
1527 LOGFQUEUE("audio >| audio Q_AUDIO_FINISH_LOAD");
1528 queue_post(&audio_queue, Q_AUDIO_FINISH_LOAD, 0);
1529 if (tracks[next_idx].id3_hid == *data)
1530 send_event(PLAYBACK_EVENT_NEXTTRACKID3_AVAILABLE, NULL);
1532 else
1534 /* This is most likely an audio handle, so we strip the useless
1535 trailing tags that are left. */
1536 strip_tags(*data);
1538 if (*data == tracks[track_widx-1].audio_hid
1539 && filling == STATE_END_OF_PLAYLIST)
1541 /* This was the last track in the playlist.
1542 We now have all the data we need. */
1543 logf("last track finished buffering");
1544 filling = STATE_FINISHED;
1550 /* --- Audio thread --- */
1552 static bool audio_have_tracks(void)
1554 return (audio_track_count() != 0);
1557 static int audio_free_track_count(void)
1559 /* Used tracks + free tracks adds up to MAX_TRACK - 1 */
1560 return MAX_TRACK - 1 - audio_track_count();
1563 int audio_track_count(void)
1565 /* Calculate difference from track_ridx to track_widx
1566 * taking into account a possible wrap-around. */
1567 return (MAX_TRACK + track_widx - track_ridx) & MAX_TRACK_MASK;
1570 long audio_filebufused(void)
1572 return (long) buf_used();
1575 /* Update track info after successful a codec track change */
1576 static void audio_update_trackinfo(void)
1578 /* Load the curent track's metadata into curtrack_id3 */
1579 if (CUR_TI->id3_hid >= 0)
1580 copy_mp3entry(thistrack_id3, bufgetid3(CUR_TI->id3_hid));
1582 /* Reset current position */
1583 thistrack_id3->elapsed = 0;
1584 thistrack_id3->offset = 0;
1586 /* Update the codec API */
1587 ci.filesize = CUR_TI->filesize;
1588 ci.id3 = thistrack_id3;
1589 ci.curpos = 0;
1590 ci.taginfo_ready = &CUR_TI->taginfo_ready;
1593 /* Clear tracks between write and read, non inclusive */
1594 static void audio_clear_track_entries(void)
1596 int cur_idx = track_widx;
1598 logf("Clearing tracks:%d/%d", track_ridx, track_widx);
1600 /* Loop over all tracks from write-to-read */
1601 while (1)
1603 cur_idx = (cur_idx + 1) & MAX_TRACK_MASK;
1605 if (cur_idx == track_ridx)
1606 break;
1608 clear_track_info(&tracks[cur_idx]);
1612 /* Clear all tracks */
1613 static bool audio_release_tracks(void)
1615 int i, cur_idx;
1617 logf("releasing all tracks");
1619 for(i = 0; i < MAX_TRACK; i++)
1621 cur_idx = (track_ridx + i) & MAX_TRACK_MASK;
1622 if (!clear_track_info(&tracks[cur_idx]))
1623 return false;
1626 return true;
1629 static bool audio_loadcodec(bool start_play)
1631 int prev_track;
1632 char codec_path[MAX_PATH]; /* Full path to codec */
1633 const struct mp3entry *id3, *prev_id3;
1635 if (tracks[track_widx].id3_hid < 0) {
1636 return false;
1639 id3 = bufgetid3(tracks[track_widx].id3_hid);
1640 if (!id3)
1641 return false;
1643 const char *codec_fn = get_codec_filename(id3->codectype);
1644 if (codec_fn == NULL)
1645 return false;
1647 tracks[track_widx].codec_hid = -1;
1649 if (start_play)
1651 /* Load the codec directly from disk and save some memory. */
1652 track_ridx = track_widx;
1653 ci.filesize = CUR_TI->filesize;
1654 ci.id3 = thistrack_id3;
1655 ci.taginfo_ready = &CUR_TI->taginfo_ready;
1656 ci.curpos = 0;
1657 LOGFQUEUE("codec > codec Q_CODEC_LOAD_DISK");
1658 queue_post(&codec_queue, Q_CODEC_LOAD_DISK, (intptr_t)codec_fn);
1659 return true;
1661 else
1663 /* If we already have another track than this one buffered */
1664 if (track_widx != track_ridx)
1666 prev_track = (track_widx - 1) & MAX_TRACK_MASK;
1668 id3 = bufgetid3(tracks[track_widx].id3_hid);
1669 prev_id3 = bufgetid3(tracks[prev_track].id3_hid);
1671 /* If the previous codec is the same as this one, there is no need
1672 * to put another copy of it on the file buffer */
1673 if (id3 && prev_id3 &&
1674 get_codec_base_type(id3->codectype) ==
1675 get_codec_base_type(prev_id3->codectype)
1676 && audio_codec_loaded)
1678 logf("Reusing prev. codec");
1679 return true;
1684 codec_get_full_path(codec_path, codec_fn);
1686 tracks[track_widx].codec_hid = bufopen(codec_path, 0, TYPE_CODEC);
1687 if (tracks[track_widx].codec_hid < 0)
1688 return false;
1690 logf("Loaded codec");
1692 return true;
1695 /* Load metadata for the next track (with bufopen). The rest of the track
1696 loading will be handled by audio_finish_load_track once the metadata has been
1697 actually loaded by the buffering thread. */
1698 static bool audio_load_track(size_t offset, bool start_play)
1700 const char *trackname;
1701 int fd = -1;
1703 if (track_load_started) {
1704 /* There is already a track load in progress, so track_widx hasn't been
1705 incremented yet. Loading another track would overwrite the one that
1706 hasn't finished loading. */
1707 logf("audio_load_track(): a track load is already in progress");
1708 return false;
1711 start_play_g = start_play; /* will be read by audio_finish_load_track */
1713 /* Stop buffer filling if there is no free track entries.
1714 Don't fill up the last track entry (we wan't to store next track
1715 metadata there). */
1716 if (!audio_free_track_count())
1718 logf("No free tracks");
1719 return false;
1722 last_peek_offset++;
1723 tracks[track_widx].taginfo_ready = false;
1725 logf("Buffering track:%d/%d", track_widx, track_ridx);
1726 /* Get track name from current playlist read position. */
1727 while ((trackname = playlist_peek(last_peek_offset)) != NULL)
1729 /* Handle broken playlists. */
1730 fd = open(trackname, O_RDONLY);
1731 if (fd < 0)
1733 logf("Open failed");
1734 /* Skip invalid entry from playlist. */
1735 playlist_skip_entry(NULL, last_peek_offset);
1737 else
1738 break;
1741 if (!trackname)
1743 logf("End-of-playlist");
1744 memset(&unbuffered_id3, 0, sizeof(struct mp3entry));
1745 filling = STATE_END_OF_PLAYLIST;
1747 if (thistrack_id3->length == 0 && thistrack_id3->filesize == 0)
1749 /* Stop playback if no valid track was found. */
1750 audio_stop_playback();
1753 return false;
1756 tracks[track_widx].filesize = filesize(fd);
1758 if (offset > tracks[track_widx].filesize)
1759 offset = 0;
1761 /* Set default values */
1762 if (start_play)
1764 buf_set_watermark(filebuflen/2);
1765 dsp_configure(ci.dsp, DSP_RESET, 0);
1766 playlist_update_resume_info(audio_current_track());
1769 /* Get track metadata if we don't already have it. */
1770 if (tracks[track_widx].id3_hid < 0)
1772 tracks[track_widx].id3_hid = bufopen(trackname, 0, TYPE_ID3);
1774 if (tracks[track_widx].id3_hid < 0)
1776 /* Buffer is full. */
1777 get_metadata(&unbuffered_id3, fd, trackname);
1778 last_peek_offset--;
1779 close(fd);
1780 logf("buffer is full for now");
1781 filling = STATE_FULL;
1782 return false;
1785 if (track_widx == track_ridx)
1787 /* TODO: Superfluos buffering call? */
1788 buf_request_buffer_handle(tracks[track_widx].id3_hid);
1789 struct mp3entry *id3 = bufgetid3(tracks[track_widx].id3_hid);
1790 if (id3)
1792 copy_mp3entry(thistrack_id3, id3);
1793 thistrack_id3->offset = offset;
1795 else
1796 memset(thistrack_id3, 0, sizeof(struct mp3entry));
1799 if (start_play)
1801 playlist_update_resume_info(audio_current_track());
1805 close(fd);
1806 track_load_started = true; /* Remember that we've started loading a track */
1807 return true;
1810 /* Second part of the track loading: We now have the metadata available, so we
1811 can load the codec, the album art and finally the audio data.
1812 This is called on the audio thread after the buffering thread calls the
1813 buffering_handle_finished_callback callback. */
1814 static void audio_finish_load_track(void)
1816 size_t file_offset = 0;
1817 size_t offset = 0;
1818 bool start_play = start_play_g;
1820 track_load_started = false;
1822 if (tracks[track_widx].id3_hid < 0) {
1823 logf("no metatdata");
1824 return;
1827 struct mp3entry *track_id3;
1829 if (track_widx == track_ridx)
1830 track_id3 = thistrack_id3;
1831 else
1832 track_id3 = bufgetid3(tracks[track_widx].id3_hid);
1834 if (track_id3->length == 0 && track_id3->filesize == 0)
1836 logf("audio_finish_load_track: invalid metadata");
1838 /* Invalid metadata */
1839 bufclose(tracks[track_widx].id3_hid);
1840 tracks[track_widx].id3_hid = -1;
1842 /* Skip invalid entry from playlist. */
1843 playlist_skip_entry(NULL, last_peek_offset--);
1845 /* load next track */
1846 LOGFQUEUE("audio > audio Q_AUDIO_FILL_BUFFER %d", (int)start_play);
1847 queue_post(&audio_queue, Q_AUDIO_FILL_BUFFER, start_play);
1849 return;
1851 /* Try to load a cuesheet for the track */
1852 if (curr_cue)
1854 char cuepath[MAX_PATH];
1855 if (look_for_cuesheet_file(track_id3->path, cuepath))
1857 void *temp;
1858 tracks[track_widx].cuesheet_hid =
1859 bufalloc(NULL, sizeof(struct cuesheet), TYPE_CUESHEET);
1860 if (tracks[track_widx].cuesheet_hid >= 0)
1862 bufgetdata(tracks[track_widx].cuesheet_hid,
1863 sizeof(struct cuesheet), &temp);
1864 struct cuesheet *cuesheet = (struct cuesheet*)temp;
1865 if (!parse_cuesheet(cuepath, cuesheet))
1867 bufclose(tracks[track_widx].cuesheet_hid);
1868 track_id3->cuesheet = NULL;
1873 #ifdef HAVE_ALBUMART
1874 if (tracks[track_widx].aa_hid < 0)
1876 char aa_path[MAX_PATH];
1877 /* find_albumart will error out if the wps doesn't have AA */
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;