Correct spelling and add a couple translations
[kugel-rb/myfork.git] / apps / playback.c
blob11f76d4db86094e7aa675e2e2c1beff25cb5dbb6
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 "talk.h"
81 #include "pcm_record.h"
82 #endif
84 #ifdef IPOD_ACCESSORY_PROTOCOL
85 #include "iap.h"
86 #endif
88 #define PLAYBACK_VOICE
90 /* amount of guess-space to allow for codecs that must hunt and peck
91 * for their correct seeek target, 32k seems a good size */
92 #define AUDIO_REBUFFER_GUESS_SIZE (1024*32)
94 /* Define LOGF_ENABLE to enable logf output in this file */
95 /*#define LOGF_ENABLE*/
96 #include "logf.h"
98 /* macros to enable logf for queues
99 logging on SYS_TIMEOUT can be disabled */
100 #ifdef SIMULATOR
101 /* Define this for logf output of all queuing except SYS_TIMEOUT */
102 #define PLAYBACK_LOGQUEUES
103 /* Define this to logf SYS_TIMEOUT messages */
104 /*#define PLAYBACK_LOGQUEUES_SYS_TIMEOUT*/
105 #endif
107 #ifdef PLAYBACK_LOGQUEUES
108 #define LOGFQUEUE logf
109 #else
110 #define LOGFQUEUE(...)
111 #endif
113 #ifdef PLAYBACK_LOGQUEUES_SYS_TIMEOUT
114 #define LOGFQUEUE_SYS_TIMEOUT logf
115 #else
116 #define LOGFQUEUE_SYS_TIMEOUT(...)
117 #endif
120 /* Define one constant that includes recording related functionality */
121 #if defined(HAVE_RECORDING) && !defined(SIMULATOR)
122 #define AUDIO_HAVE_RECORDING
123 #endif
125 enum {
126 Q_NULL = 0,
127 Q_AUDIO_PLAY = 1,
128 Q_AUDIO_STOP,
129 Q_AUDIO_PAUSE,
130 Q_AUDIO_SKIP,
131 Q_AUDIO_PRE_FF_REWIND,
132 Q_AUDIO_FF_REWIND,
133 Q_AUDIO_CHECK_NEW_TRACK,
134 Q_AUDIO_FLUSH,
135 Q_AUDIO_TRACK_CHANGED,
136 Q_AUDIO_DIR_SKIP,
137 Q_AUDIO_POSTINIT,
138 Q_AUDIO_FILL_BUFFER,
139 Q_AUDIO_FINISH_LOAD,
140 Q_CODEC_REQUEST_COMPLETE,
141 Q_CODEC_REQUEST_FAILED,
143 Q_CODEC_LOAD,
144 Q_CODEC_LOAD_DISK,
146 #ifdef AUDIO_HAVE_RECORDING
147 Q_ENCODER_LOAD_DISK,
148 Q_ENCODER_RECORD,
149 #endif
151 Q_CODEC_DO_CALLBACK,
154 enum filling_state {
155 STATE_IDLE, /* audio is stopped: nothing to do */
156 STATE_FILLING, /* adding tracks to the buffer */
157 STATE_FULL, /* can't add any more tracks */
158 STATE_END_OF_PLAYLIST, /* all remaining tracks have been added */
159 STATE_FINISHED, /* all remaining tracks are fully buffered */
162 #define MAX_TRACK 128
164 #define MAX_TRACK_MASK (MAX_TRACK-1)
166 /* As defined in plugins/lib/xxx2wav.h */
167 #define GUARD_BUFSIZE (32*1024)
169 /* As defined in plugin.lds */
170 #if defined(CPU_PP)
171 #define CODEC_IRAM_ORIGIN ((unsigned char *)0x4000c000)
172 #define CODEC_IRAM_SIZE ((size_t)0xc000)
173 #elif defined(IAUDIO_X5) || defined(IAUDIO_M5)
174 #define CODEC_IRAM_ORIGIN ((unsigned char *)0x10010000)
175 #define CODEC_IRAM_SIZE ((size_t)0x10000)
176 #else
177 #define CODEC_IRAM_ORIGIN ((unsigned char *)0x1000c000)
178 #define CODEC_IRAM_SIZE ((size_t)0xc000)
179 #endif
181 bool audio_is_initialized = false;
182 static bool audio_thread_ready SHAREDBSS_ATTR = false;
184 /* Variables are commented with the threads that use them: *
185 * A=audio, C=codec, V=voice. A suffix of - indicates that *
186 * the variable is read but not updated on that thread. */
187 /* TBD: Split out "audio" and "playback" (ie. calling) threads */
189 /* Main state control */
190 static volatile bool audio_codec_loaded SHAREDBSS_ATTR = false; /* Codec loaded? (C/A-) */
191 static volatile bool playing SHAREDBSS_ATTR = false; /* Is audio playing? (A) */
192 static volatile bool paused SHAREDBSS_ATTR = false; /* Is audio paused? (A/C-) */
194 /* Ring buffer where compressed audio and codecs are loaded */
195 static unsigned char *filebuf = NULL; /* Start of buffer (A/C-) */
196 static unsigned char *malloc_buf = NULL; /* Start of malloc buffer (A/C-) */
197 /* FIXME: make filebuflen static */
198 size_t filebuflen = 0; /* Size of buffer (A/C-) */
199 /* FIXME: make buf_ridx (C/A-) */
201 /* Possible arrangements of the buffer */
202 static int buffer_state = AUDIOBUF_STATE_TRASHED; /* Buffer state */
204 /* Used to keep the WPS up-to-date during track transtition */
205 static struct mp3entry prevtrack_id3;
207 /* Used to provide the codec with a pointer */
208 static struct mp3entry curtrack_id3;
210 /* Used to make next track info available while playing last track on buffer */
211 static struct mp3entry lasttrack_id3;
213 /* Track info structure about songs in the file buffer (A/C-) */
214 struct track_info {
215 int audio_hid; /* The ID for the track's buffer handle */
216 int id3_hid; /* The ID for the track's metadata handle */
217 int codec_hid; /* The ID for the track's codec handle */
218 #ifdef HAVE_ALBUMART
219 int aa_hid; /* The ID for the track's album art handle */
220 #endif
222 size_t filesize; /* File total length */
224 bool taginfo_ready; /* Is metadata read */
227 static struct track_info tracks[MAX_TRACK];
228 static volatile int track_ridx = 0; /* Track being decoded (A/C-) */
229 static int track_widx = 0; /* Track being buffered (A) */
231 #define CUR_TI (&tracks[track_ridx]) /* Playing track info pointer (A/C-) */
232 static struct track_info *prev_ti = NULL; /* Pointer to the previously played
233 track */
235 /* Set by the audio thread when the current track information has updated
236 * and the WPS may need to update its cached information */
237 static bool track_changed = false;
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 = 0; /* 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 track->filesize = 0;
392 track->taginfo_ready = false;
394 return true;
397 /* --- External interfaces --- */
399 /* This sends a stop message and the audio thread will dump all it's
400 subsequenct messages */
401 void audio_hard_stop(void)
403 /* Stop playback */
404 LOGFQUEUE("audio >| audio Q_AUDIO_STOP: 1");
405 queue_send(&audio_queue, Q_AUDIO_STOP, 1);
406 #ifdef PLAYBACK_VOICE
407 voice_stop();
408 #endif
411 bool audio_restore_playback(int type)
413 switch (type)
415 case AUDIO_WANT_PLAYBACK:
416 if (buffer_state != AUDIOBUF_STATE_INITIALIZED)
417 audio_reset_buffer();
418 return true;
419 case AUDIO_WANT_VOICE:
420 if (buffer_state == AUDIOBUF_STATE_TRASHED)
421 audio_reset_buffer();
422 return true;
423 default:
424 return false;
428 unsigned char *audio_get_buffer(bool talk_buf, size_t *buffer_size)
430 unsigned char *buf, *end;
432 if (audio_is_initialized)
434 audio_hard_stop();
436 /* else buffer_state will be AUDIOBUF_STATE_TRASHED at this point */
438 /* Reset the buffering thread so that it doesn't try to use the data */
439 buffering_reset(filebuf, filebuflen);
441 if (buffer_size == NULL)
443 /* Special case for talk_init to use since it already knows it's
444 trashed */
445 buffer_state = AUDIOBUF_STATE_TRASHED;
446 return NULL;
449 if (talk_buf || buffer_state == AUDIOBUF_STATE_TRASHED
450 || !talk_voice_required())
452 logf("get buffer: talk, audio");
453 /* Ok to use everything from audiobuf to audiobufend - voice is loaded,
454 the talk buffer is not needed because voice isn't being used, or
455 could be AUDIOBUF_STATE_TRASHED already. If state is
456 AUDIOBUF_STATE_VOICED_ONLY, no problem as long as memory isn't written
457 without the caller knowing what's going on. Changing certain settings
458 may move it to a worse condition but the memory in use by something
459 else will remain undisturbed.
461 if (buffer_state != AUDIOBUF_STATE_TRASHED)
463 talk_buffer_steal();
464 buffer_state = AUDIOBUF_STATE_TRASHED;
467 buf = audiobuf;
468 end = audiobufend;
470 else
472 /* Safe to just return this if already AUDIOBUF_STATE_VOICED_ONLY or
473 still AUDIOBUF_STATE_INITIALIZED */
474 /* Skip talk buffer and move pcm buffer to end to maximize available
475 contiguous memory - no audio running means voice will not need the
476 swap space */
477 logf("get buffer: audio");
478 buf = audiobuf + talk_get_bufsize();
479 end = audiobufend - pcmbuf_init(audiobufend);
480 buffer_state = AUDIOBUF_STATE_VOICED_ONLY;
483 *buffer_size = end - buf;
485 return buf;
488 int audio_buffer_state(void)
490 return buffer_state;
493 #ifdef HAVE_RECORDING
494 unsigned char *audio_get_recording_buffer(size_t *buffer_size)
496 /* Stop audio, voice and obtain all available buffer space */
497 audio_hard_stop();
498 talk_buffer_steal();
500 unsigned char *end = audiobufend;
501 buffer_state = AUDIOBUF_STATE_TRASHED;
502 *buffer_size = end - audiobuf;
504 return (unsigned char *)audiobuf;
507 bool audio_load_encoder(int afmt)
509 #ifndef SIMULATOR
510 const char *enc_fn = get_codec_filename(afmt | CODEC_TYPE_ENCODER);
511 if (!enc_fn)
512 return false;
514 audio_remove_encoder();
515 ci.enc_codec_loaded = 0; /* clear any previous error condition */
517 LOGFQUEUE("codec > Q_ENCODER_LOAD_DISK");
518 queue_post(&codec_queue, Q_ENCODER_LOAD_DISK, (intptr_t)enc_fn);
520 while (ci.enc_codec_loaded == 0)
521 yield();
523 logf("codec loaded: %d", ci.enc_codec_loaded);
525 return ci.enc_codec_loaded > 0;
526 #else
527 (void)afmt;
528 return true;
529 #endif
530 } /* audio_load_encoder */
532 void audio_remove_encoder(void)
534 #ifndef SIMULATOR
535 /* force encoder codec unload (if currently loaded) */
536 if (ci.enc_codec_loaded <= 0)
537 return;
539 ci.stop_encoder = true;
540 while (ci.enc_codec_loaded > 0)
541 yield();
542 #endif
543 } /* audio_remove_encoder */
545 #endif /* HAVE_RECORDING */
547 #ifdef HAVE_ALBUMART
548 int audio_current_aa_hid(void)
550 int cur_idx;
551 int offset = ci.new_track + wps_offset;
553 cur_idx = track_ridx + offset;
554 cur_idx &= MAX_TRACK_MASK;
556 return tracks[cur_idx].aa_hid;
558 #endif
560 struct mp3entry* audio_current_track(void)
562 const char *filename;
563 static struct mp3entry temp_id3;
564 struct playlist_track_info trackinfo;
565 int cur_idx;
566 int offset = ci.new_track + wps_offset;
568 cur_idx = (track_ridx + offset) & MAX_TRACK_MASK;
570 if (cur_idx == track_ridx && *curtrack_id3.path)
572 /* The usual case */
573 return &curtrack_id3;
575 else if (automatic_skip && offset == -1 && *prevtrack_id3.path)
577 /* We're in a track transition. The codec has moved on to the nex track,
578 but the audio being played is still the same (now previous) track.
579 prevtrack_id3.elapsed is being updated in an ISR by
580 codec_pcmbuf_position_callback */
581 return &prevtrack_id3;
583 else if (tracks[cur_idx].id3_hid >= 0)
585 /* Get the ID3 metadata from the main buffer */
586 struct mp3entry *ret = bufgetid3(tracks[cur_idx].id3_hid);
587 if (ret) return ret;
590 /* We didn't find the ID3 metadata, so we fill temp_id3 with the little info
591 we have and return that. */
593 memset(&temp_id3, 0, sizeof(struct mp3entry));
595 playlist_get_track_info(NULL, playlist_next(0)+wps_offset, &trackinfo);
596 filename = trackinfo.filename;
597 if (!filename)
598 filename = "No file!";
600 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
601 if (tagcache_fill_tags(&temp_id3, filename))
602 return &temp_id3;
603 #endif
605 strncpy(temp_id3.path, filename, sizeof(temp_id3.path)-1);
606 temp_id3.title = strrchr(temp_id3.path, '/');
607 if (!temp_id3.title)
608 temp_id3.title = &temp_id3.path[0];
609 else
610 temp_id3.title++;
612 return &temp_id3;
615 struct mp3entry* audio_next_track(void)
617 int next_idx;
618 int offset = ci.new_track + wps_offset;
620 if (!audio_have_tracks())
621 return NULL;
623 if (wps_offset == -1 && *prevtrack_id3.path)
625 /* We're in a track transition. The next track for the WPS is the one
626 currently being decoded. */
627 return &curtrack_id3;
630 next_idx = (track_ridx + offset + 1) & MAX_TRACK_MASK;
632 if (tracks[next_idx].id3_hid >= 0)
633 return bufgetid3(tracks[next_idx].id3_hid);
635 if (next_idx == track_widx)
637 /* The next track hasn't been buffered yet, so we return the static
638 version of its metadata. */
639 return &lasttrack_id3;
642 return NULL;
645 bool audio_has_changed_track(void)
647 if (track_changed)
649 #ifdef IPOD_ACCESSORY_PROTOCOL
650 iap_track_changed();
651 #endif
652 track_changed = false;
653 return true;
656 return false;
659 void audio_play(long offset)
661 logf("audio_play");
663 #ifdef PLAYBACK_VOICE
664 /* Truncate any existing voice output so we don't have spelling
665 * etc. over the first part of the played track */
666 talk_force_shutup();
667 #endif
669 /* Start playback */
670 LOGFQUEUE("audio >| audio Q_AUDIO_PLAY: %ld", offset);
671 /* Don't return until playback has actually started */
672 queue_send(&audio_queue, Q_AUDIO_PLAY, offset);
675 void audio_stop(void)
677 /* Stop playback */
678 LOGFQUEUE("audio >| audio Q_AUDIO_STOP");
679 /* Don't return until playback has actually stopped */
680 queue_send(&audio_queue, Q_AUDIO_STOP, 0);
683 void audio_pause(void)
685 LOGFQUEUE("audio >| audio Q_AUDIO_PAUSE");
686 /* Don't return until playback has actually paused */
687 queue_send(&audio_queue, Q_AUDIO_PAUSE, true);
690 void audio_resume(void)
692 LOGFQUEUE("audio >| audio Q_AUDIO_PAUSE resume");
693 /* Don't return until playback has actually resumed */
694 queue_send(&audio_queue, Q_AUDIO_PAUSE, false);
697 void audio_skip(int direction)
699 if (playlist_check(ci.new_track + wps_offset + direction))
701 if (global_settings.beep)
702 pcmbuf_beep(2000, 100, 2500*global_settings.beep);
704 LOGFQUEUE("audio > audio Q_AUDIO_SKIP %d", direction);
705 queue_post(&audio_queue, Q_AUDIO_SKIP, direction);
706 /* Update wps while our message travels inside deep playback queues. */
707 wps_offset += direction;
708 track_changed = true;
710 else
712 /* No more tracks. */
713 if (global_settings.beep)
714 pcmbuf_beep(1000, 100, 1500*global_settings.beep);
718 void audio_next(void)
720 audio_skip(1);
723 void audio_prev(void)
725 audio_skip(-1);
728 void audio_next_dir(void)
730 LOGFQUEUE("audio > audio Q_AUDIO_DIR_SKIP 1");
731 queue_post(&audio_queue, Q_AUDIO_DIR_SKIP, 1);
734 void audio_prev_dir(void)
736 LOGFQUEUE("audio > audio Q_AUDIO_DIR_SKIP -1");
737 queue_post(&audio_queue, Q_AUDIO_DIR_SKIP, -1);
740 void audio_pre_ff_rewind(void)
742 LOGFQUEUE("audio > audio Q_AUDIO_PRE_FF_REWIND");
743 queue_post(&audio_queue, Q_AUDIO_PRE_FF_REWIND, 0);
746 void audio_ff_rewind(long newpos)
748 LOGFQUEUE("audio > audio Q_AUDIO_FF_REWIND");
749 queue_post(&audio_queue, Q_AUDIO_FF_REWIND, newpos);
752 void audio_flush_and_reload_tracks(void)
754 LOGFQUEUE("audio > audio Q_AUDIO_FLUSH");
755 queue_post(&audio_queue, Q_AUDIO_FLUSH, 0);
758 void audio_error_clear(void)
760 #ifdef AUDIO_HAVE_RECORDING
761 pcm_rec_error_clear();
762 #endif
765 int audio_status(void)
767 int ret = 0;
769 if (playing)
770 ret |= AUDIO_STATUS_PLAY;
772 if (paused)
773 ret |= AUDIO_STATUS_PAUSE;
775 #ifdef HAVE_RECORDING
776 /* Do this here for constitency with mpeg.c version */
777 ret |= pcm_rec_status();
778 #endif
780 return ret;
783 int audio_get_file_pos(void)
785 return 0;
788 #ifdef HAVE_DISK_STORAGE
789 void audio_set_buffer_margin(int setting)
791 static const int lookup[] = {5, 15, 30, 60, 120, 180, 300, 600};
792 buffer_margin = lookup[setting];
793 logf("buffer margin: %ld", (long)buffer_margin);
794 set_filebuf_watermark();
796 #endif
798 /* Take necessary steps to enable or disable the crossfade setting */
799 void audio_set_crossfade(int enable)
801 size_t offset;
802 bool was_playing;
803 size_t size;
805 /* Tell it the next setting to use */
806 pcmbuf_crossfade_enable(enable);
808 /* Return if size hasn't changed or this is too early to determine
809 which in the second case there's no way we could be playing
810 anything at all */
811 if (pcmbuf_is_same_size())
813 /* This function is a copout and just syncs some variables -
814 to be removed at a later date */
815 pcmbuf_crossfade_enable_finished();
816 return;
819 offset = 0;
820 was_playing = playing;
822 /* Playback has to be stopped before changing the buffer size */
823 if (was_playing)
825 /* Store the track resume position */
826 offset = curtrack_id3.offset;
829 /* Blast it - audio buffer will have to be setup again next time
830 something plays */
831 audio_get_buffer(true, &size);
833 /* Restart playback if audio was running previously */
834 if (was_playing)
835 audio_play(offset);
838 /* --- Routines called from multiple threads --- */
840 static void set_filebuf_watermark(void)
842 if (!filebuf)
843 return; /* Audio buffers not yet set up */
845 #ifdef HAVE_FLASH_STORAGE
846 int seconds = 1;
847 #else
848 int seconds;
849 int spinup = ata_spinup_time();
850 if (spinup)
851 seconds = (spinup / HZ) + 1;
852 else
853 seconds = 5;
854 #endif
856 /* bitrate of last track in buffer dictates watermark */
857 struct mp3entry* id3 = NULL;
858 if (tracks[track_widx].taginfo_ready)
859 id3 = bufgetid3(tracks[track_widx].id3_hid);
860 else
861 id3 = bufgetid3(tracks[track_widx-1].id3_hid);
862 if (!id3) {
863 logf("fwmark: No id3 for last track (r%d/w%d), aborting!", track_ridx, track_widx);
864 return;
866 size_t bytes = id3->bitrate * (1000/8) * seconds;
867 buf_set_watermark(bytes);
868 logf("fwmark: %d", bytes);
871 const char *get_codec_filename(int cod_spec)
873 const char *fname;
875 #ifdef HAVE_RECORDING
876 /* Can choose decoder or encoder if one available */
877 int type = cod_spec & CODEC_TYPE_MASK;
878 int afmt = cod_spec & CODEC_AFMT_MASK;
880 if ((unsigned)afmt >= AFMT_NUM_CODECS)
881 type = AFMT_UNKNOWN | (type & CODEC_TYPE_MASK);
883 fname = (type == CODEC_TYPE_ENCODER) ?
884 audio_formats[afmt].codec_enc_root_fn :
885 audio_formats[afmt].codec_root_fn;
887 logf("%s: %d - %s",
888 (type == CODEC_TYPE_ENCODER) ? "Encoder" : "Decoder",
889 afmt, fname ? fname : "<unknown>");
890 #else /* !HAVE_RECORDING */
891 /* Always decoder */
892 if ((unsigned)cod_spec >= AFMT_NUM_CODECS)
893 cod_spec = AFMT_UNKNOWN;
894 fname = audio_formats[cod_spec].codec_root_fn;
895 logf("Codec: %d - %s", cod_spec, fname ? fname : "<unknown>");
896 #endif /* HAVE_RECORDING */
898 return fname;
899 } /* get_codec_filename */
901 /* --- Codec thread --- */
902 static bool codec_pcmbuf_insert_callback(
903 const void *ch1, const void *ch2, int count)
905 const char *src[2] = { ch1, ch2 };
907 while (count > 0)
909 int out_count = dsp_output_count(ci.dsp, count);
910 int inp_count;
911 char *dest;
913 /* Prevent audio from a previous track from playing */
914 if (ci.new_track || ci.stop_codec)
915 return true;
917 while ((dest = pcmbuf_request_buffer(&out_count)) == NULL)
919 cancel_cpu_boost();
920 sleep(1);
921 if (ci.seek_time || ci.new_track || ci.stop_codec)
922 return true;
925 /* Get the real input_size for output_size bytes, guarding
926 * against resampling buffer overflows. */
927 inp_count = dsp_input_count(ci.dsp, out_count);
929 if (inp_count <= 0)
930 return true;
932 /* Input size has grown, no error, just don't write more than length */
933 if (inp_count > count)
934 inp_count = count;
936 out_count = dsp_process(ci.dsp, dest, src, inp_count);
938 if (out_count <= 0)
939 return true;
941 pcmbuf_write_complete(out_count);
943 count -= inp_count;
946 return true;
947 } /* codec_pcmbuf_insert_callback */
949 static void* codec_get_buffer(size_t *size)
951 if (codec_size >= CODEC_SIZE)
952 return NULL;
953 *size = CODEC_SIZE - codec_size;
954 return &codecbuf[codec_size];
957 /* Between the codec and PCM track change, we need to keep updating the
958 "elapsed" value of the previous (to the codec, but current to the
959 user/PCM/WPS) track, so that the progressbar reaches the end.
960 During that transition, the WPS will display prevtrack_id3. */
961 static void codec_pcmbuf_position_callback(size_t size) ICODE_ATTR;
962 static void codec_pcmbuf_position_callback(size_t size)
964 /* This is called from an ISR, so be quick */
965 unsigned int time = size * 1000 / 4 / NATIVE_FREQUENCY +
966 prevtrack_id3.elapsed;
968 if (time >= prevtrack_id3.length)
970 pcmbuf_set_position_callback(NULL);
971 prevtrack_id3.elapsed = prevtrack_id3.length;
973 else
974 prevtrack_id3.elapsed = time;
977 static void codec_set_elapsed_callback(unsigned int value)
979 unsigned int latency;
980 if (ci.seek_time)
981 return;
983 #ifdef AB_REPEAT_ENABLE
984 ab_position_report(value);
985 #endif
987 latency = pcmbuf_get_latency();
988 if (value < latency)
989 curtrack_id3.elapsed = 0;
990 else if (value - latency > curtrack_id3.elapsed ||
991 value - latency < curtrack_id3.elapsed - 2)
993 curtrack_id3.elapsed = value - latency;
997 static void codec_set_offset_callback(size_t value)
999 unsigned int latency;
1001 if (ci.seek_time)
1002 return;
1004 latency = pcmbuf_get_latency() * curtrack_id3.bitrate / 8;
1005 if (value < latency)
1006 curtrack_id3.offset = 0;
1007 else
1008 curtrack_id3.offset = value - latency;
1011 static void codec_advance_buffer_counters(size_t amount)
1013 bufadvance(CUR_TI->audio_hid, amount);
1014 ci.curpos += amount;
1017 /* copy up-to size bytes into ptr and return the actual size copied */
1018 static size_t codec_filebuf_callback(void *ptr, size_t size)
1020 ssize_t copy_n;
1022 if (ci.stop_codec || !playing)
1023 return 0;
1025 copy_n = bufread(CUR_TI->audio_hid, size, ptr);
1027 /* Nothing requested OR nothing left */
1028 if (copy_n == 0)
1029 return 0;
1031 /* Update read and other position pointers */
1032 codec_advance_buffer_counters(copy_n);
1034 /* Return the actual amount of data copied to the buffer */
1035 return copy_n;
1036 } /* codec_filebuf_callback */
1038 static void* codec_request_buffer_callback(size_t *realsize, size_t reqsize)
1040 size_t copy_n = reqsize;
1041 ssize_t ret;
1042 void *ptr;
1044 if (!playing)
1046 *realsize = 0;
1047 return NULL;
1050 ret = bufgetdata(CUR_TI->audio_hid, reqsize, &ptr);
1051 if (ret >= 0)
1052 copy_n = MIN((size_t)ret, reqsize);
1054 if (copy_n == 0)
1056 *realsize = 0;
1057 return NULL;
1060 *realsize = copy_n;
1062 return ptr;
1063 } /* codec_request_buffer_callback */
1065 static int get_codec_base_type(int type)
1067 switch (type) {
1068 case AFMT_MPA_L1:
1069 case AFMT_MPA_L2:
1070 case AFMT_MPA_L3:
1071 return AFMT_MPA_L3;
1074 return type;
1077 static void codec_advance_buffer_callback(size_t amount)
1079 codec_advance_buffer_counters(amount);
1080 codec_set_offset_callback(ci.curpos);
1083 static void codec_advance_buffer_loc_callback(void *ptr)
1085 size_t amount = buf_get_offset(CUR_TI->audio_hid, ptr);
1086 codec_advance_buffer_callback(amount);
1089 static void codec_seek_complete_callback(void)
1091 logf("seek_complete");
1092 if (pcm_is_paused())
1094 /* If this is not a seamless seek, clear the buffer */
1095 pcmbuf_play_stop();
1096 dsp_configure(ci.dsp, DSP_FLUSH, 0);
1098 /* If playback was not 'deliberately' paused, unpause now */
1099 if (!paused)
1100 pcmbuf_pause(false);
1102 ci.seek_time = 0;
1105 static bool codec_seek_buffer_callback(size_t newpos)
1107 logf("codec_seek_buffer_callback");
1109 int ret = bufseek(CUR_TI->audio_hid, newpos);
1110 if (ret == 0) {
1111 ci.curpos = newpos;
1112 return true;
1114 else {
1115 return false;
1119 static void codec_configure_callback(int setting, intptr_t value)
1121 switch (setting) {
1122 default:
1123 if (!dsp_configure(ci.dsp, setting, value))
1124 { logf("Illegal key:%d", setting); }
1128 static void codec_track_changed(void)
1130 LOGFQUEUE("codec > audio Q_AUDIO_TRACK_CHANGED");
1131 queue_post(&audio_queue, Q_AUDIO_TRACK_CHANGED, 0);
1134 static void codec_pcmbuf_track_changed_callback(void)
1136 pcmbuf_set_position_callback(NULL);
1137 pcmbuf_callback_queue_post(Q_AUDIO_TRACK_CHANGED, 0);
1140 static void codec_discard_codec_callback(void)
1142 if (CUR_TI->codec_hid >= 0)
1144 bufclose(CUR_TI->codec_hid);
1145 CUR_TI->codec_hid = -1;
1149 static inline void codec_gapless_track_change(void)
1151 /* callback keeps the progress bar moving while the pcmbuf empties */
1152 pcmbuf_set_position_callback(codec_pcmbuf_position_callback);
1153 /* set the pcmbuf callback for when the track really changes */
1154 pcmbuf_set_event_handler(codec_pcmbuf_track_changed_callback);
1157 static inline void codec_crossfade_track_change(void)
1159 /* Initiate automatic crossfade mode */
1160 pcmbuf_crossfade_init(false);
1161 /* Notify the wps that the track change starts now */
1162 codec_track_changed();
1165 static void codec_track_skip_done(bool was_manual)
1167 /* Manual track change (always crossfade or flush audio). */
1168 if (was_manual)
1170 pcmbuf_crossfade_init(true);
1171 LOGFQUEUE("codec > audio Q_AUDIO_TRACK_CHANGED");
1172 queue_post(&audio_queue, Q_AUDIO_TRACK_CHANGED, 0);
1174 /* Automatic track change w/crossfade, if not in "Track Skip Only" mode. */
1175 else if (pcmbuf_is_crossfade_enabled() && !pcmbuf_is_crossfade_active()
1176 && global_settings.crossfade != CROSSFADE_ENABLE_TRACKSKIP)
1178 if (global_settings.crossfade == CROSSFADE_ENABLE_SHUFFLE_AND_TRACKSKIP)
1180 if (global_settings.playlist_shuffle)
1181 /* shuffle mode is on, so crossfade: */
1182 codec_crossfade_track_change();
1183 else
1184 /* shuffle mode is off, so do a gapless track change */
1185 codec_gapless_track_change();
1187 else
1188 /* normal crossfade: */
1189 codec_crossfade_track_change();
1191 else
1192 /* normal gapless playback. */
1193 codec_gapless_track_change();
1196 static bool codec_load_next_track(void)
1198 intptr_t result = Q_CODEC_REQUEST_FAILED;
1200 prev_track_elapsed = curtrack_id3.elapsed;
1202 #ifdef AB_REPEAT_ENABLE
1203 ab_end_of_track_report();
1204 #endif
1206 logf("Request new track");
1208 if (ci.new_track == 0)
1210 ci.new_track++;
1211 automatic_skip = true;
1214 if (!ci.stop_codec)
1216 trigger_cpu_boost();
1217 LOGFQUEUE("codec >| audio Q_AUDIO_CHECK_NEW_TRACK");
1218 result = queue_send(&audio_queue, Q_AUDIO_CHECK_NEW_TRACK, 0);
1221 switch (result)
1223 case Q_CODEC_REQUEST_COMPLETE:
1224 LOGFQUEUE("codec |< Q_CODEC_REQUEST_COMPLETE");
1225 codec_track_skip_done(!automatic_skip);
1226 return true;
1228 case Q_CODEC_REQUEST_FAILED:
1229 LOGFQUEUE("codec |< Q_CODEC_REQUEST_FAILED");
1230 ci.new_track = 0;
1231 ci.stop_codec = true;
1232 codec_requested_stop = true;
1233 return false;
1235 default:
1236 LOGFQUEUE("codec |< default");
1237 ci.stop_codec = true;
1238 codec_requested_stop = true;
1239 return false;
1243 static bool codec_request_next_track_callback(void)
1245 int prev_codectype;
1247 if (ci.stop_codec || !playing)
1248 return false;
1250 prev_codectype = get_codec_base_type(curtrack_id3.codectype);
1252 if (!codec_load_next_track())
1253 return false;
1255 /* Seek to the beginning of the new track because if the struct
1256 mp3entry was buffered, "elapsed" might not be zero (if the track has
1257 been played already but not unbuffered) */
1258 codec_seek_buffer_callback(curtrack_id3.first_frame_offset);
1260 /* Check if the next codec is the same file. */
1261 if (prev_codectype == get_codec_base_type(curtrack_id3.codectype))
1263 logf("New track loaded");
1264 codec_discard_codec_callback();
1265 return true;
1267 else
1269 logf("New codec:%d/%d", curtrack_id3.codectype, prev_codectype);
1270 return false;
1274 static void codec_thread(void)
1276 struct queue_event ev;
1277 int status;
1279 while (1) {
1280 status = 0;
1282 if (!pcmbuf_is_crossfade_active()) {
1283 cancel_cpu_boost();
1286 queue_wait(&codec_queue, &ev);
1287 codec_requested_stop = false;
1289 switch (ev.id) {
1290 case Q_CODEC_LOAD_DISK:
1291 LOGFQUEUE("codec < Q_CODEC_LOAD_DISK");
1292 queue_reply(&codec_queue, 1);
1293 audio_codec_loaded = true;
1294 ci.stop_codec = false;
1295 status = codec_load_file((const char *)ev.data, &ci);
1296 break;
1298 case Q_CODEC_LOAD:
1299 LOGFQUEUE("codec < Q_CODEC_LOAD");
1300 if (CUR_TI->codec_hid < 0) {
1301 logf("Codec slot is empty!");
1302 /* Wait for the pcm buffer to go empty */
1303 while (pcm_is_playing())
1304 yield();
1305 /* This must be set to prevent an infinite loop */
1306 ci.stop_codec = true;
1307 LOGFQUEUE("codec > codec Q_AUDIO_PLAY");
1308 queue_post(&codec_queue, Q_AUDIO_PLAY, 0);
1309 break;
1312 audio_codec_loaded = true;
1313 ci.stop_codec = false;
1314 status = codec_load_buf(CUR_TI->codec_hid, &ci);
1315 break;
1317 case Q_CODEC_DO_CALLBACK:
1318 LOGFQUEUE("codec < Q_CODEC_DO_CALLBACK");
1319 queue_reply(&codec_queue, 1);
1320 if ((void*)ev.data != NULL)
1322 cpucache_invalidate();
1323 ((void (*)(void))ev.data)();
1324 cpucache_flush();
1326 break;
1328 #ifdef AUDIO_HAVE_RECORDING
1329 case Q_ENCODER_LOAD_DISK:
1330 LOGFQUEUE("codec < Q_ENCODER_LOAD_DISK");
1331 audio_codec_loaded = false; /* Not audio codec! */
1332 logf("loading encoder");
1333 ci.stop_encoder = false;
1334 status = codec_load_file((const char *)ev.data, &ci);
1335 logf("encoder stopped");
1336 break;
1337 #endif /* AUDIO_HAVE_RECORDING */
1339 default:
1340 LOGFQUEUE("codec < default");
1343 if (audio_codec_loaded)
1345 if (ci.stop_codec)
1347 status = CODEC_OK;
1348 if (!playing)
1349 pcmbuf_play_stop();
1352 audio_codec_loaded = false;
1355 switch (ev.id) {
1356 case Q_CODEC_LOAD_DISK:
1357 case Q_CODEC_LOAD:
1358 LOGFQUEUE("codec < Q_CODEC_LOAD");
1359 if (playing)
1361 if (ci.new_track || status != CODEC_OK)
1363 if (!ci.new_track)
1365 logf("Codec failure");
1366 splash(HZ*2, "Codec failure");
1369 if (!codec_load_next_track())
1371 LOGFQUEUE("codec > audio Q_AUDIO_STOP");
1372 /* End of playlist */
1373 queue_post(&audio_queue, Q_AUDIO_STOP, 0);
1374 break;
1377 else
1379 logf("Codec finished");
1380 if (ci.stop_codec)
1382 /* Wait for the audio to stop playing before
1383 * triggering the WPS exit */
1384 while(pcm_is_playing())
1386 curtrack_id3.elapsed =
1387 curtrack_id3.length - pcmbuf_get_latency();
1388 sleep(1);
1391 if (codec_requested_stop)
1393 LOGFQUEUE("codec > audio Q_AUDIO_STOP");
1394 queue_post(&audio_queue, Q_AUDIO_STOP, 0);
1396 break;
1400 if (CUR_TI->codec_hid >= 0)
1402 LOGFQUEUE("codec > codec Q_CODEC_LOAD");
1403 queue_post(&codec_queue, Q_CODEC_LOAD, 0);
1405 else
1407 const char *codec_fn =
1408 get_codec_filename(curtrack_id3.codectype);
1409 if (codec_fn)
1411 LOGFQUEUE("codec > codec Q_CODEC_LOAD_DISK");
1412 queue_post(&codec_queue, Q_CODEC_LOAD_DISK,
1413 (intptr_t)codec_fn);
1417 break;
1419 #ifdef AUDIO_HAVE_RECORDING
1420 case Q_ENCODER_LOAD_DISK:
1421 LOGFQUEUE("codec < Q_ENCODER_LOAD_DISK");
1423 if (status == CODEC_OK)
1424 break;
1426 logf("Encoder failure");
1427 splash(HZ*2, "Encoder failure");
1429 if (ci.enc_codec_loaded < 0)
1430 break;
1432 logf("Encoder failed to load");
1433 ci.enc_codec_loaded = -1;
1434 break;
1435 #endif /* AUDIO_HAVE_RECORDING */
1437 default:
1438 LOGFQUEUE("codec < default");
1440 } /* end switch */
1444 /* Borrow the codec thread and return the ID */
1445 void codec_thread_do_callback(void (*fn)(void), unsigned int *id)
1447 /* Set id before telling thread to call something; it may be
1448 * needed before this function returns. */
1449 if (id != NULL)
1450 *id = codec_thread_id;
1452 /* Codec thread will signal just before entering callback */
1453 LOGFQUEUE("codec >| Q_CODEC_DO_CALLBACK");
1454 queue_send(&codec_queue, Q_CODEC_DO_CALLBACK, (intptr_t)fn);
1457 /* --- Buffering callbacks --- */
1459 static void buffering_low_buffer_callback(void *data)
1461 (void)data;
1462 logf("low buffer callback");
1464 if (filling == STATE_FULL || filling == STATE_END_OF_PLAYLIST) {
1465 /* force a refill */
1466 LOGFQUEUE("buffering > audio Q_AUDIO_FILL_BUFFER");
1467 queue_post(&audio_queue, Q_AUDIO_FILL_BUFFER, 0);
1471 static void buffering_handle_rebuffer_callback(void *data)
1473 (void)data;
1474 LOGFQUEUE("audio >| audio Q_AUDIO_FLUSH");
1475 queue_post(&audio_queue, Q_AUDIO_FLUSH, 0);
1478 static void buffering_handle_finished_callback(int *data)
1480 logf("handle %d finished buffering", *data);
1482 if (*data == tracks[track_widx].id3_hid)
1484 /* The metadata handle for the last loaded track has been buffered.
1485 We can ask the audio thread to load the rest of the track's data. */
1486 LOGFQUEUE("audio >| audio Q_AUDIO_FINISH_LOAD");
1487 queue_post(&audio_queue, Q_AUDIO_FINISH_LOAD, 0);
1489 else
1491 /* This is most likely an audio handle, so we strip the useless
1492 trailing tags that are left. */
1493 strip_tags(*data);
1495 if (*data == tracks[track_widx-1].audio_hid
1496 && filling == STATE_END_OF_PLAYLIST)
1498 /* This was the last track in the playlist.
1499 We now have all the data we need. */
1500 logf("last track finished buffering");
1501 filling = STATE_FINISHED;
1507 /* --- Audio thread --- */
1509 static bool audio_have_tracks(void)
1511 return (audio_track_count() != 0);
1514 static int audio_free_track_count(void)
1516 /* Used tracks + free tracks adds up to MAX_TRACK - 1 */
1517 return MAX_TRACK - 1 - audio_track_count();
1520 int audio_track_count(void)
1522 /* Calculate difference from track_ridx to track_widx
1523 * taking into account a possible wrap-around. */
1524 return (MAX_TRACK + track_widx - track_ridx) & MAX_TRACK_MASK;
1527 long audio_filebufused(void)
1529 return (long) buf_used();
1532 /* Update track info after successful a codec track change */
1533 static void audio_update_trackinfo(void)
1535 /* Load the curent track's metadata into curtrack_id3 */
1536 if (CUR_TI->id3_hid >= 0)
1537 copy_mp3entry(&curtrack_id3, bufgetid3(CUR_TI->id3_hid));
1539 /* Reset current position */
1540 curtrack_id3.elapsed = 0;
1541 curtrack_id3.offset = 0;
1543 /* Update the codec API */
1544 ci.filesize = CUR_TI->filesize;
1545 ci.id3 = &curtrack_id3;
1546 ci.curpos = 0;
1547 ci.taginfo_ready = &CUR_TI->taginfo_ready;
1550 /* Clear tracks between write and read, non inclusive */
1551 static void audio_clear_track_entries(void)
1553 int cur_idx = track_widx;
1555 logf("Clearing tracks:%d/%d", track_ridx, track_widx);
1557 /* Loop over all tracks from write-to-read */
1558 while (1)
1560 cur_idx = (cur_idx + 1) & MAX_TRACK_MASK;
1562 if (cur_idx == track_ridx)
1563 break;
1565 clear_track_info(&tracks[cur_idx]);
1569 /* Clear all tracks */
1570 static bool audio_release_tracks(void)
1572 int i, cur_idx;
1574 logf("releasing all tracks");
1576 for(i = 0; i < MAX_TRACK; i++)
1578 cur_idx = (track_ridx + i) & MAX_TRACK_MASK;
1579 if (!clear_track_info(&tracks[cur_idx]))
1580 return false;
1583 return true;
1586 static bool audio_loadcodec(bool start_play)
1588 int prev_track;
1589 char codec_path[MAX_PATH]; /* Full path to codec */
1590 const struct mp3entry *id3, *prev_id3;
1592 if (tracks[track_widx].id3_hid < 0) {
1593 return false;
1596 id3 = bufgetid3(tracks[track_widx].id3_hid);
1597 if (!id3)
1598 return false;
1600 const char *codec_fn = get_codec_filename(id3->codectype);
1601 if (codec_fn == NULL)
1602 return false;
1604 tracks[track_widx].codec_hid = -1;
1606 if (start_play)
1608 /* Load the codec directly from disk and save some memory. */
1609 track_ridx = track_widx;
1610 ci.filesize = CUR_TI->filesize;
1611 ci.id3 = &curtrack_id3;
1612 ci.taginfo_ready = &CUR_TI->taginfo_ready;
1613 ci.curpos = 0;
1614 LOGFQUEUE("codec > codec Q_CODEC_LOAD_DISK");
1615 queue_post(&codec_queue, Q_CODEC_LOAD_DISK, (intptr_t)codec_fn);
1616 return true;
1618 else
1620 /* If we already have another track than this one buffered */
1621 if (track_widx != track_ridx)
1623 prev_track = (track_widx - 1) & MAX_TRACK_MASK;
1625 id3 = bufgetid3(tracks[track_widx].id3_hid);
1626 prev_id3 = bufgetid3(tracks[prev_track].id3_hid);
1628 /* If the previous codec is the same as this one, there is no need
1629 * to put another copy of it on the file buffer */
1630 if (id3 && prev_id3 &&
1631 get_codec_base_type(id3->codectype) ==
1632 get_codec_base_type(prev_id3->codectype)
1633 && audio_codec_loaded)
1635 logf("Reusing prev. codec");
1636 return true;
1641 codec_get_full_path(codec_path, codec_fn);
1643 tracks[track_widx].codec_hid = bufopen(codec_path, 0, TYPE_CODEC);
1644 if (tracks[track_widx].codec_hid < 0)
1645 return false;
1647 logf("Loaded codec");
1649 return true;
1652 /* Load metadata for the next track (with bufopen). The rest of the track
1653 loading will be handled by audio_finish_load_track once the metadata has been
1654 actually loaded by the buffering thread. */
1655 static bool audio_load_track(size_t offset, bool start_play)
1657 const char *trackname;
1658 int fd = -1;
1660 if (track_load_started) {
1661 /* There is already a track load in progress, so track_widx hasn't been
1662 incremented yet. Loading another track would overwrite the one that
1663 hasn't finished loading. */
1664 logf("audio_load_track(): a track load is already in progress");
1665 return false;
1668 start_play_g = start_play; /* will be read by audio_finish_load_track */
1670 /* Stop buffer filling if there is no free track entries.
1671 Don't fill up the last track entry (we wan't to store next track
1672 metadata there). */
1673 if (!audio_free_track_count())
1675 logf("No free tracks");
1676 return false;
1679 last_peek_offset++;
1680 tracks[track_widx].taginfo_ready = false;
1682 logf("Buffering track:%d/%d", track_widx, track_ridx);
1683 /* Get track name from current playlist read position. */
1684 while ((trackname = playlist_peek(last_peek_offset)) != NULL)
1686 /* Handle broken playlists. */
1687 fd = open(trackname, O_RDONLY);
1688 if (fd < 0)
1690 logf("Open failed");
1691 /* Skip invalid entry from playlist. */
1692 playlist_skip_entry(NULL, last_peek_offset);
1694 else
1695 break;
1698 if (!trackname)
1700 logf("End-of-playlist");
1701 memset(&lasttrack_id3, 0, sizeof(struct mp3entry));
1702 filling = STATE_END_OF_PLAYLIST;
1704 if (curtrack_id3.length == 0 && curtrack_id3.filesize == 0)
1706 /* Stop playback if no valid track was found. */
1707 audio_stop_playback();
1710 return false;
1713 tracks[track_widx].filesize = filesize(fd);
1715 if (offset > tracks[track_widx].filesize)
1716 offset = 0;
1718 /* Set default values */
1719 if (start_play)
1721 buf_set_watermark(filebuflen/2);
1722 dsp_configure(ci.dsp, DSP_RESET, 0);
1723 track_changed = true;
1724 playlist_update_resume_info(audio_current_track());
1727 /* Get track metadata if we don't already have it. */
1728 if (tracks[track_widx].id3_hid < 0)
1730 tracks[track_widx].id3_hid = bufopen(trackname, 0, TYPE_ID3);
1732 if (tracks[track_widx].id3_hid < 0)
1734 /* Buffer is full. */
1735 get_metadata(&lasttrack_id3, fd, trackname);
1736 last_peek_offset--;
1737 close(fd);
1738 logf("buffer is full for now");
1739 filling = STATE_FULL;
1740 return false;
1743 if (track_widx == track_ridx)
1745 /* TODO: Superfluos buffering call? */
1746 buf_request_buffer_handle(tracks[track_widx].id3_hid);
1747 copy_mp3entry(&curtrack_id3, bufgetid3(tracks[track_widx].id3_hid));
1748 curtrack_id3.offset = offset;
1751 if (start_play)
1753 track_changed = true;
1754 playlist_update_resume_info(audio_current_track());
1758 close(fd);
1759 track_load_started = true; /* Remember that we've started loading a track */
1760 return true;
1763 /* Second part of the track loading: We now have the metadata available, so we
1764 can load the codec, the album art and finally the audio data.
1765 This is called on the audio thread after the buffering thread calls the
1766 buffering_handle_finished_callback callback. */
1767 static void audio_finish_load_track(void)
1769 size_t file_offset = 0;
1770 size_t offset = 0;
1771 bool start_play = start_play_g;
1773 track_load_started = false;
1775 if (tracks[track_widx].id3_hid < 0) {
1776 logf("no metatdata");
1777 return;
1780 struct mp3entry *track_id3;
1782 if (track_widx == track_ridx)
1783 track_id3 = &curtrack_id3;
1784 else
1785 track_id3 = bufgetid3(tracks[track_widx].id3_hid);
1787 if (track_id3->length == 0 && track_id3->filesize == 0)
1789 logf("audio_finish_load_track: invalid metadata");
1791 /* Invalid metadata */
1792 bufclose(tracks[track_widx].id3_hid);
1793 tracks[track_widx].id3_hid = -1;
1795 /* Skip invalid entry from playlist. */
1796 playlist_skip_entry(NULL, last_peek_offset--);
1798 /* load next track */
1799 LOGFQUEUE("audio > audio Q_AUDIO_FILL_BUFFER %d", (int)start_play);
1800 queue_post(&audio_queue, Q_AUDIO_FILL_BUFFER, start_play);
1802 return;
1805 #ifdef HAVE_ALBUMART
1806 if (tracks[track_widx].aa_hid < 0 && gui_sync_wps_uses_albumart())
1808 char aa_path[MAX_PATH];
1809 if (find_albumart(track_id3, aa_path, sizeof(aa_path)))
1811 tracks[track_widx].aa_hid = bufopen(aa_path, 0, TYPE_BITMAP);
1813 if(tracks[track_widx].aa_hid == ERR_BUFFER_FULL)
1815 filling = STATE_FULL;
1816 logf("buffer is full for now");
1817 return; /* No space for track's album art, not an error */
1819 else if (tracks[track_widx].aa_hid < 0)
1821 /* another error, ignore AlbumArt */
1822 logf("Album art loading failed");
1826 #endif
1828 /* Load the codec. */
1829 if (!audio_loadcodec(start_play))
1831 if (tracks[track_widx].codec_hid == ERR_BUFFER_FULL)
1833 /* No space for codec on buffer, not an error */
1834 filling = STATE_FULL;
1835 return;
1838 /* This is an error condition, either no codec was found, or reading
1839 * the codec file failed part way through, either way, skip the track */
1840 /* FIXME: We should not use splashf from audio thread! */
1841 splashf(HZ*2, "No codec for: %s", track_id3->path);
1842 /* Skip invalid entry from playlist. */
1843 playlist_skip_entry(NULL, last_peek_offset);
1844 return;
1847 track_id3->elapsed = 0;
1848 offset = track_id3->offset;
1850 enum data_type type = TYPE_PACKET_AUDIO;
1852 switch (track_id3->codectype) {
1853 case AFMT_MPA_L1:
1854 case AFMT_MPA_L2:
1855 case AFMT_MPA_L3:
1856 if (offset > 0) {
1857 file_offset = offset;
1858 track_id3->offset = offset;
1860 break;
1862 case AFMT_WAVPACK:
1863 if (offset > 0) {
1864 file_offset = offset;
1865 track_id3->offset = offset;
1866 track_id3->elapsed = track_id3->length / 2;
1868 break;
1870 case AFMT_OGG_VORBIS:
1871 case AFMT_SPEEX:
1872 case AFMT_FLAC:
1873 case AFMT_PCM_WAV:
1874 case AFMT_A52:
1875 case AFMT_AAC:
1876 case AFMT_MPC:
1877 case AFMT_APE:
1878 case AFMT_WMA:
1879 if (offset > 0)
1880 track_id3->offset = offset;
1881 break;
1883 case AFMT_NSF:
1884 case AFMT_SPC:
1885 case AFMT_SID:
1886 logf("Loading atomic %d",track_id3->codectype);
1887 type = TYPE_ATOMIC_AUDIO;
1888 break;
1891 logf("alt:%s", track_id3->path);
1893 if (file_offset > AUDIO_REBUFFER_GUESS_SIZE)
1894 file_offset -= AUDIO_REBUFFER_GUESS_SIZE;
1895 else if (track_id3->first_frame_offset)
1896 file_offset = track_id3->first_frame_offset;
1897 else
1898 file_offset = 0;
1900 tracks[track_widx].audio_hid = bufopen(track_id3->path, file_offset, type);
1902 /* No space left, not an error */
1903 if (tracks[track_widx].audio_hid == ERR_BUFFER_FULL)
1905 filling = STATE_FULL;
1906 logf("buffer is full for now");
1907 return;
1909 else if (tracks[track_widx].audio_hid < 0)
1911 /* another error, do not continue either */
1912 logf("Could not add audio data handle");
1913 return;
1916 /* All required data is now available for the codec. */
1917 tracks[track_widx].taginfo_ready = true;
1919 if (start_play)
1921 ci.curpos=file_offset;
1922 buf_request_buffer_handle(tracks[track_widx].audio_hid);
1925 track_widx = (track_widx + 1) & MAX_TRACK_MASK;
1927 send_event(PLAYBACK_EVENT_TRACK_BUFFER, track_id3);
1929 /* load next track */
1930 LOGFQUEUE("audio > audio Q_AUDIO_FILL_BUFFER");
1931 queue_post(&audio_queue, Q_AUDIO_FILL_BUFFER, 0);
1933 return;
1936 static void audio_fill_file_buffer(bool start_play, size_t offset)
1938 bool had_next_track = audio_next_track() != NULL;
1940 filling = STATE_FILLING;
1941 trigger_cpu_boost();
1943 /* No need to rebuffer if there are track skips pending. */
1944 if (ci.new_track != 0)
1945 return;
1947 /* Must reset the buffer before use if trashed or voice only - voice
1948 file size shouldn't have changed so we can go straight from
1949 AUDIOBUF_STATE_VOICED_ONLY to AUDIOBUF_STATE_INITIALIZED */
1950 if (buffer_state != AUDIOBUF_STATE_INITIALIZED)
1951 audio_reset_buffer();
1953 logf("Starting buffer fill");
1955 if (!start_play)
1956 audio_clear_track_entries();
1958 /* Save the current resume position once. */
1959 playlist_update_resume_info(audio_current_track());
1961 audio_load_track(offset, start_play);
1963 if (!had_next_track && audio_next_track())
1964 track_changed = true;
1967 static void audio_rebuffer(void)
1969 logf("Forcing rebuffer");
1971 clear_track_info(CUR_TI);
1973 /* Reset track pointers */
1974 track_widx = track_ridx;
1975 audio_clear_track_entries();
1977 /* Reset a possibly interrupted track load */
1978 track_load_started = false;
1980 /* Fill the buffer */
1981 last_peek_offset = -1;
1982 ci.curpos = 0;
1984 if (!CUR_TI->taginfo_ready)
1985 memset(&curtrack_id3, 0, sizeof(struct mp3entry));
1987 audio_fill_file_buffer(false, 0);
1990 /* Called on request from the codec to get a new track. This is the codec part
1991 of the track transition. */
1992 static int audio_check_new_track(void)
1994 int track_count = audio_track_count();
1995 int old_track_ridx = track_ridx;
1996 int i, idx;
1997 bool forward;
1999 /* Now it's good time to send track finish events. */
2000 send_event(PLAYBACK_EVENT_TRACK_FINISH, &curtrack_id3);
2001 if (dir_skip)
2003 dir_skip = false;
2004 /* regardless of the return value we need to rebuffer.
2005 if it fails the old playlist will resume, else the
2006 next dir will start playing */
2007 playlist_next_dir(ci.new_track);
2008 ci.new_track = 0;
2009 audio_rebuffer();
2010 goto skip_done;
2013 if (new_playlist)
2014 ci.new_track = 0;
2016 /* If the playlist isn't that big */
2017 if (automatic_skip)
2019 while (!playlist_check(ci.new_track))
2021 if (ci.new_track >= 0)
2023 LOGFQUEUE("audio >|= codec Q_CODEC_REQUEST_FAILED");
2024 return Q_CODEC_REQUEST_FAILED;
2026 ci.new_track++;
2030 /* Update the playlist */
2031 last_peek_offset -= ci.new_track;
2033 if (playlist_next(ci.new_track) < 0)
2035 LOGFQUEUE("audio >|= codec Q_CODEC_REQUEST_FAILED");
2036 return Q_CODEC_REQUEST_FAILED;
2039 if (new_playlist)
2041 ci.new_track = 1;
2042 new_playlist = false;
2045 /* Save the track metadata to allow the WPS to display it
2046 while PCM finishes playing that track */
2047 copy_mp3entry(&prevtrack_id3, &curtrack_id3);
2049 /* Update the main buffer copy of the track metadata with the one
2050 the codec has been using (for the unbuffer callbacks) */
2051 if (CUR_TI->id3_hid >= 0)
2052 copy_mp3entry(bufgetid3(CUR_TI->id3_hid), &curtrack_id3);
2054 /* Save a pointer to the old track to allow later clearing */
2055 prev_ti = CUR_TI;
2057 for (i = 0; i < ci.new_track; i++)
2059 idx = (track_ridx + i) & MAX_TRACK_MASK;
2060 struct mp3entry *id3 = bufgetid3(tracks[idx].id3_hid);
2061 ssize_t offset = buf_handle_offset(tracks[idx].audio_hid);
2062 if (!id3 || offset < 0 || (unsigned)offset > id3->first_frame_offset)
2064 /* We don't have all the audio data for that track, so clear it,
2065 but keep the metadata. */
2066 if (tracks[idx].audio_hid >= 0 && bufclose(tracks[idx].audio_hid))
2068 tracks[idx].audio_hid = -1;
2069 tracks[idx].filesize = 0;
2074 /* Move to the new track */
2075 track_ridx = (track_ridx + ci.new_track) & MAX_TRACK_MASK;
2077 buf_set_base_handle(CUR_TI->audio_hid);
2079 if (automatic_skip)
2081 wps_offset = -ci.new_track;
2082 track_changed = true;
2085 /* If it is not safe to even skip this many track entries */
2086 if (ci.new_track >= track_count || ci.new_track <= track_count - MAX_TRACK)
2088 ci.new_track = 0;
2089 audio_rebuffer();
2090 goto skip_done;
2093 forward = ci.new_track > 0;
2094 ci.new_track = 0;
2096 /* If the target track is clearly not in memory */
2097 if (CUR_TI->filesize == 0 || !CUR_TI->taginfo_ready)
2099 audio_rebuffer();
2100 goto skip_done;
2103 /* When skipping backwards, it is possible that we've found a track that's
2104 * buffered, but which is around the track-wrap and therefore not the track
2105 * we are looking for */
2106 if (!forward)
2108 int cur_idx = track_ridx;
2109 bool taginfo_ready = true;
2110 /* We've wrapped the buffer backwards if new > old */
2111 bool wrap = track_ridx > old_track_ridx;
2113 while (1)
2115 cur_idx = (cur_idx + 1) & MAX_TRACK_MASK;
2117 /* if we've advanced past the wrap when cur_idx is zeroed */
2118 if (!cur_idx)
2119 wrap = false;
2121 /* if we aren't still on the wrap and we've caught the old track */
2122 if (!(wrap || cur_idx < old_track_ridx))
2123 break;
2125 /* If we hit a track in between without valid tag info, bail */
2126 if (!tracks[cur_idx].taginfo_ready)
2128 taginfo_ready = false;
2129 break;
2132 if (!taginfo_ready)
2134 audio_rebuffer();
2138 skip_done:
2139 audio_update_trackinfo();
2140 LOGFQUEUE("audio >|= codec Q_CODEC_REQUEST_COMPLETE");
2141 return Q_CODEC_REQUEST_COMPLETE;
2144 unsigned long audio_prev_elapsed(void)
2146 return prev_track_elapsed;
2149 static void audio_stop_codec_flush(void)
2151 ci.stop_codec = true;
2152 pcmbuf_pause(true);
2154 while (audio_codec_loaded)
2155 yield();
2157 /* If the audio codec is not loaded any more, and the audio is still
2158 * playing, it is now and _only_ now safe to call this function from the
2159 * audio thread */
2160 if (pcm_is_playing())
2162 pcmbuf_play_stop();
2163 pcmbuf_queue_clear();
2165 pcmbuf_pause(paused);
2168 static void audio_stop_playback(void)
2170 /* If we were playing, save resume information */
2171 if (playing)
2173 struct mp3entry *id3 = NULL;
2175 if (!ci.stop_codec)
2177 /* Set this early, the outside code yields and may allow the codec
2178 to try to wait for a reply on a buffer wait */
2179 ci.stop_codec = true;
2180 id3 = audio_current_track();
2183 /* Save the current playing spot, or NULL if the playlist has ended */
2184 playlist_update_resume_info(id3);
2186 /* TODO: Create auto bookmark too? */
2188 prev_track_elapsed = curtrack_id3.elapsed;
2190 remove_event(BUFFER_EVENT_BUFFER_LOW, buffering_low_buffer_callback);
2193 audio_stop_codec_flush();
2194 paused = false;
2195 playing = false;
2196 track_load_started = false;
2198 filling = STATE_IDLE;
2200 /* Mark all entries null. */
2201 audio_clear_track_entries();
2203 /* Close all tracks */
2204 audio_release_tracks();
2206 memset(&curtrack_id3, 0, sizeof(struct mp3entry));
2209 static void audio_play_start(size_t offset)
2211 int i;
2213 #if INPUT_SRC_CAPS != 0
2214 audio_set_input_source(AUDIO_SRC_PLAYBACK, SRCF_PLAYBACK);
2215 audio_set_output_source(AUDIO_SRC_PLAYBACK);
2216 #endif
2218 /* Wait for any previously playing audio to flush - TODO: Not necessary? */
2219 paused = false;
2220 audio_stop_codec_flush();
2222 track_changed = true;
2224 playing = true;
2225 track_load_started = false;
2227 ci.new_track = 0;
2228 ci.seek_time = 0;
2229 wps_offset = 0;
2231 sound_set_volume(global_settings.volume);
2232 track_widx = track_ridx = 0;
2234 /* Clear all track entries. */
2235 for (i = 0; i < MAX_TRACK; i++) {
2236 clear_track_info(&tracks[i]);
2239 last_peek_offset = -1;
2241 /* Officially playing */
2242 queue_reply(&audio_queue, 1);
2244 audio_fill_file_buffer(true, offset);
2246 add_event(BUFFER_EVENT_BUFFER_LOW, false, buffering_low_buffer_callback);
2248 LOGFQUEUE("audio > audio Q_AUDIO_TRACK_CHANGED");
2249 queue_post(&audio_queue, Q_AUDIO_TRACK_CHANGED, 0);
2253 /* Invalidates all but currently playing track. */
2254 static void audio_invalidate_tracks(void)
2256 if (audio_have_tracks())
2258 last_peek_offset = 0;
2259 track_widx = track_ridx;
2261 /* Mark all other entries null (also buffered wrong metadata). */
2262 audio_clear_track_entries();
2264 track_widx = (track_widx + 1) & MAX_TRACK_MASK;
2266 audio_fill_file_buffer(false, 0);
2270 static void audio_new_playlist(void)
2272 /* Prepare to start a new fill from the beginning of the playlist */
2273 last_peek_offset = -1;
2274 if (audio_have_tracks())
2276 if (paused)
2277 skipped_during_pause = true;
2278 track_widx = track_ridx;
2279 audio_clear_track_entries();
2281 track_widx = (track_widx + 1) & MAX_TRACK_MASK;
2283 /* Mark the current track as invalid to prevent skipping back to it */
2284 CUR_TI->taginfo_ready = false;
2287 /* Signal the codec to initiate a track change forward */
2288 new_playlist = true;
2289 ci.new_track = 1;
2291 /* Officially playing */
2292 queue_reply(&audio_queue, 1);
2294 audio_fill_file_buffer(false, 0);
2297 /* Called on manual track skip */
2298 static void audio_initiate_track_change(long direction)
2300 logf("audio_initiate_track_change(%ld)", direction);
2302 ci.new_track += direction;
2303 wps_offset -= direction;
2304 if (paused)
2305 skipped_during_pause = true;
2308 /* Called on manual dir skip */
2309 static void audio_initiate_dir_change(long direction)
2311 dir_skip = true;
2312 ci.new_track = direction;
2313 if (paused)
2314 skipped_during_pause = true;
2317 /* Called when PCM track change is complete */
2318 static void audio_finalise_track_change(void)
2320 logf("audio_finalise_track_change");
2322 if (automatic_skip)
2324 wps_offset = 0;
2325 automatic_skip = false;
2327 /* Invalidate prevtrack_id3 */
2328 prevtrack_id3.path[0] = 0;
2330 if (prev_ti && prev_ti->audio_hid < 0)
2332 /* No audio left so we clear all the track info. */
2333 clear_track_info(prev_ti);
2336 if (prev_ti && prev_ti->id3_hid >= 0)
2338 /* Reset the elapsed time to force the progressbar to be empty if
2339 the user skips back to this track */
2340 bufgetid3(prev_ti->id3_hid)->elapsed = 0;
2344 send_event(PLAYBACK_EVENT_TRACK_CHANGE, &curtrack_id3);
2346 track_changed = true;
2347 playlist_update_resume_info(audio_current_track());
2351 * Layout audio buffer as follows - iram buffer depends on target:
2352 * [|SWAP:iram][|TALK]|FILE|GUARD|PCM|[SWAP:dram[|iram]|]
2354 static void audio_reset_buffer(void)
2356 /* see audio_get_recording_buffer if this is modified */
2357 logf("audio_reset_buffer");
2359 /* If the setup of anything allocated before the file buffer is
2360 changed, do check the adjustments after the buffer_alloc call
2361 as it will likely be affected and need sliding over */
2363 /* Initially set up file buffer as all space available */
2364 malloc_buf = audiobuf + talk_get_bufsize();
2365 /* Align the malloc buf to line size. Especially important to cf
2366 targets that do line reads/writes. */
2367 malloc_buf = (unsigned char *)(((uintptr_t)malloc_buf + 15) & ~15);
2368 filebuf = malloc_buf; /* filebuf line align implied */
2369 filebuflen = audiobufend - filebuf;
2371 filebuflen &= ~15;
2373 /* Subtract whatever the pcm buffer says it used plus the guard buffer */
2374 const size_t pcmbuf_size = pcmbuf_init(filebuf + filebuflen) +GUARD_BUFSIZE;
2376 #ifdef DEBUG
2377 if(pcmbuf_size > filebuflen)
2378 panicf("Not enough memory for pcmbuf_init() : %d > %d",
2379 (int)pcmbuf_size, (int)filebuflen);
2380 #endif
2382 filebuflen -= pcmbuf_size;
2384 /* Make sure filebuflen is a longword multiple after adjustment - filebuf
2385 will already be line aligned */
2386 filebuflen &= ~3;
2388 buffering_reset(filebuf, filebuflen);
2390 /* Clear any references to the file buffer */
2391 buffer_state = AUDIOBUF_STATE_INITIALIZED;
2393 #if defined(ROCKBOX_HAS_LOGF) && defined(LOGF_ENABLE)
2394 /* Make sure everything adds up - yes, some info is a bit redundant but
2395 aids viewing and the sumation of certain variables should add up to
2396 the location of others. */
2398 size_t pcmbufsize;
2399 const unsigned char *pcmbuf = pcmbuf_get_meminfo(&pcmbufsize);
2400 logf("mabuf: %08X", (unsigned)malloc_buf);
2401 logf("fbuf: %08X", (unsigned)filebuf);
2402 logf("fbufe: %08X", (unsigned)(filebuf + filebuflen));
2403 logf("gbuf: %08X", (unsigned)(filebuf + filebuflen));
2404 logf("gbufe: %08X", (unsigned)(filebuf + filebuflen + GUARD_BUFSIZE));
2405 logf("pcmb: %08X", (unsigned)pcmbuf);
2406 logf("pcmbe: %08X", (unsigned)(pcmbuf + pcmbufsize));
2408 #endif
2411 static void audio_thread(void)
2413 struct queue_event ev;
2415 pcm_postinit();
2417 audio_thread_ready = true;
2419 while (1)
2421 if (filling != STATE_FILLING) {
2422 /* End of buffering, let's calculate the watermark and unboost */
2423 set_filebuf_watermark();
2424 cancel_cpu_boost();
2427 if (!pcmbuf_queue_scan(&ev))
2428 queue_wait_w_tmo(&audio_queue, &ev, HZ/2);
2430 switch (ev.id) {
2432 case Q_AUDIO_FILL_BUFFER:
2433 LOGFQUEUE("audio < Q_AUDIO_FILL_BUFFER %d", (int)ev.data);
2434 audio_fill_file_buffer((bool)ev.data, 0);
2435 break;
2437 case Q_AUDIO_FINISH_LOAD:
2438 LOGFQUEUE("audio < Q_AUDIO_FINISH_LOAD");
2439 audio_finish_load_track();
2440 break;
2442 case Q_AUDIO_PLAY:
2443 LOGFQUEUE("audio < Q_AUDIO_PLAY");
2444 if (playing && ev.data <= 0)
2445 audio_new_playlist();
2446 else
2448 audio_stop_playback();
2449 audio_play_start((size_t)ev.data);
2451 break;
2453 case Q_AUDIO_STOP:
2454 LOGFQUEUE("audio < Q_AUDIO_STOP");
2455 if (playing)
2456 audio_stop_playback();
2457 if (ev.data != 0)
2458 queue_clear(&audio_queue);
2459 break;
2461 case Q_AUDIO_PAUSE:
2462 LOGFQUEUE("audio < Q_AUDIO_PAUSE");
2463 if (!(bool) ev.data && skipped_during_pause && !pcmbuf_is_crossfade_active())
2464 pcmbuf_play_stop(); /* Flush old track on resume after skip */
2465 skipped_during_pause = false;
2466 if (!playing)
2467 break;
2468 pcmbuf_pause((bool)ev.data);
2469 paused = (bool)ev.data;
2470 break;
2472 case Q_AUDIO_SKIP:
2473 LOGFQUEUE("audio < Q_AUDIO_SKIP");
2474 audio_initiate_track_change((long)ev.data);
2475 break;
2477 case Q_AUDIO_PRE_FF_REWIND:
2478 LOGFQUEUE("audio < Q_AUDIO_PRE_FF_REWIND");
2479 if (!playing)
2480 break;
2481 pcmbuf_pause(true);
2482 break;
2484 case Q_AUDIO_FF_REWIND:
2485 LOGFQUEUE("audio < Q_AUDIO_FF_REWIND");
2486 if (!playing)
2487 break;
2488 if (automatic_skip)
2490 /* An automatic track skip is in progress. Finalize it,
2491 then go back to the previous track */
2492 audio_finalise_track_change();
2493 ci.new_track = -1;
2495 ci.seek_time = (long)ev.data+1;
2496 break;
2498 case Q_AUDIO_CHECK_NEW_TRACK:
2499 LOGFQUEUE("audio < Q_AUDIO_CHECK_NEW_TRACK");
2500 queue_reply(&audio_queue, audio_check_new_track());
2501 break;
2503 case Q_AUDIO_DIR_SKIP:
2504 LOGFQUEUE("audio < Q_AUDIO_DIR_SKIP");
2505 audio_initiate_dir_change(ev.data);
2506 break;
2508 case Q_AUDIO_FLUSH:
2509 LOGFQUEUE("audio < Q_AUDIO_FLUSH");
2510 audio_invalidate_tracks();
2511 break;
2513 case Q_AUDIO_TRACK_CHANGED:
2514 /* PCM track change done */
2515 LOGFQUEUE("audio < Q_AUDIO_TRACK_CHANGED");
2516 audio_finalise_track_change();
2517 break;
2519 #ifndef SIMULATOR
2520 case SYS_USB_CONNECTED:
2521 LOGFQUEUE("audio < SYS_USB_CONNECTED");
2522 if (playing)
2523 audio_stop_playback();
2524 #ifdef PLAYBACK_VOICE
2525 voice_stop();
2526 #endif
2527 usb_acknowledge(SYS_USB_CONNECTED_ACK);
2528 usb_wait_for_disconnect(&audio_queue);
2530 /* Mark all entries null. */
2531 audio_clear_track_entries();
2533 /* release tracks to make sure all handles are closed */
2534 audio_release_tracks();
2535 break;
2536 #endif
2538 case SYS_TIMEOUT:
2539 LOGFQUEUE_SYS_TIMEOUT("audio < SYS_TIMEOUT");
2540 break;
2542 default:
2543 LOGFQUEUE("audio < default");
2544 break;
2545 } /* end switch */
2546 } /* end while */
2549 /* Initialize the audio system - called from init() in main.c.
2550 * Last function because of all the references to internal symbols
2552 void audio_init(void)
2554 unsigned int audio_thread_id;
2556 /* Can never do this twice */
2557 if (audio_is_initialized)
2559 logf("audio: already initialized");
2560 return;
2563 logf("audio: initializing");
2565 /* Initialize queues before giving control elsewhere in case it likes
2566 to send messages. Thread creation will be delayed however so nothing
2567 starts running until ready if something yields such as talk_init. */
2568 queue_init(&audio_queue, true);
2569 queue_init(&codec_queue, false);
2570 queue_init(&pcmbuf_queue, false);
2572 pcm_init();
2574 /* Initialize codec api. */
2575 ci.read_filebuf = codec_filebuf_callback;
2576 ci.pcmbuf_insert = codec_pcmbuf_insert_callback;
2577 ci.codec_get_buffer = codec_get_buffer;
2578 ci.request_buffer = codec_request_buffer_callback;
2579 ci.advance_buffer = codec_advance_buffer_callback;
2580 ci.advance_buffer_loc = codec_advance_buffer_loc_callback;
2581 ci.request_next_track = codec_request_next_track_callback;
2582 ci.seek_buffer = codec_seek_buffer_callback;
2583 ci.seek_complete = codec_seek_complete_callback;
2584 ci.set_elapsed = codec_set_elapsed_callback;
2585 ci.set_offset = codec_set_offset_callback;
2586 ci.configure = codec_configure_callback;
2587 ci.discard_codec = codec_discard_codec_callback;
2588 ci.dsp = (struct dsp_config *)dsp_configure(NULL, DSP_MYDSP,
2589 CODEC_IDX_AUDIO);
2591 /* initialize the buffer */
2592 filebuf = audiobuf;
2594 /* audio_reset_buffer must to know the size of voice buffer so init
2595 talk first */
2596 talk_init();
2598 codec_thread_id = create_thread(
2599 codec_thread, codec_stack, sizeof(codec_stack),
2600 CREATE_THREAD_FROZEN,
2601 codec_thread_name IF_PRIO(, PRIORITY_PLAYBACK)
2602 IF_COP(, CPU));
2604 queue_enable_queue_send(&codec_queue, &codec_queue_sender_list,
2605 codec_thread_id);
2607 audio_thread_id = create_thread(audio_thread, audio_stack,
2608 sizeof(audio_stack), CREATE_THREAD_FROZEN,
2609 audio_thread_name IF_PRIO(, PRIORITY_USER_INTERFACE)
2610 IF_COP(, CPU));
2612 queue_enable_queue_send(&audio_queue, &audio_queue_sender_list,
2613 audio_thread_id);
2615 #ifdef PLAYBACK_VOICE
2616 voice_thread_init();
2617 #endif
2619 /* Set crossfade setting for next buffer init which should be about... */
2620 pcmbuf_crossfade_enable(global_settings.crossfade);
2622 /* initialize the buffering system */
2624 buffering_init();
2625 /* ...now! Set up the buffers */
2626 audio_reset_buffer();
2628 int i;
2629 for(i = 0; i < MAX_TRACK; i++)
2631 tracks[i].audio_hid = -1;
2632 tracks[i].id3_hid = -1;
2633 tracks[i].codec_hid = -1;
2634 #ifdef HAVE_ALBUMART
2635 tracks[i].aa_hid = -1;
2636 #endif
2639 add_event(BUFFER_EVENT_REBUFFER, false, buffering_handle_rebuffer_callback);
2640 add_event(BUFFER_EVENT_FINISHED, false, buffering_handle_finished_callback);
2642 /* Probably safe to say */
2643 audio_is_initialized = true;
2645 sound_settings_apply();
2646 #ifdef HAVE_DISK_STORAGE
2647 audio_set_buffer_margin(global_settings.buffer_margin);
2648 #endif
2650 /* it's safe to let the threads run now */
2651 #ifdef PLAYBACK_VOICE
2652 voice_thread_resume();
2653 #endif
2654 thread_thaw(codec_thread_id);
2655 thread_thaw(audio_thread_id);
2657 } /* audio_init */
2659 bool audio_is_thread_ready(void)
2661 return audio_thread_ready;