Add the Lua scripting language plugin to the manual.
[maemo-rb.git] / apps / playback.c
blob16c04e1f5bce1d467ce84b3d9cc60e0c55febf2a
1 /***************************************************************************
2 * __________ __ ___.
3 * Open \______ \ ____ ____ | | _\_ |__ _______ ___
4 * Source | _// _ \_/ ___\| |/ /| __ \ / _ \ \/ /
5 * Jukebox | | ( <_> ) \___| < | \_\ ( <_> > < <
6 * Firmware |____|_ /\____/ \___ >__|_ \|___ /\____/__/\_ \
7 * \/ \/ \/ \/ \/
8 * $Id$
10 * Copyright (C) 2005-2007 Miika Pekkarinen
11 * Copyright (C) 2007-2008 Nicolas Pennequin
13 * This program is free software; you can redistribute it and/or
14 * modify it under the terms of the GNU General Public License
15 * as published by the Free Software Foundation; either version 2
16 * of the License, or (at your option) any later version.
18 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
19 * KIND, either express or implied.
21 ****************************************************************************/
23 /* TODO: Pause should be handled in here, rather than PCMBUF so that voice can
24 * play whilst audio is paused */
26 #include <stdio.h>
27 #include <string.h>
28 #include <stdlib.h>
29 #include <ctype.h>
31 #include "system.h"
32 #include "thread.h"
33 #include "file.h"
34 #include "panic.h"
35 #include "memory.h"
36 #include "lcd.h"
37 #include "font.h"
38 #include "button.h"
39 #include "kernel.h"
40 #include "tree.h"
41 #include "debug.h"
42 #include "sprintf.h"
43 #include "settings.h"
44 #include "codecs.h"
45 #include "audio.h"
46 #include "buffering.h"
47 #include "appevents.h"
48 #include "voice_thread.h"
49 #include "mp3_playback.h"
50 #include "usb.h"
51 #include "storage.h"
52 #include "screens.h"
53 #include "playlist.h"
54 #include "playback.h"
55 #include "pcmbuf.h"
56 #include "buffer.h"
57 #include "dsp.h"
58 #include "abrepeat.h"
59 #include "cuesheet.h"
60 #ifdef HAVE_TAGCACHE
61 #include "tagcache.h"
62 #endif
63 #ifdef HAVE_LCD_BITMAP
64 #include "icons.h"
65 #include "peakmeter.h"
66 #include "action.h"
67 #include "albumart.h"
68 #endif
69 #include "lang.h"
70 #include "bookmark.h"
71 #include "misc.h"
72 #include "sound.h"
73 #include "metadata.h"
74 #include "splash.h"
75 #include "talk.h"
76 #include "ata_idle_notify.h"
78 #ifdef HAVE_RECORDING
79 #include "recording.h"
80 #include "pcm_record.h"
81 #endif
83 #ifdef IPOD_ACCESSORY_PROTOCOL
84 #include "iap.h"
85 #endif
87 #define PLAYBACK_VOICE
89 /* amount of guess-space to allow for codecs that must hunt and peck
90 * for their correct seeek target, 32k seems a good size */
91 #define AUDIO_REBUFFER_GUESS_SIZE (1024*32)
93 /* Define LOGF_ENABLE to enable logf output in this file */
94 /*#define LOGF_ENABLE*/
95 #include "logf.h"
97 /* macros to enable logf for queues
98 logging on SYS_TIMEOUT can be disabled */
99 #ifdef SIMULATOR
100 /* Define this for logf output of all queuing except SYS_TIMEOUT */
101 #define PLAYBACK_LOGQUEUES
102 /* Define this to logf SYS_TIMEOUT messages */
103 /*#define PLAYBACK_LOGQUEUES_SYS_TIMEOUT*/
104 #endif
106 #ifdef PLAYBACK_LOGQUEUES
107 #define LOGFQUEUE logf
108 #else
109 #define LOGFQUEUE(...)
110 #endif
112 #ifdef PLAYBACK_LOGQUEUES_SYS_TIMEOUT
113 #define LOGFQUEUE_SYS_TIMEOUT logf
114 #else
115 #define LOGFQUEUE_SYS_TIMEOUT(...)
116 #endif
119 /* Define one constant that includes recording related functionality */
120 #if defined(HAVE_RECORDING) && !defined(SIMULATOR)
121 #define AUDIO_HAVE_RECORDING
122 #endif
124 enum {
125 Q_NULL = 0,
126 Q_AUDIO_PLAY = 1,
127 Q_AUDIO_STOP,
128 Q_AUDIO_PAUSE,
129 Q_AUDIO_SKIP,
130 Q_AUDIO_PRE_FF_REWIND,
131 Q_AUDIO_FF_REWIND,
132 Q_AUDIO_CHECK_NEW_TRACK,
133 Q_AUDIO_FLUSH,
134 Q_AUDIO_TRACK_CHANGED,
135 Q_AUDIO_DIR_SKIP,
136 Q_AUDIO_POSTINIT,
137 Q_AUDIO_FILL_BUFFER,
138 Q_AUDIO_FINISH_LOAD,
139 Q_CODEC_REQUEST_COMPLETE,
140 Q_CODEC_REQUEST_FAILED,
142 Q_CODEC_LOAD,
143 Q_CODEC_LOAD_DISK,
145 #ifdef AUDIO_HAVE_RECORDING
146 Q_ENCODER_LOAD_DISK,
147 Q_ENCODER_RECORD,
148 #endif
150 Q_CODEC_DO_CALLBACK,
153 enum filling_state {
154 STATE_IDLE, /* audio is stopped: nothing to do */
155 STATE_FILLING, /* adding tracks to the buffer */
156 STATE_FULL, /* can't add any more tracks */
157 STATE_END_OF_PLAYLIST, /* all remaining tracks have been added */
158 STATE_FINISHED, /* all remaining tracks are fully buffered */
161 #define MAX_TRACK 128
163 #define MAX_TRACK_MASK (MAX_TRACK-1)
165 /* As defined in plugins/lib/xxx2wav.h */
166 #define GUARD_BUFSIZE (32*1024)
168 /* As defined in plugin.lds */
169 #if defined(CPU_PP)
170 #define CODEC_IRAM_ORIGIN ((unsigned char *)0x4000c000)
171 #define CODEC_IRAM_SIZE ((size_t)0xc000)
172 #elif defined(IAUDIO_X5) || defined(IAUDIO_M5)
173 #define CODEC_IRAM_ORIGIN ((unsigned char *)0x10010000)
174 #define CODEC_IRAM_SIZE ((size_t)0x10000)
175 #else
176 #define CODEC_IRAM_ORIGIN ((unsigned char *)0x1000c000)
177 #define CODEC_IRAM_SIZE ((size_t)0xc000)
178 #endif
180 bool audio_is_initialized = false;
181 static bool audio_thread_ready SHAREDBSS_ATTR = false;
183 /* Variables are commented with the threads that use them: *
184 * A=audio, C=codec, V=voice. A suffix of - indicates that *
185 * the variable is read but not updated on that thread. */
186 /* TBD: Split out "audio" and "playback" (ie. calling) threads */
188 /* Main state control */
189 static volatile bool audio_codec_loaded SHAREDBSS_ATTR = false; /* Codec loaded? (C/A-) */
190 static volatile bool playing SHAREDBSS_ATTR = false; /* Is audio playing? (A) */
191 static volatile bool paused SHAREDBSS_ATTR = false; /* Is audio paused? (A/C-) */
193 /* Ring buffer where compressed audio and codecs are loaded */
194 static unsigned char *filebuf = NULL; /* Start of buffer (A/C-) */
195 static unsigned char *malloc_buf = NULL; /* Start of malloc buffer (A/C-) */
196 /* FIXME: make filebuflen static */
197 size_t filebuflen = 0; /* Size of buffer (A/C-) */
198 /* FIXME: make buf_ridx (C/A-) */
200 /* Possible arrangements of the buffer */
201 static int buffer_state = AUDIOBUF_STATE_TRASHED; /* Buffer state */
203 /* These are used to store the current and next (or prev if the current is the last)
204 * mp3entry's in a round-robin system. This guarentees that the pointer returned
205 * by audio_current/next_track will be valid for the full duration of the
206 * currently playing track */
207 static struct mp3entry mp3entry_buf[2];
208 static struct mp3entry *thistrack_id3, /* the currently playing track */
209 *othertrack_id3; /* prev track during track-change-transition, or end of playlist,
210 * next track otherwise */
211 static struct mp3entry unbuffered_id3; /* the id3 for the first unbuffered track */
213 /* 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 /* Information used only for filling the buffer */
236 /* Playlist steps from playing track to next track to be buffered (A) */
237 static int last_peek_offset = 0;
239 /* Scrobbler support */
240 static unsigned long prev_track_elapsed = 0; /* Previous track elapsed time (C/A-)*/
242 static enum filling_state filling;
244 /* Track change controls */
245 static bool automatic_skip = false; /* Who initiated in-progress skip? (C/A-) */
246 static bool dir_skip = false; /* Is a directory skip pending? (A) */
247 static bool new_playlist = false; /* Are we starting a new playlist? (A) */
248 static int wps_offset = 0; /* Pending track change offset, to keep WPS responsive (A) */
249 static bool skipped_during_pause = false; /* Do we need to clear the PCM buffer when playback resumes (A) */
251 static bool start_play_g = false; /* Used by audio_load_track to notify
252 audio_finish_load_track about start_play */
254 /* True when a track load is in progress, i.e. audio_load_track() has returned
255 * but audio_finish_load_track() hasn't been called yet. Used to avoid allowing
256 * audio_load_track() to get called twice in a row, which would cause problems.
258 static bool track_load_started = false;
260 /* Set to true if the codec thread should send an audio stop request
261 * (typically because the end of the playlist has been reached).
263 static bool codec_requested_stop = false;
265 #ifdef HAVE_DISK_STORAGE
266 static size_t buffer_margin = 5; /* Buffer margin aka anti-skip buffer (A/C-) */
267 #endif
269 /* Multiple threads */
270 /* Set the watermark to trigger buffer fill (A/C) */
271 static void set_filebuf_watermark(void);
273 /* Audio thread */
274 static struct event_queue audio_queue SHAREDBSS_ATTR;
275 static struct queue_sender_list audio_queue_sender_list SHAREDBSS_ATTR;
276 static long audio_stack[(DEFAULT_STACK_SIZE + 0x1000)/sizeof(long)];
277 static const char audio_thread_name[] = "audio";
279 static void audio_thread(void);
280 static void audio_initiate_track_change(long direction);
281 static bool audio_have_tracks(void);
282 static void audio_reset_buffer(void);
283 static void audio_stop_playback(void);
285 /* Codec thread */
286 extern struct codec_api ci;
287 static struct event_queue codec_queue SHAREDBSS_ATTR;
288 static struct queue_sender_list codec_queue_sender_list;
289 static long codec_stack[(DEFAULT_STACK_SIZE + 0x2000)/sizeof(long)]
290 IBSS_ATTR;
291 static const char codec_thread_name[] = "codec";
292 unsigned int codec_thread_id; /* For modifying thread priority later. */
294 /* PCM buffer messaging */
295 static struct event_queue pcmbuf_queue SHAREDBSS_ATTR;
297 /* Function to be called by pcm buffer callbacks.
298 * Permissible Context(s): Audio interrupt
300 static void pcmbuf_callback_queue_post(long id, intptr_t data)
302 /* No lock since we're already in audio interrupt context */
303 queue_post(&pcmbuf_queue, id, data);
306 /* Scan the pcmbuf queue and return true if a message pulled.
307 * Permissible Context(s): Thread
309 static bool pcmbuf_queue_scan(struct queue_event *ev)
311 if (!queue_empty(&pcmbuf_queue))
313 /* Transfer message to audio queue */
314 pcm_play_lock();
315 /* Pull message - never, ever any blocking call! */
316 queue_wait_w_tmo(&pcmbuf_queue, ev, 0);
317 pcm_play_unlock();
318 return true;
321 return false;
324 /* Clear the pcmbuf queue of messages
325 * Permissible Context(s): Thread
327 static void pcmbuf_queue_clear(void)
329 pcm_play_lock();
330 queue_clear(&pcmbuf_queue);
331 pcm_play_unlock();
334 /* --- Helper functions --- */
336 static struct mp3entry *bufgetid3(int handle_id)
338 if (handle_id < 0)
339 return NULL;
341 struct mp3entry *id3;
342 ssize_t ret = bufgetdata(handle_id, 0, (void *)&id3);
344 if (ret < 0 || ret != sizeof(struct mp3entry))
345 return NULL;
347 return id3;
350 static bool clear_track_info(struct track_info *track)
352 /* bufclose returns true if the handle is not found, or if it is closed
353 * successfully, so these checks are safe on non-existant handles */
354 if (!track)
355 return false;
357 if (track->codec_hid >= 0) {
358 if (bufclose(track->codec_hid))
359 track->codec_hid = -1;
360 else
361 return false;
364 if (track->id3_hid >= 0) {
365 if (bufclose(track->id3_hid))
366 track->id3_hid = -1;
367 else
368 return false;
371 if (track->audio_hid >= 0) {
372 if (bufclose(track->audio_hid))
373 track->audio_hid = -1;
374 else
375 return false;
378 #ifdef HAVE_ALBUMART
379 if (track->aa_hid >= 0) {
380 if (bufclose(track->aa_hid))
381 track->aa_hid = -1;
382 else
383 return false;
385 #endif
387 track->filesize = 0;
388 track->taginfo_ready = false;
390 return true;
393 /* --- External interfaces --- */
395 /* This sends a stop message and the audio thread will dump all it's
396 subsequenct messages */
397 void audio_hard_stop(void)
399 /* Stop playback */
400 LOGFQUEUE("audio >| audio Q_AUDIO_STOP: 1");
401 queue_send(&audio_queue, Q_AUDIO_STOP, 1);
402 #ifdef PLAYBACK_VOICE
403 voice_stop();
404 #endif
407 bool audio_restore_playback(int type)
409 switch (type)
411 case AUDIO_WANT_PLAYBACK:
412 if (buffer_state != AUDIOBUF_STATE_INITIALIZED)
413 audio_reset_buffer();
414 return true;
415 case AUDIO_WANT_VOICE:
416 if (buffer_state == AUDIOBUF_STATE_TRASHED)
417 audio_reset_buffer();
418 return true;
419 default:
420 return false;
424 unsigned char *audio_get_buffer(bool talk_buf, size_t *buffer_size)
426 unsigned char *buf, *end;
428 if (audio_is_initialized)
430 audio_hard_stop();
432 /* else buffer_state will be AUDIOBUF_STATE_TRASHED at this point */
434 /* Reset the buffering thread so that it doesn't try to use the data */
435 buffering_reset(filebuf, filebuflen);
437 if (buffer_size == NULL)
439 /* Special case for talk_init to use since it already knows it's
440 trashed */
441 buffer_state = AUDIOBUF_STATE_TRASHED;
442 return NULL;
445 if (talk_buf || buffer_state == AUDIOBUF_STATE_TRASHED
446 || !talk_voice_required())
448 logf("get buffer: talk, audio");
449 /* Ok to use everything from audiobuf to audiobufend - voice is loaded,
450 the talk buffer is not needed because voice isn't being used, or
451 could be AUDIOBUF_STATE_TRASHED already. If state is
452 AUDIOBUF_STATE_VOICED_ONLY, no problem as long as memory isn't written
453 without the caller knowing what's going on. Changing certain settings
454 may move it to a worse condition but the memory in use by something
455 else will remain undisturbed.
457 if (buffer_state != AUDIOBUF_STATE_TRASHED)
459 talk_buffer_steal();
460 buffer_state = AUDIOBUF_STATE_TRASHED;
463 buf = audiobuf;
464 end = audiobufend;
466 else
468 /* Safe to just return this if already AUDIOBUF_STATE_VOICED_ONLY or
469 still AUDIOBUF_STATE_INITIALIZED */
470 /* Skip talk buffer and move pcm buffer to end to maximize available
471 contiguous memory - no audio running means voice will not need the
472 swap space */
473 logf("get buffer: audio");
474 buf = audiobuf + talk_get_bufsize();
475 end = audiobufend - pcmbuf_init(audiobufend);
476 buffer_state = AUDIOBUF_STATE_VOICED_ONLY;
479 *buffer_size = end - buf;
481 return buf;
484 int audio_buffer_state(void)
486 return buffer_state;
489 #ifdef HAVE_RECORDING
490 unsigned char *audio_get_recording_buffer(size_t *buffer_size)
492 /* Stop audio, voice and obtain all available buffer space */
493 audio_hard_stop();
494 talk_buffer_steal();
496 unsigned char *end = audiobufend;
497 buffer_state = AUDIOBUF_STATE_TRASHED;
498 *buffer_size = end - audiobuf;
500 return (unsigned char *)audiobuf;
503 bool audio_load_encoder(int afmt)
505 #ifndef SIMULATOR
506 const char *enc_fn = get_codec_filename(afmt | CODEC_TYPE_ENCODER);
507 if (!enc_fn)
508 return false;
510 audio_remove_encoder();
511 ci.enc_codec_loaded = 0; /* clear any previous error condition */
513 LOGFQUEUE("codec > Q_ENCODER_LOAD_DISK");
514 queue_post(&codec_queue, Q_ENCODER_LOAD_DISK, (intptr_t)enc_fn);
516 while (ci.enc_codec_loaded == 0)
517 yield();
519 logf("codec loaded: %d", ci.enc_codec_loaded);
521 return ci.enc_codec_loaded > 0;
522 #else
523 (void)afmt;
524 return true;
525 #endif
526 } /* audio_load_encoder */
528 void audio_remove_encoder(void)
530 #ifndef SIMULATOR
531 /* force encoder codec unload (if currently loaded) */
532 if (ci.enc_codec_loaded <= 0)
533 return;
535 ci.stop_encoder = true;
536 while (ci.enc_codec_loaded > 0)
537 yield();
538 #endif
539 } /* audio_remove_encoder */
541 #endif /* HAVE_RECORDING */
543 #ifdef HAVE_ALBUMART
544 int audio_current_aa_hid(void)
546 int cur_idx;
547 int offset = ci.new_track + wps_offset;
549 cur_idx = track_ridx + offset;
550 cur_idx &= MAX_TRACK_MASK;
552 return tracks[cur_idx].aa_hid;
554 #endif
556 struct mp3entry* audio_current_track(void)
558 const char *filename;
559 struct playlist_track_info trackinfo;
560 int cur_idx;
561 int offset = ci.new_track + wps_offset;
562 struct mp3entry *write_id3;
564 cur_idx = (track_ridx + offset) & MAX_TRACK_MASK;
566 if (cur_idx == track_ridx && *thistrack_id3->path)
568 /* The usual case */
569 return thistrack_id3;
571 else if (automatic_skip && offset == -1 && *othertrack_id3->path)
573 /* We're in a track transition. The codec has moved on to the next track,
574 but the audio being played is still the same (now previous) track.
575 othertrack_id3.elapsed is being updated in an ISR by
576 codec_pcmbuf_position_callback */
577 return othertrack_id3;
580 if (offset != 0)
582 /* Codec may be using thistrack_id3, so it must not be overwritten.
583 If this is a manual skip, othertrack_id3 will become
584 thistrack_id3 in audio_check_new_track().
585 FIXME: If this is an automatic skip, it probably means multiple
586 short tracks fit in the PCM buffer. Overwriting othertrack_id3
587 can lead to an incorrect value later.
588 Note that othertrack_id3 may also be used for next track.
590 write_id3 = othertrack_id3;
592 else
594 write_id3 = thistrack_id3;
597 if (tracks[cur_idx].id3_hid >= 0)
599 /* The current track's info has been buffered but not read yet, so get it */
600 if (bufread(tracks[cur_idx].id3_hid, sizeof(struct mp3entry), write_id3)
601 == sizeof(struct mp3entry))
602 return write_id3;
605 /* We didn't find the ID3 metadata, so we fill temp_id3 with the little info
606 we have and return that. */
608 memset(write_id3, 0, sizeof(struct mp3entry));
610 playlist_get_track_info(NULL, playlist_next(0)+wps_offset, &trackinfo);
611 filename = trackinfo.filename;
612 if (!filename)
613 filename = "No file!";
615 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
616 if (tagcache_fill_tags(write_id3, filename))
617 return write_id3;
618 #endif
620 strncpy(write_id3->path, filename, sizeof(write_id3->path)-1);
621 write_id3->title = strrchr(write_id3->path, '/');
622 if (!write_id3->title)
623 write_id3->title = &write_id3->path[0];
624 else
625 write_id3->title++;
627 return write_id3;
630 struct mp3entry* audio_next_track(void)
632 int next_idx;
633 int offset = ci.new_track + wps_offset;
635 if (!audio_have_tracks())
636 return NULL;
638 if (wps_offset == -1 && *thistrack_id3->path)
640 /* We're in a track transition. The next track for the WPS is the one
641 currently being decoded. */
642 return thistrack_id3;
645 next_idx = (track_ridx + offset + 1) & MAX_TRACK_MASK;
647 if (tracks[next_idx].id3_hid >= 0)
649 if (bufread(tracks[next_idx].id3_hid, sizeof(struct mp3entry), othertrack_id3)
650 == sizeof(struct mp3entry))
651 return othertrack_id3;
652 else
653 return NULL;
656 if (next_idx == track_widx)
658 /* The next track hasn't been buffered yet, so we return the static
659 version of its metadata. */
660 return &unbuffered_id3;
663 return NULL;
666 void audio_play(long offset)
668 logf("audio_play");
670 #ifdef PLAYBACK_VOICE
671 /* Truncate any existing voice output so we don't have spelling
672 * etc. over the first part of the played track */
673 talk_force_shutup();
674 #endif
676 /* Start playback */
677 LOGFQUEUE("audio >| audio Q_AUDIO_PLAY: %ld", offset);
678 /* Don't return until playback has actually started */
679 queue_send(&audio_queue, Q_AUDIO_PLAY, offset);
682 void audio_stop(void)
684 /* Stop playback */
685 LOGFQUEUE("audio >| audio Q_AUDIO_STOP");
686 /* Don't return until playback has actually stopped */
687 queue_send(&audio_queue, Q_AUDIO_STOP, 0);
690 void audio_pause(void)
692 LOGFQUEUE("audio >| audio Q_AUDIO_PAUSE");
693 /* Don't return until playback has actually paused */
694 queue_send(&audio_queue, Q_AUDIO_PAUSE, true);
697 void audio_resume(void)
699 LOGFQUEUE("audio >| audio Q_AUDIO_PAUSE resume");
700 /* Don't return until playback has actually resumed */
701 queue_send(&audio_queue, Q_AUDIO_PAUSE, false);
704 void audio_skip(int direction)
706 if (playlist_check(ci.new_track + wps_offset + direction))
708 if (global_settings.beep)
709 pcmbuf_beep(2000, 100, 2500*global_settings.beep);
711 LOGFQUEUE("audio > audio Q_AUDIO_SKIP %d", direction);
712 queue_post(&audio_queue, Q_AUDIO_SKIP, direction);
713 /* Update wps while our message travels inside deep playback queues. */
714 wps_offset += direction;
716 else
718 /* No more tracks. */
719 if (global_settings.beep)
720 pcmbuf_beep(1000, 100, 1500*global_settings.beep);
724 void audio_next(void)
726 audio_skip(1);
729 void audio_prev(void)
731 audio_skip(-1);
734 void audio_next_dir(void)
736 LOGFQUEUE("audio > audio Q_AUDIO_DIR_SKIP 1");
737 queue_post(&audio_queue, Q_AUDIO_DIR_SKIP, 1);
740 void audio_prev_dir(void)
742 LOGFQUEUE("audio > audio Q_AUDIO_DIR_SKIP -1");
743 queue_post(&audio_queue, Q_AUDIO_DIR_SKIP, -1);
746 void audio_pre_ff_rewind(void)
748 LOGFQUEUE("audio > audio Q_AUDIO_PRE_FF_REWIND");
749 queue_post(&audio_queue, Q_AUDIO_PRE_FF_REWIND, 0);
752 void audio_ff_rewind(long newpos)
754 LOGFQUEUE("audio > audio Q_AUDIO_FF_REWIND");
755 queue_post(&audio_queue, Q_AUDIO_FF_REWIND, newpos);
758 void audio_flush_and_reload_tracks(void)
760 LOGFQUEUE("audio > audio Q_AUDIO_FLUSH");
761 queue_post(&audio_queue, Q_AUDIO_FLUSH, 0);
764 void audio_error_clear(void)
766 #ifdef AUDIO_HAVE_RECORDING
767 pcm_rec_error_clear();
768 #endif
771 int audio_status(void)
773 int ret = 0;
775 if (playing)
776 ret |= AUDIO_STATUS_PLAY;
778 if (paused)
779 ret |= AUDIO_STATUS_PAUSE;
781 #ifdef HAVE_RECORDING
782 /* Do this here for constitency with mpeg.c version */
783 ret |= pcm_rec_status();
784 #endif
786 return ret;
789 int audio_get_file_pos(void)
791 return 0;
794 #ifdef HAVE_DISK_STORAGE
795 void audio_set_buffer_margin(int setting)
797 static const unsigned short lookup[] = {5, 15, 30, 60, 120, 180, 300, 600};
798 buffer_margin = lookup[setting];
799 logf("buffer margin: %ld", (long)buffer_margin);
800 set_filebuf_watermark();
802 #endif
804 /* Take necessary steps to enable or disable the crossfade setting */
805 void audio_set_crossfade(int enable)
807 size_t offset;
808 bool was_playing;
809 size_t size;
811 /* Tell it the next setting to use */
812 pcmbuf_crossfade_enable(enable);
814 /* Return if size hasn't changed or this is too early to determine
815 which in the second case there's no way we could be playing
816 anything at all */
817 if (pcmbuf_is_same_size())
819 /* This function is a copout and just syncs some variables -
820 to be removed at a later date */
821 pcmbuf_crossfade_enable_finished();
822 return;
825 offset = 0;
826 was_playing = playing;
828 /* Playback has to be stopped before changing the buffer size */
829 if (was_playing)
831 /* Store the track resume position */
832 offset = thistrack_id3->offset;
835 /* Blast it - audio buffer will have to be setup again next time
836 something plays */
837 audio_get_buffer(true, &size);
839 /* Restart playback if audio was running previously */
840 if (was_playing)
841 audio_play(offset);
844 /* --- Routines called from multiple threads --- */
846 static void set_filebuf_watermark(void)
848 if (!filebuf)
849 return; /* Audio buffers not yet set up */
851 #ifdef HAVE_DISK_STORAGE
852 int seconds;
853 int spinup = ata_spinup_time();
854 if (spinup)
855 seconds = (spinup / HZ) + 1;
856 else
857 seconds = 5;
859 seconds += buffer_margin;
860 #else
861 /* flash storage */
862 int seconds = 1;
863 #endif
865 /* bitrate of last track in buffer dictates watermark */
866 struct mp3entry* id3 = NULL;
867 if (tracks[track_widx].taginfo_ready)
868 id3 = bufgetid3(tracks[track_widx].id3_hid);
869 else
870 id3 = bufgetid3(tracks[track_widx-1].id3_hid);
871 if (!id3) {
872 logf("fwmark: No id3 for last track (r%d/w%d), aborting!", track_ridx, track_widx);
873 return;
875 size_t bytes = id3->bitrate * (1000/8) * seconds;
876 buf_set_watermark(bytes);
877 logf("fwmark: %d", bytes);
880 const char *get_codec_filename(int cod_spec)
882 const char *fname;
884 #ifdef HAVE_RECORDING
885 /* Can choose decoder or encoder if one available */
886 int type = cod_spec & CODEC_TYPE_MASK;
887 int afmt = cod_spec & CODEC_AFMT_MASK;
889 if ((unsigned)afmt >= AFMT_NUM_CODECS)
890 type = AFMT_UNKNOWN | (type & CODEC_TYPE_MASK);
892 fname = (type == CODEC_TYPE_ENCODER) ?
893 audio_formats[afmt].codec_enc_root_fn :
894 audio_formats[afmt].codec_root_fn;
896 logf("%s: %d - %s",
897 (type == CODEC_TYPE_ENCODER) ? "Encoder" : "Decoder",
898 afmt, fname ? fname : "<unknown>");
899 #else /* !HAVE_RECORDING */
900 /* Always decoder */
901 if ((unsigned)cod_spec >= AFMT_NUM_CODECS)
902 cod_spec = AFMT_UNKNOWN;
903 fname = audio_formats[cod_spec].codec_root_fn;
904 logf("Codec: %d - %s", cod_spec, fname ? fname : "<unknown>");
905 #endif /* HAVE_RECORDING */
907 return fname;
908 } /* get_codec_filename */
910 /* --- Codec thread --- */
911 static bool codec_pcmbuf_insert_callback(
912 const void *ch1, const void *ch2, int count)
914 const char *src[2] = { ch1, ch2 };
916 while (count > 0)
918 int out_count = dsp_output_count(ci.dsp, count);
919 int inp_count;
920 char *dest;
922 /* Prevent audio from a previous track from playing */
923 if (ci.new_track || ci.stop_codec)
924 return true;
926 while ((dest = pcmbuf_request_buffer(&out_count)) == NULL)
928 cancel_cpu_boost();
929 sleep(1);
930 if (ci.seek_time || ci.new_track || ci.stop_codec)
931 return true;
934 /* Get the real input_size for output_size bytes, guarding
935 * against resampling buffer overflows. */
936 inp_count = dsp_input_count(ci.dsp, out_count);
938 if (inp_count <= 0)
939 return true;
941 /* Input size has grown, no error, just don't write more than length */
942 if (inp_count > count)
943 inp_count = count;
945 out_count = dsp_process(ci.dsp, dest, src, inp_count);
947 if (out_count <= 0)
948 return true;
950 pcmbuf_write_complete(out_count);
952 count -= inp_count;
955 return true;
956 } /* codec_pcmbuf_insert_callback */
958 static void* codec_get_buffer(size_t *size)
960 if (codec_size >= CODEC_SIZE)
961 return NULL;
962 *size = CODEC_SIZE - codec_size;
963 return &codecbuf[codec_size];
966 /* Between the codec and PCM track change, we need to keep updating the
967 "elapsed" value of the previous (to the codec, but current to the
968 user/PCM/WPS) track, so that the progressbar reaches the end.
969 During that transition, the WPS will display prevtrack_id3. */
970 static void codec_pcmbuf_position_callback(size_t size) ICODE_ATTR;
971 static void codec_pcmbuf_position_callback(size_t size)
973 /* This is called from an ISR, so be quick */
974 unsigned int time = size * 1000 / 4 / NATIVE_FREQUENCY +
975 othertrack_id3->elapsed;
977 if (time >= othertrack_id3->length)
979 pcmbuf_set_position_callback(NULL);
980 othertrack_id3->elapsed = othertrack_id3->length;
982 else
983 othertrack_id3->elapsed = time;
986 static void codec_set_elapsed_callback(unsigned int value)
988 unsigned int latency;
989 if (ci.seek_time)
990 return;
992 #ifdef AB_REPEAT_ENABLE
993 ab_position_report(value);
994 #endif
996 latency = pcmbuf_get_latency();
997 if (value < latency)
998 thistrack_id3->elapsed = 0;
999 else if (value - latency > thistrack_id3->elapsed ||
1000 value - latency < thistrack_id3->elapsed - 2)
1002 thistrack_id3->elapsed = value - latency;
1006 static void codec_set_offset_callback(size_t value)
1008 unsigned int latency;
1010 if (ci.seek_time)
1011 return;
1013 latency = pcmbuf_get_latency() * thistrack_id3->bitrate / 8;
1014 if (value < latency)
1015 thistrack_id3->offset = 0;
1016 else
1017 thistrack_id3->offset = value - latency;
1020 static void codec_advance_buffer_counters(size_t amount)
1022 bufadvance(CUR_TI->audio_hid, amount);
1023 ci.curpos += amount;
1026 /* copy up-to size bytes into ptr and return the actual size copied */
1027 static size_t codec_filebuf_callback(void *ptr, size_t size)
1029 ssize_t copy_n;
1031 if (ci.stop_codec || !playing)
1032 return 0;
1034 copy_n = bufread(CUR_TI->audio_hid, size, ptr);
1036 /* Nothing requested OR nothing left */
1037 if (copy_n == 0)
1038 return 0;
1040 /* Update read and other position pointers */
1041 codec_advance_buffer_counters(copy_n);
1043 /* Return the actual amount of data copied to the buffer */
1044 return copy_n;
1045 } /* codec_filebuf_callback */
1047 static void* codec_request_buffer_callback(size_t *realsize, size_t reqsize)
1049 size_t copy_n = reqsize;
1050 ssize_t ret;
1051 void *ptr;
1053 if (!playing)
1055 *realsize = 0;
1056 return NULL;
1059 ret = bufgetdata(CUR_TI->audio_hid, reqsize, &ptr);
1060 if (ret >= 0)
1061 copy_n = MIN((size_t)ret, reqsize);
1063 if (copy_n == 0)
1065 *realsize = 0;
1066 return NULL;
1069 *realsize = copy_n;
1071 return ptr;
1072 } /* codec_request_buffer_callback */
1074 static int get_codec_base_type(int type)
1076 switch (type) {
1077 case AFMT_MPA_L1:
1078 case AFMT_MPA_L2:
1079 case AFMT_MPA_L3:
1080 return AFMT_MPA_L3;
1083 return type;
1086 static void codec_advance_buffer_callback(size_t amount)
1088 codec_advance_buffer_counters(amount);
1089 codec_set_offset_callback(ci.curpos);
1092 static void codec_advance_buffer_loc_callback(void *ptr)
1094 size_t amount = buf_get_offset(CUR_TI->audio_hid, ptr);
1095 codec_advance_buffer_callback(amount);
1098 static void codec_seek_complete_callback(void)
1100 logf("seek_complete");
1101 if (pcm_is_paused())
1103 /* If this is not a seamless seek, clear the buffer */
1104 pcmbuf_play_stop();
1105 dsp_configure(ci.dsp, DSP_FLUSH, 0);
1107 /* If playback was not 'deliberately' paused, unpause now */
1108 if (!paused)
1109 pcmbuf_pause(false);
1111 ci.seek_time = 0;
1114 static bool codec_seek_buffer_callback(size_t newpos)
1116 logf("codec_seek_buffer_callback");
1118 int ret = bufseek(CUR_TI->audio_hid, newpos);
1119 if (ret == 0) {
1120 ci.curpos = newpos;
1121 return true;
1123 else {
1124 return false;
1128 static void codec_configure_callback(int setting, intptr_t value)
1130 switch (setting) {
1131 default:
1132 if (!dsp_configure(ci.dsp, setting, value))
1133 { logf("Illegal key:%d", setting); }
1137 static void codec_track_changed(void)
1139 LOGFQUEUE("codec > audio Q_AUDIO_TRACK_CHANGED");
1140 queue_post(&audio_queue, Q_AUDIO_TRACK_CHANGED, 0);
1143 static void codec_pcmbuf_track_changed_callback(void)
1145 pcmbuf_set_position_callback(NULL);
1146 pcmbuf_callback_queue_post(Q_AUDIO_TRACK_CHANGED, 0);
1149 static void codec_discard_codec_callback(void)
1151 if (CUR_TI->codec_hid >= 0)
1153 bufclose(CUR_TI->codec_hid);
1154 CUR_TI->codec_hid = -1;
1158 static inline void codec_gapless_track_change(void)
1160 /* callback keeps the progress bar moving while the pcmbuf empties */
1161 pcmbuf_set_position_callback(codec_pcmbuf_position_callback);
1162 /* set the pcmbuf callback for when the track really changes */
1163 pcmbuf_set_event_handler(codec_pcmbuf_track_changed_callback);
1166 static inline void codec_crossfade_track_change(void)
1168 /* Initiate automatic crossfade mode */
1169 pcmbuf_crossfade_init(false);
1170 /* Notify the wps that the track change starts now */
1171 codec_track_changed();
1174 static void codec_track_skip_done(bool was_manual)
1176 /* Manual track change (always crossfade or flush audio). */
1177 if (was_manual)
1179 pcmbuf_crossfade_init(true);
1180 LOGFQUEUE("codec > audio Q_AUDIO_TRACK_CHANGED");
1181 queue_post(&audio_queue, Q_AUDIO_TRACK_CHANGED, 0);
1183 /* Automatic track change w/crossfade, if not in "Track Skip Only" mode. */
1184 else if (pcmbuf_is_crossfade_enabled() && !pcmbuf_is_crossfade_active()
1185 && global_settings.crossfade != CROSSFADE_ENABLE_TRACKSKIP)
1187 if (global_settings.crossfade == CROSSFADE_ENABLE_SHUFFLE_AND_TRACKSKIP)
1189 if (global_settings.playlist_shuffle)
1190 /* shuffle mode is on, so crossfade: */
1191 codec_crossfade_track_change();
1192 else
1193 /* shuffle mode is off, so do a gapless track change */
1194 codec_gapless_track_change();
1196 else
1197 /* normal crossfade: */
1198 codec_crossfade_track_change();
1200 else
1201 /* normal gapless playback. */
1202 codec_gapless_track_change();
1205 static bool codec_load_next_track(void)
1207 intptr_t result = Q_CODEC_REQUEST_FAILED;
1209 prev_track_elapsed = thistrack_id3->elapsed;
1211 #ifdef AB_REPEAT_ENABLE
1212 ab_end_of_track_report();
1213 #endif
1215 logf("Request new track");
1217 if (ci.new_track == 0)
1219 ci.new_track++;
1220 automatic_skip = true;
1223 if (!ci.stop_codec)
1225 trigger_cpu_boost();
1226 LOGFQUEUE("codec >| audio Q_AUDIO_CHECK_NEW_TRACK");
1227 result = queue_send(&audio_queue, Q_AUDIO_CHECK_NEW_TRACK, 0);
1230 switch (result)
1232 case Q_CODEC_REQUEST_COMPLETE:
1233 LOGFQUEUE("codec |< Q_CODEC_REQUEST_COMPLETE");
1234 codec_track_skip_done(!automatic_skip);
1235 return true;
1237 case Q_CODEC_REQUEST_FAILED:
1238 LOGFQUEUE("codec |< Q_CODEC_REQUEST_FAILED");
1239 ci.new_track = 0;
1240 ci.stop_codec = true;
1241 codec_requested_stop = true;
1242 return false;
1244 default:
1245 LOGFQUEUE("codec |< default");
1246 ci.stop_codec = true;
1247 codec_requested_stop = true;
1248 return false;
1252 static bool codec_request_next_track_callback(void)
1254 int prev_codectype;
1256 if (ci.stop_codec || !playing)
1257 return false;
1259 prev_codectype = get_codec_base_type(thistrack_id3->codectype);
1260 if (!codec_load_next_track())
1261 return false;
1263 /* Seek to the beginning of the new track because if the struct
1264 mp3entry was buffered, "elapsed" might not be zero (if the track has
1265 been played already but not unbuffered) */
1266 codec_seek_buffer_callback(thistrack_id3->first_frame_offset);
1267 /* Check if the next codec is the same file. */
1268 if (prev_codectype == get_codec_base_type(thistrack_id3->codectype))
1270 logf("New track loaded");
1271 codec_discard_codec_callback();
1272 return true;
1274 else
1276 logf("New codec:%d/%d", thistrack_id3->codectype, prev_codectype);
1277 return false;
1281 static void codec_thread(void)
1283 struct queue_event ev;
1284 int status;
1286 while (1) {
1287 status = 0;
1289 if (!pcmbuf_is_crossfade_active()) {
1290 cancel_cpu_boost();
1293 queue_wait(&codec_queue, &ev);
1294 codec_requested_stop = false;
1296 switch (ev.id) {
1297 case Q_CODEC_LOAD_DISK:
1298 LOGFQUEUE("codec < Q_CODEC_LOAD_DISK");
1299 queue_reply(&codec_queue, 1);
1300 audio_codec_loaded = true;
1301 ci.stop_codec = false;
1302 status = codec_load_file((const char *)ev.data, &ci);
1303 LOGFQUEUE("codec_load_file %s %d\n", (const char *)ev.data, status);
1304 break;
1306 case Q_CODEC_LOAD:
1307 LOGFQUEUE("codec < Q_CODEC_LOAD");
1308 if (CUR_TI->codec_hid < 0) {
1309 logf("Codec slot is empty!");
1310 /* Wait for the pcm buffer to go empty */
1311 while (pcm_is_playing())
1312 yield();
1313 /* This must be set to prevent an infinite loop */
1314 ci.stop_codec = true;
1315 LOGFQUEUE("codec > codec Q_AUDIO_PLAY");
1316 queue_post(&codec_queue, Q_AUDIO_PLAY, 0);
1317 break;
1320 audio_codec_loaded = true;
1321 ci.stop_codec = false;
1322 status = codec_load_buf(CUR_TI->codec_hid, &ci);
1323 LOGFQUEUE("codec_load_buf %d\n", status);
1324 break;
1326 case Q_CODEC_DO_CALLBACK:
1327 LOGFQUEUE("codec < Q_CODEC_DO_CALLBACK");
1328 queue_reply(&codec_queue, 1);
1329 if ((void*)ev.data != NULL)
1331 cpucache_invalidate();
1332 ((void (*)(void))ev.data)();
1333 cpucache_flush();
1335 break;
1337 #ifdef AUDIO_HAVE_RECORDING
1338 case Q_ENCODER_LOAD_DISK:
1339 LOGFQUEUE("codec < Q_ENCODER_LOAD_DISK");
1340 audio_codec_loaded = false; /* Not audio codec! */
1341 logf("loading encoder");
1342 ci.stop_encoder = false;
1343 status = codec_load_file((const char *)ev.data, &ci);
1344 logf("encoder stopped");
1345 break;
1346 #endif /* AUDIO_HAVE_RECORDING */
1348 default:
1349 LOGFQUEUE("codec < default");
1352 if (audio_codec_loaded)
1354 if (ci.stop_codec)
1356 status = CODEC_OK;
1357 if (!playing)
1358 pcmbuf_play_stop();
1361 audio_codec_loaded = false;
1364 switch (ev.id) {
1365 case Q_CODEC_LOAD_DISK:
1366 case Q_CODEC_LOAD:
1367 LOGFQUEUE("codec < Q_CODEC_LOAD");
1368 if (playing)
1370 if (ci.new_track || status != CODEC_OK)
1372 if (!ci.new_track)
1374 logf("Codec failure, %d %d", ci.new_track, status);
1375 splash(HZ*2, "Codec failure");
1378 if (!codec_load_next_track())
1380 LOGFQUEUE("codec > audio Q_AUDIO_STOP");
1381 /* End of playlist */
1382 queue_post(&audio_queue, Q_AUDIO_STOP, 0);
1383 break;
1386 else
1388 logf("Codec finished");
1389 if (ci.stop_codec)
1391 /* Wait for the audio to stop playing before
1392 * triggering the WPS exit */
1393 while(pcm_is_playing())
1395 /* There has been one too many struct pointer swaps by now
1396 * so even though it says othertrack_id3, its the correct one! */
1397 othertrack_id3->elapsed =
1398 othertrack_id3->length - pcmbuf_get_latency();
1399 sleep(1);
1402 if (codec_requested_stop)
1404 LOGFQUEUE("codec > audio Q_AUDIO_STOP");
1405 queue_post(&audio_queue, Q_AUDIO_STOP, 0);
1407 break;
1411 if (CUR_TI->codec_hid >= 0)
1413 LOGFQUEUE("codec > codec Q_CODEC_LOAD");
1414 queue_post(&codec_queue, Q_CODEC_LOAD, 0);
1416 else
1418 const char *codec_fn =
1419 get_codec_filename(thistrack_id3->codectype);
1420 if (codec_fn)
1422 LOGFQUEUE("codec > codec Q_CODEC_LOAD_DISK");
1423 queue_post(&codec_queue, Q_CODEC_LOAD_DISK,
1424 (intptr_t)codec_fn);
1428 break;
1430 #ifdef AUDIO_HAVE_RECORDING
1431 case Q_ENCODER_LOAD_DISK:
1432 LOGFQUEUE("codec < Q_ENCODER_LOAD_DISK");
1434 if (status == CODEC_OK)
1435 break;
1437 logf("Encoder failure");
1438 splash(HZ*2, "Encoder failure");
1440 if (ci.enc_codec_loaded < 0)
1441 break;
1443 logf("Encoder failed to load");
1444 ci.enc_codec_loaded = -1;
1445 break;
1446 #endif /* AUDIO_HAVE_RECORDING */
1448 default:
1449 LOGFQUEUE("codec < default");
1451 } /* end switch */
1455 /* Borrow the codec thread and return the ID */
1456 void codec_thread_do_callback(void (*fn)(void), unsigned int *id)
1458 /* Set id before telling thread to call something; it may be
1459 * needed before this function returns. */
1460 if (id != NULL)
1461 *id = codec_thread_id;
1463 /* Codec thread will signal just before entering callback */
1464 LOGFQUEUE("codec >| Q_CODEC_DO_CALLBACK");
1465 queue_send(&codec_queue, Q_CODEC_DO_CALLBACK, (intptr_t)fn);
1468 /* --- Buffering callbacks --- */
1470 static void buffering_low_buffer_callback(void *data)
1472 (void)data;
1473 logf("low buffer callback");
1475 if (filling == STATE_FULL || filling == STATE_END_OF_PLAYLIST) {
1476 /* force a refill */
1477 LOGFQUEUE("buffering > audio Q_AUDIO_FILL_BUFFER");
1478 queue_post(&audio_queue, Q_AUDIO_FILL_BUFFER, 0);
1482 static void buffering_handle_rebuffer_callback(void *data)
1484 (void)data;
1485 LOGFQUEUE("audio >| audio Q_AUDIO_FLUSH");
1486 queue_post(&audio_queue, Q_AUDIO_FLUSH, 0);
1489 static void buffering_handle_finished_callback(int *data)
1491 logf("handle %d finished buffering", *data);
1493 if (*data == tracks[track_widx].id3_hid)
1495 int offset = ci.new_track + wps_offset;
1496 int next_idx = (track_ridx + offset + 1) & MAX_TRACK_MASK;
1497 /* The metadata handle for the last loaded track has been buffered.
1498 We can ask the audio thread to load the rest of the track's data. */
1499 LOGFQUEUE("audio >| audio Q_AUDIO_FINISH_LOAD");
1500 queue_post(&audio_queue, Q_AUDIO_FINISH_LOAD, 0);
1501 if (tracks[next_idx].id3_hid == *data)
1502 send_event(PLAYBACK_EVENT_NEXTTRACKID3_AVAILABLE, NULL);
1504 else
1506 /* This is most likely an audio handle, so we strip the useless
1507 trailing tags that are left. */
1508 strip_tags(*data);
1510 if (*data == tracks[track_widx-1].audio_hid
1511 && filling == STATE_END_OF_PLAYLIST)
1513 /* This was the last track in the playlist.
1514 We now have all the data we need. */
1515 logf("last track finished buffering");
1516 filling = STATE_FINISHED;
1522 /* --- Audio thread --- */
1524 static bool audio_have_tracks(void)
1526 return (audio_track_count() != 0);
1529 static int audio_free_track_count(void)
1531 /* Used tracks + free tracks adds up to MAX_TRACK - 1 */
1532 return MAX_TRACK - 1 - audio_track_count();
1535 int audio_track_count(void)
1537 /* Calculate difference from track_ridx to track_widx
1538 * taking into account a possible wrap-around. */
1539 return (MAX_TRACK + track_widx - track_ridx) & MAX_TRACK_MASK;
1542 long audio_filebufused(void)
1544 return (long) buf_used();
1547 /* Update track info after successful a codec track change */
1548 static void audio_update_trackinfo(void)
1550 /* Load the curent track's metadata into curtrack_id3 */
1551 if (CUR_TI->id3_hid >= 0)
1552 copy_mp3entry(thistrack_id3, bufgetid3(CUR_TI->id3_hid));
1554 /* Reset current position */
1555 thistrack_id3->elapsed = 0;
1556 thistrack_id3->offset = 0;
1558 /* Update the codec API */
1559 ci.filesize = CUR_TI->filesize;
1560 ci.id3 = thistrack_id3;
1561 ci.curpos = 0;
1562 ci.taginfo_ready = &CUR_TI->taginfo_ready;
1565 /* Clear tracks between write and read, non inclusive */
1566 static void audio_clear_track_entries(void)
1568 int cur_idx = track_widx;
1570 logf("Clearing tracks:%d/%d", track_ridx, track_widx);
1572 /* Loop over all tracks from write-to-read */
1573 while (1)
1575 cur_idx = (cur_idx + 1) & MAX_TRACK_MASK;
1577 if (cur_idx == track_ridx)
1578 break;
1580 clear_track_info(&tracks[cur_idx]);
1584 /* Clear all tracks */
1585 static bool audio_release_tracks(void)
1587 int i, cur_idx;
1589 logf("releasing all tracks");
1591 for(i = 0; i < MAX_TRACK; i++)
1593 cur_idx = (track_ridx + i) & MAX_TRACK_MASK;
1594 if (!clear_track_info(&tracks[cur_idx]))
1595 return false;
1598 return true;
1601 static bool audio_loadcodec(bool start_play)
1603 int prev_track;
1604 char codec_path[MAX_PATH]; /* Full path to codec */
1605 const struct mp3entry *id3, *prev_id3;
1607 if (tracks[track_widx].id3_hid < 0) {
1608 return false;
1611 id3 = bufgetid3(tracks[track_widx].id3_hid);
1612 if (!id3)
1613 return false;
1615 const char *codec_fn = get_codec_filename(id3->codectype);
1616 if (codec_fn == NULL)
1617 return false;
1619 tracks[track_widx].codec_hid = -1;
1621 if (start_play)
1623 /* Load the codec directly from disk and save some memory. */
1624 track_ridx = track_widx;
1625 ci.filesize = CUR_TI->filesize;
1626 ci.id3 = thistrack_id3;
1627 ci.taginfo_ready = &CUR_TI->taginfo_ready;
1628 ci.curpos = 0;
1629 LOGFQUEUE("codec > codec Q_CODEC_LOAD_DISK");
1630 queue_post(&codec_queue, Q_CODEC_LOAD_DISK, (intptr_t)codec_fn);
1631 return true;
1633 else
1635 /* If we already have another track than this one buffered */
1636 if (track_widx != track_ridx)
1638 prev_track = (track_widx - 1) & MAX_TRACK_MASK;
1640 id3 = bufgetid3(tracks[track_widx].id3_hid);
1641 prev_id3 = bufgetid3(tracks[prev_track].id3_hid);
1643 /* If the previous codec is the same as this one, there is no need
1644 * to put another copy of it on the file buffer */
1645 if (id3 && prev_id3 &&
1646 get_codec_base_type(id3->codectype) ==
1647 get_codec_base_type(prev_id3->codectype)
1648 && audio_codec_loaded)
1650 logf("Reusing prev. codec");
1651 return true;
1656 codec_get_full_path(codec_path, codec_fn);
1658 tracks[track_widx].codec_hid = bufopen(codec_path, 0, TYPE_CODEC);
1659 if (tracks[track_widx].codec_hid < 0)
1660 return false;
1662 logf("Loaded codec");
1664 return true;
1667 /* Load metadata for the next track (with bufopen). The rest of the track
1668 loading will be handled by audio_finish_load_track once the metadata has been
1669 actually loaded by the buffering thread. */
1670 static bool audio_load_track(size_t offset, bool start_play)
1672 const char *trackname;
1673 int fd = -1;
1675 if (track_load_started) {
1676 /* There is already a track load in progress, so track_widx hasn't been
1677 incremented yet. Loading another track would overwrite the one that
1678 hasn't finished loading. */
1679 logf("audio_load_track(): a track load is already in progress");
1680 return false;
1683 start_play_g = start_play; /* will be read by audio_finish_load_track */
1685 /* Stop buffer filling if there is no free track entries.
1686 Don't fill up the last track entry (we wan't to store next track
1687 metadata there). */
1688 if (!audio_free_track_count())
1690 logf("No free tracks");
1691 return false;
1694 last_peek_offset++;
1695 tracks[track_widx].taginfo_ready = false;
1697 logf("Buffering track:%d/%d", track_widx, track_ridx);
1698 /* Get track name from current playlist read position. */
1699 while ((trackname = playlist_peek(last_peek_offset)) != NULL)
1701 /* Handle broken playlists. */
1702 fd = open(trackname, O_RDONLY);
1703 if (fd < 0)
1705 logf("Open failed");
1706 /* Skip invalid entry from playlist. */
1707 playlist_skip_entry(NULL, last_peek_offset);
1709 else
1710 break;
1713 if (!trackname)
1715 logf("End-of-playlist");
1716 memset(&unbuffered_id3, 0, sizeof(struct mp3entry));
1717 filling = STATE_END_OF_PLAYLIST;
1719 if (thistrack_id3->length == 0 && thistrack_id3->filesize == 0)
1721 /* Stop playback if no valid track was found. */
1722 audio_stop_playback();
1725 return false;
1728 tracks[track_widx].filesize = filesize(fd);
1730 if (offset > tracks[track_widx].filesize)
1731 offset = 0;
1733 /* Set default values */
1734 if (start_play)
1736 buf_set_watermark(filebuflen/2);
1737 dsp_configure(ci.dsp, DSP_RESET, 0);
1738 playlist_update_resume_info(audio_current_track());
1741 /* Get track metadata if we don't already have it. */
1742 if (tracks[track_widx].id3_hid < 0)
1744 tracks[track_widx].id3_hid = bufopen(trackname, 0, TYPE_ID3);
1746 if (tracks[track_widx].id3_hid < 0)
1748 /* Buffer is full. */
1749 get_metadata(&unbuffered_id3, fd, trackname);
1750 last_peek_offset--;
1751 close(fd);
1752 logf("buffer is full for now");
1753 filling = STATE_FULL;
1754 return false;
1757 if (track_widx == track_ridx)
1759 /* TODO: Superfluos buffering call? */
1760 buf_request_buffer_handle(tracks[track_widx].id3_hid);
1761 struct mp3entry *id3 = bufgetid3(tracks[track_widx].id3_hid);
1762 if (id3)
1764 copy_mp3entry(thistrack_id3, id3);
1765 thistrack_id3->offset = offset;
1767 else
1768 memset(thistrack_id3, 0, sizeof(struct mp3entry));
1771 if (start_play)
1773 playlist_update_resume_info(audio_current_track());
1777 close(fd);
1778 track_load_started = true; /* Remember that we've started loading a track */
1779 return true;
1782 /* Second part of the track loading: We now have the metadata available, so we
1783 can load the codec, the album art and finally the audio data.
1784 This is called on the audio thread after the buffering thread calls the
1785 buffering_handle_finished_callback callback. */
1786 static void audio_finish_load_track(void)
1788 size_t file_offset = 0;
1789 size_t offset = 0;
1790 bool start_play = start_play_g;
1792 track_load_started = false;
1794 if (tracks[track_widx].id3_hid < 0) {
1795 logf("no metatdata");
1796 return;
1799 struct mp3entry *track_id3;
1801 if (track_widx == track_ridx)
1802 track_id3 = thistrack_id3;
1803 else
1804 track_id3 = bufgetid3(tracks[track_widx].id3_hid);
1806 if (track_id3->length == 0 && track_id3->filesize == 0)
1808 logf("audio_finish_load_track: invalid metadata");
1810 /* Invalid metadata */
1811 bufclose(tracks[track_widx].id3_hid);
1812 tracks[track_widx].id3_hid = -1;
1814 /* Skip invalid entry from playlist. */
1815 playlist_skip_entry(NULL, last_peek_offset--);
1817 /* load next track */
1818 LOGFQUEUE("audio > audio Q_AUDIO_FILL_BUFFER %d", (int)start_play);
1819 queue_post(&audio_queue, Q_AUDIO_FILL_BUFFER, start_play);
1821 return;
1824 #ifdef HAVE_ALBUMART
1825 if (tracks[track_widx].aa_hid < 0 && gui_sync_wps_uses_albumart())
1827 char aa_path[MAX_PATH];
1828 if (find_albumart(track_id3, aa_path, sizeof(aa_path)))
1830 tracks[track_widx].aa_hid = bufopen(aa_path, 0, TYPE_BITMAP);
1832 if(tracks[track_widx].aa_hid == ERR_BUFFER_FULL)
1834 filling = STATE_FULL;
1835 logf("buffer is full for now");
1836 return; /* No space for track's album art, not an error */
1838 else if (tracks[track_widx].aa_hid < 0)
1840 /* another error, ignore AlbumArt */
1841 logf("Album art loading failed");
1845 #endif
1847 /* Load the codec. */
1848 if (!audio_loadcodec(start_play))
1850 if (tracks[track_widx].codec_hid == ERR_BUFFER_FULL)
1852 /* No space for codec on buffer, not an error */
1853 filling = STATE_FULL;
1854 return;
1857 /* This is an error condition, either no codec was found, or reading
1858 * the codec file failed part way through, either way, skip the track */
1859 /* FIXME: We should not use splashf from audio thread! */
1860 splashf(HZ*2, "No codec for: %s", track_id3->path);
1861 /* Skip invalid entry from playlist. */
1862 playlist_skip_entry(NULL, last_peek_offset);
1863 return;
1866 track_id3->elapsed = 0;
1867 offset = track_id3->offset;
1869 enum data_type type = TYPE_PACKET_AUDIO;
1871 switch (track_id3->codectype) {
1872 case AFMT_MPA_L1:
1873 case AFMT_MPA_L2:
1874 case AFMT_MPA_L3:
1875 if (offset > 0) {
1876 file_offset = offset;
1877 track_id3->offset = offset;
1879 break;
1881 case AFMT_WAVPACK:
1882 if (offset > 0) {
1883 file_offset = offset;
1884 track_id3->offset = offset;
1885 track_id3->elapsed = track_id3->length / 2;
1887 break;
1889 case AFMT_OGG_VORBIS:
1890 case AFMT_SPEEX:
1891 case AFMT_FLAC:
1892 case AFMT_PCM_WAV:
1893 case AFMT_A52:
1894 case AFMT_AAC:
1895 case AFMT_MPC:
1896 case AFMT_APE:
1897 case AFMT_WMA:
1898 if (offset > 0)
1899 track_id3->offset = offset;
1900 break;
1902 case AFMT_NSF:
1903 case AFMT_SPC:
1904 case AFMT_SID:
1905 logf("Loading atomic %d",track_id3->codectype);
1906 type = TYPE_ATOMIC_AUDIO;
1907 break;
1910 logf("alt:%s", track_id3->path);
1912 if (file_offset > AUDIO_REBUFFER_GUESS_SIZE)
1913 file_offset -= AUDIO_REBUFFER_GUESS_SIZE;
1914 else if (track_id3->first_frame_offset)
1915 file_offset = track_id3->first_frame_offset;
1916 else
1917 file_offset = 0;
1919 tracks[track_widx].audio_hid = bufopen(track_id3->path, file_offset, type);
1921 /* No space left, not an error */
1922 if (tracks[track_widx].audio_hid == ERR_BUFFER_FULL)
1924 filling = STATE_FULL;
1925 logf("buffer is full for now");
1926 return;
1928 else if (tracks[track_widx].audio_hid < 0)
1930 /* another error, do not continue either */
1931 logf("Could not add audio data handle");
1932 return;
1935 /* All required data is now available for the codec. */
1936 tracks[track_widx].taginfo_ready = true;
1938 if (start_play)
1940 ci.curpos=file_offset;
1941 buf_request_buffer_handle(tracks[track_widx].audio_hid);
1944 track_widx = (track_widx + 1) & MAX_TRACK_MASK;
1946 send_event(PLAYBACK_EVENT_TRACK_BUFFER, track_id3);
1948 /* load next track */
1949 LOGFQUEUE("audio > audio Q_AUDIO_FILL_BUFFER");
1950 queue_post(&audio_queue, Q_AUDIO_FILL_BUFFER, 0);
1952 return;
1955 static void audio_fill_file_buffer(bool start_play, size_t offset)
1957 filling = STATE_FILLING;
1958 trigger_cpu_boost();
1960 /* No need to rebuffer if there are track skips pending. */
1961 if (ci.new_track != 0)
1962 return;
1964 /* Must reset the buffer before use if trashed or voice only - voice
1965 file size shouldn't have changed so we can go straight from
1966 AUDIOBUF_STATE_VOICED_ONLY to AUDIOBUF_STATE_INITIALIZED */
1967 if (buffer_state != AUDIOBUF_STATE_INITIALIZED)
1968 audio_reset_buffer();
1970 logf("Starting buffer fill");
1972 if (!start_play)
1973 audio_clear_track_entries();
1975 /* Save the current resume position once. */
1976 playlist_update_resume_info(audio_current_track());
1978 audio_load_track(offset, start_play);
1981 static void audio_rebuffer(void)
1983 logf("Forcing rebuffer");
1985 clear_track_info(CUR_TI);
1987 /* Reset track pointers */
1988 track_widx = track_ridx;
1989 audio_clear_track_entries();
1991 /* Reset a possibly interrupted track load */
1992 track_load_started = false;
1994 /* Fill the buffer */
1995 last_peek_offset = -1;
1996 ci.curpos = 0;
1998 if (!CUR_TI->taginfo_ready)
1999 memset(thistrack_id3, 0, sizeof(struct mp3entry));
2001 audio_fill_file_buffer(false, 0);
2004 /* Called on request from the codec to get a new track. This is the codec part
2005 of the track transition. */
2006 static int audio_check_new_track(void)
2008 int track_count = audio_track_count();
2009 int old_track_ridx = track_ridx;
2010 int i, idx;
2011 bool forward;
2012 struct mp3entry *temp = thistrack_id3;
2014 /* Now it's good time to send track finish events. */
2015 send_event(PLAYBACK_EVENT_TRACK_FINISH, thistrack_id3);
2016 /* swap the mp3entry pointers */
2017 thistrack_id3 = othertrack_id3;
2018 othertrack_id3 = temp;
2019 ci.id3 = thistrack_id3;
2020 memset(thistrack_id3, 0, sizeof(struct mp3entry));
2022 if (dir_skip)
2024 dir_skip = false;
2025 /* regardless of the return value we need to rebuffer.
2026 if it fails the old playlist will resume, else the
2027 next dir will start playing */
2028 playlist_next_dir(ci.new_track);
2029 ci.new_track = 0;
2030 audio_rebuffer();
2031 goto skip_done;
2034 if (new_playlist)
2035 ci.new_track = 0;
2037 /* If the playlist isn't that big */
2038 if (automatic_skip)
2040 while (!playlist_check(ci.new_track))
2042 if (ci.new_track >= 0)
2044 LOGFQUEUE("audio >|= codec Q_CODEC_REQUEST_FAILED");
2045 return Q_CODEC_REQUEST_FAILED;
2047 ci.new_track++;
2051 /* Update the playlist */
2052 last_peek_offset -= ci.new_track;
2054 if (playlist_next(ci.new_track) < 0)
2056 LOGFQUEUE("audio >|= codec Q_CODEC_REQUEST_FAILED");
2057 return Q_CODEC_REQUEST_FAILED;
2060 if (new_playlist)
2062 ci.new_track = 1;
2063 new_playlist = false;
2066 /* Save a pointer to the old track to allow later clearing */
2067 prev_ti = CUR_TI;
2069 for (i = 0; i < ci.new_track; i++)
2071 idx = (track_ridx + i) & MAX_TRACK_MASK;
2072 struct mp3entry *id3 = bufgetid3(tracks[idx].id3_hid);
2073 ssize_t offset = buf_handle_offset(tracks[idx].audio_hid);
2074 if (!id3 || offset < 0 || (unsigned)offset > id3->first_frame_offset)
2076 /* We don't have all the audio data for that track, so clear it,
2077 but keep the metadata. */
2078 if (tracks[idx].audio_hid >= 0 && bufclose(tracks[idx].audio_hid))
2080 tracks[idx].audio_hid = -1;
2081 tracks[idx].filesize = 0;
2086 /* Move to the new track */
2087 track_ridx = (track_ridx + ci.new_track) & MAX_TRACK_MASK;
2089 buf_set_base_handle(CUR_TI->audio_hid);
2091 if (automatic_skip)
2093 wps_offset = -ci.new_track;
2096 /* If it is not safe to even skip this many track entries */
2097 if (ci.new_track >= track_count || ci.new_track <= track_count - MAX_TRACK)
2099 ci.new_track = 0;
2100 audio_rebuffer();
2101 goto skip_done;
2104 forward = ci.new_track > 0;
2105 ci.new_track = 0;
2107 /* If the target track is clearly not in memory */
2108 if (CUR_TI->filesize == 0 || !CUR_TI->taginfo_ready)
2110 audio_rebuffer();
2111 goto skip_done;
2114 /* When skipping backwards, it is possible that we've found a track that's
2115 * buffered, but which is around the track-wrap and therefore not the track
2116 * we are looking for */
2117 if (!forward)
2119 int cur_idx = track_ridx;
2120 bool taginfo_ready = true;
2121 /* We've wrapped the buffer backwards if new > old */
2122 bool wrap = track_ridx > old_track_ridx;
2124 while (1)
2126 cur_idx = (cur_idx + 1) & MAX_TRACK_MASK;
2128 /* if we've advanced past the wrap when cur_idx is zeroed */
2129 if (!cur_idx)
2130 wrap = false;
2132 /* if we aren't still on the wrap and we've caught the old track */
2133 if (!(wrap || cur_idx < old_track_ridx))
2134 break;
2136 /* If we hit a track in between without valid tag info, bail */
2137 if (!tracks[cur_idx].taginfo_ready)
2139 taginfo_ready = false;
2140 break;
2143 if (!taginfo_ready)
2145 audio_rebuffer();
2149 skip_done:
2150 audio_update_trackinfo();
2151 LOGFQUEUE("audio >|= codec Q_CODEC_REQUEST_COMPLETE");
2152 return Q_CODEC_REQUEST_COMPLETE;
2155 unsigned long audio_prev_elapsed(void)
2157 return prev_track_elapsed;
2160 static void audio_stop_codec_flush(void)
2162 ci.stop_codec = true;
2163 pcmbuf_pause(true);
2165 while (audio_codec_loaded)
2166 yield();
2168 /* If the audio codec is not loaded any more, and the audio is still
2169 * playing, it is now and _only_ now safe to call this function from the
2170 * audio thread */
2171 if (pcm_is_playing())
2173 pcmbuf_play_stop();
2174 pcmbuf_queue_clear();
2176 pcmbuf_pause(paused);
2179 static void audio_stop_playback(void)
2181 /* If we were playing, save resume information */
2182 if (playing)
2184 struct mp3entry *id3 = NULL;
2186 if (!ci.stop_codec)
2188 /* Set this early, the outside code yields and may allow the codec
2189 to try to wait for a reply on a buffer wait */
2190 ci.stop_codec = true;
2191 id3 = audio_current_track();
2194 /* Save the current playing spot, or NULL if the playlist has ended */
2195 playlist_update_resume_info(id3);
2197 /* TODO: Create auto bookmark too? */
2199 prev_track_elapsed = othertrack_id3->elapsed;
2201 remove_event(BUFFER_EVENT_BUFFER_LOW, buffering_low_buffer_callback);
2204 audio_stop_codec_flush();
2205 paused = false;
2206 playing = false;
2207 track_load_started = false;
2209 filling = STATE_IDLE;
2211 /* Mark all entries null. */
2212 audio_clear_track_entries();
2214 /* Close all tracks */
2215 audio_release_tracks();
2218 static void audio_play_start(size_t offset)
2220 int i;
2222 #if INPUT_SRC_CAPS != 0
2223 audio_set_input_source(AUDIO_SRC_PLAYBACK, SRCF_PLAYBACK);
2224 audio_set_output_source(AUDIO_SRC_PLAYBACK);
2225 #endif
2227 /* Wait for any previously playing audio to flush - TODO: Not necessary? */
2228 paused = false;
2229 audio_stop_codec_flush();
2231 playing = true;
2232 track_load_started = false;
2234 ci.new_track = 0;
2235 ci.seek_time = 0;
2236 wps_offset = 0;
2238 sound_set_volume(global_settings.volume);
2239 track_widx = track_ridx = 0;
2241 /* Clear all track entries. */
2242 for (i = 0; i < MAX_TRACK; i++) {
2243 clear_track_info(&tracks[i]);
2246 last_peek_offset = -1;
2248 /* Officially playing */
2249 queue_reply(&audio_queue, 1);
2251 audio_fill_file_buffer(true, offset);
2253 add_event(BUFFER_EVENT_BUFFER_LOW, false, buffering_low_buffer_callback);
2255 LOGFQUEUE("audio > audio Q_AUDIO_TRACK_CHANGED");
2256 queue_post(&audio_queue, Q_AUDIO_TRACK_CHANGED, 0);
2260 /* Invalidates all but currently playing track. */
2261 static void audio_invalidate_tracks(void)
2263 if (audio_have_tracks())
2265 last_peek_offset = 0;
2266 track_widx = track_ridx;
2268 /* Mark all other entries null (also buffered wrong metadata). */
2269 audio_clear_track_entries();
2271 track_widx = (track_widx + 1) & MAX_TRACK_MASK;
2273 audio_fill_file_buffer(false, 0);
2277 static void audio_new_playlist(void)
2279 /* Prepare to start a new fill from the beginning of the playlist */
2280 last_peek_offset = -1;
2281 if (audio_have_tracks())
2283 if (paused)
2284 skipped_during_pause = true;
2285 track_widx = track_ridx;
2286 audio_clear_track_entries();
2288 track_widx = (track_widx + 1) & MAX_TRACK_MASK;
2290 /* Mark the current track as invalid to prevent skipping back to it */
2291 CUR_TI->taginfo_ready = false;
2294 /* Signal the codec to initiate a track change forward */
2295 new_playlist = true;
2296 ci.new_track = 1;
2298 /* Officially playing */
2299 queue_reply(&audio_queue, 1);
2301 audio_fill_file_buffer(false, 0);
2304 /* Called on manual track skip */
2305 static void audio_initiate_track_change(long direction)
2307 logf("audio_initiate_track_change(%ld)", direction);
2309 ci.new_track += direction;
2310 wps_offset -= direction;
2311 if (paused)
2312 skipped_during_pause = true;
2315 /* Called on manual dir skip */
2316 static void audio_initiate_dir_change(long direction)
2318 dir_skip = true;
2319 ci.new_track = direction;
2320 if (paused)
2321 skipped_during_pause = true;
2324 /* Called when PCM track change is complete */
2325 static void audio_finalise_track_change(void)
2327 logf("audio_finalise_track_change");
2329 if (automatic_skip)
2331 wps_offset = 0;
2332 automatic_skip = false;
2334 /* Invalidate prevtrack_id3 */
2335 memset(othertrack_id3, 0, sizeof(struct mp3entry));
2337 if (prev_ti && prev_ti->audio_hid < 0)
2339 /* No audio left so we clear all the track info. */
2340 clear_track_info(prev_ti);
2343 send_event(PLAYBACK_EVENT_TRACK_CHANGE, thistrack_id3);
2344 playlist_update_resume_info(audio_current_track());
2348 * Layout audio buffer as follows - iram buffer depends on target:
2349 * [|SWAP:iram][|TALK]|FILE|GUARD|PCM|[SWAP:dram[|iram]|]
2351 static void audio_reset_buffer(void)
2353 /* see audio_get_recording_buffer if this is modified */
2354 logf("audio_reset_buffer");
2356 /* If the setup of anything allocated before the file buffer is
2357 changed, do check the adjustments after the buffer_alloc call
2358 as it will likely be affected and need sliding over */
2360 /* Initially set up file buffer as all space available */
2361 malloc_buf = audiobuf + talk_get_bufsize();
2362 /* Align the malloc buf to line size. Especially important to cf
2363 targets that do line reads/writes. */
2364 malloc_buf = (unsigned char *)(((uintptr_t)malloc_buf + 15) & ~15);
2365 filebuf = malloc_buf; /* filebuf line align implied */
2366 filebuflen = audiobufend - filebuf;
2368 filebuflen &= ~15;
2370 /* Subtract whatever the pcm buffer says it used plus the guard buffer */
2371 const size_t pcmbuf_size = pcmbuf_init(filebuf + filebuflen) +GUARD_BUFSIZE;
2373 #ifdef DEBUG
2374 if(pcmbuf_size > filebuflen)
2375 panicf("Not enough memory for pcmbuf_init() : %d > %d",
2376 (int)pcmbuf_size, (int)filebuflen);
2377 #endif
2379 filebuflen -= pcmbuf_size;
2381 /* Make sure filebuflen is a longword multiple after adjustment - filebuf
2382 will already be line aligned */
2383 filebuflen &= ~3;
2385 buffering_reset(filebuf, filebuflen);
2387 /* Clear any references to the file buffer */
2388 buffer_state = AUDIOBUF_STATE_INITIALIZED;
2390 #if defined(ROCKBOX_HAS_LOGF) && defined(LOGF_ENABLE)
2391 /* Make sure everything adds up - yes, some info is a bit redundant but
2392 aids viewing and the sumation of certain variables should add up to
2393 the location of others. */
2395 size_t pcmbufsize;
2396 const unsigned char *pcmbuf = pcmbuf_get_meminfo(&pcmbufsize);
2397 logf("mabuf: %08X", (unsigned)malloc_buf);
2398 logf("fbuf: %08X", (unsigned)filebuf);
2399 logf("fbufe: %08X", (unsigned)(filebuf + filebuflen));
2400 logf("gbuf: %08X", (unsigned)(filebuf + filebuflen));
2401 logf("gbufe: %08X", (unsigned)(filebuf + filebuflen + GUARD_BUFSIZE));
2402 logf("pcmb: %08X", (unsigned)pcmbuf);
2403 logf("pcmbe: %08X", (unsigned)(pcmbuf + pcmbufsize));
2405 #endif
2408 static void audio_thread(void)
2410 struct queue_event ev;
2412 pcm_postinit();
2414 audio_thread_ready = true;
2416 while (1)
2418 if (filling != STATE_FILLING) {
2419 /* End of buffering, let's calculate the watermark and unboost */
2420 set_filebuf_watermark();
2421 cancel_cpu_boost();
2424 if (!pcmbuf_queue_scan(&ev))
2425 queue_wait_w_tmo(&audio_queue, &ev, HZ/2);
2427 switch (ev.id) {
2429 case Q_AUDIO_FILL_BUFFER:
2430 LOGFQUEUE("audio < Q_AUDIO_FILL_BUFFER %d", (int)ev.data);
2431 audio_fill_file_buffer((bool)ev.data, 0);
2432 break;
2434 case Q_AUDIO_FINISH_LOAD:
2435 LOGFQUEUE("audio < Q_AUDIO_FINISH_LOAD");
2436 audio_finish_load_track();
2437 break;
2439 case Q_AUDIO_PLAY:
2440 LOGFQUEUE("audio < Q_AUDIO_PLAY");
2441 if (playing && ev.data <= 0)
2442 audio_new_playlist();
2443 else
2445 audio_stop_playback();
2446 audio_play_start((size_t)ev.data);
2448 break;
2450 case Q_AUDIO_STOP:
2451 LOGFQUEUE("audio < Q_AUDIO_STOP");
2452 if (playing)
2453 audio_stop_playback();
2454 if (ev.data != 0)
2455 queue_clear(&audio_queue);
2456 break;
2458 case Q_AUDIO_PAUSE:
2459 LOGFQUEUE("audio < Q_AUDIO_PAUSE");
2460 if (!(bool) ev.data && skipped_during_pause && !pcmbuf_is_crossfade_active())
2461 pcmbuf_play_stop(); /* Flush old track on resume after skip */
2462 skipped_during_pause = false;
2463 if (!playing)
2464 break;
2465 pcmbuf_pause((bool)ev.data);
2466 paused = (bool)ev.data;
2467 break;
2469 case Q_AUDIO_SKIP:
2470 LOGFQUEUE("audio < Q_AUDIO_SKIP");
2471 audio_initiate_track_change((long)ev.data);
2472 break;
2474 case Q_AUDIO_PRE_FF_REWIND:
2475 LOGFQUEUE("audio < Q_AUDIO_PRE_FF_REWIND");
2476 if (!playing)
2477 break;
2478 pcmbuf_pause(true);
2479 break;
2481 case Q_AUDIO_FF_REWIND:
2482 LOGFQUEUE("audio < Q_AUDIO_FF_REWIND");
2483 if (!playing)
2484 break;
2485 if (automatic_skip)
2487 /* An automatic track skip is in progress. Finalize it,
2488 then go back to the previous track */
2489 audio_finalise_track_change();
2490 ci.new_track = -1;
2492 ci.seek_time = (long)ev.data+1;
2493 break;
2495 case Q_AUDIO_CHECK_NEW_TRACK:
2496 LOGFQUEUE("audio < Q_AUDIO_CHECK_NEW_TRACK");
2497 queue_reply(&audio_queue, audio_check_new_track());
2498 break;
2500 case Q_AUDIO_DIR_SKIP:
2501 LOGFQUEUE("audio < Q_AUDIO_DIR_SKIP");
2502 audio_initiate_dir_change(ev.data);
2503 break;
2505 case Q_AUDIO_FLUSH:
2506 LOGFQUEUE("audio < Q_AUDIO_FLUSH");
2507 audio_invalidate_tracks();
2508 break;
2510 case Q_AUDIO_TRACK_CHANGED:
2511 /* PCM track change done */
2512 LOGFQUEUE("audio < Q_AUDIO_TRACK_CHANGED");
2513 audio_finalise_track_change();
2514 break;
2516 #ifndef SIMULATOR
2517 case SYS_USB_CONNECTED:
2518 LOGFQUEUE("audio < SYS_USB_CONNECTED");
2519 if (playing)
2520 audio_stop_playback();
2521 #ifdef PLAYBACK_VOICE
2522 voice_stop();
2523 #endif
2524 usb_acknowledge(SYS_USB_CONNECTED_ACK);
2525 usb_wait_for_disconnect(&audio_queue);
2527 /* Mark all entries null. */
2528 audio_clear_track_entries();
2530 /* release tracks to make sure all handles are closed */
2531 audio_release_tracks();
2532 break;
2533 #endif
2535 case SYS_TIMEOUT:
2536 LOGFQUEUE_SYS_TIMEOUT("audio < SYS_TIMEOUT");
2537 break;
2539 default:
2540 LOGFQUEUE("audio < default");
2541 break;
2542 } /* end switch */
2543 } /* end while */
2546 /* Initialize the audio system - called from init() in main.c.
2547 * Last function because of all the references to internal symbols
2549 void audio_init(void)
2551 unsigned int audio_thread_id;
2553 /* Can never do this twice */
2554 if (audio_is_initialized)
2556 logf("audio: already initialized");
2557 return;
2560 logf("audio: initializing");
2562 /* Initialize queues before giving control elsewhere in case it likes
2563 to send messages. Thread creation will be delayed however so nothing
2564 starts running until ready if something yields such as talk_init. */
2565 queue_init(&audio_queue, true);
2566 queue_init(&codec_queue, false);
2567 queue_init(&pcmbuf_queue, false);
2569 pcm_init();
2571 /* Initialize codec api. */
2572 ci.read_filebuf = codec_filebuf_callback;
2573 ci.pcmbuf_insert = codec_pcmbuf_insert_callback;
2574 ci.codec_get_buffer = codec_get_buffer;
2575 ci.request_buffer = codec_request_buffer_callback;
2576 ci.advance_buffer = codec_advance_buffer_callback;
2577 ci.advance_buffer_loc = codec_advance_buffer_loc_callback;
2578 ci.request_next_track = codec_request_next_track_callback;
2579 ci.seek_buffer = codec_seek_buffer_callback;
2580 ci.seek_complete = codec_seek_complete_callback;
2581 ci.set_elapsed = codec_set_elapsed_callback;
2582 ci.set_offset = codec_set_offset_callback;
2583 ci.configure = codec_configure_callback;
2584 ci.discard_codec = codec_discard_codec_callback;
2585 ci.dsp = (struct dsp_config *)dsp_configure(NULL, DSP_MYDSP,
2586 CODEC_IDX_AUDIO);
2588 thistrack_id3 = &mp3entry_buf[0];
2589 othertrack_id3 = &mp3entry_buf[1];
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;