Simulate the effects of sector caching a bit. Bypass I/O yield if a byte counter...
[Rockbox.git] / apps / playback.c
blob8467614329075cff39d8519db12ca70c9c326d1d
1 /***************************************************************************
2 * __________ __ ___.
3 * Open \______ \ ____ ____ | | _\_ |__ _______ ___
4 * Source | _// _ \_/ ___\| |/ /| __ \ / _ \ \/ /
5 * Jukebox | | ( <_> ) \___| < | \_\ ( <_> > < <
6 * Firmware |____|_ /\____/ \___ >__|_ \|___ /\____/__/\_ \
7 * \/ \/ \/ \/ \/
8 * $Id$
10 * Copyright (C) 2005 Miika Pekkarinen
12 * All files in this archive are subject to the GNU General Public License.
13 * See the file COPYING in the source tree root for full license agreement.
15 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
16 * KIND, either express or implied.
18 ****************************************************************************/
20 /* TODO: Can use the track changed callback to detect end of track and seek
21 * in the previous track until this happens */
22 /* Design: we have prev_ti already, have a conditional for what type of seek
23 * to do on a seek request, if it is a previous track seek, skip previous,
24 * and in the request_next_track callback set the offset up the same way that
25 * starting from an offset works. */
26 /* TODO: Pause should be handled in here, rather than PCMBUF so that voice can
27 * play whilst audio is paused */
29 #include <stdio.h>
30 #include <string.h>
31 #include <stdlib.h>
32 #include <ctype.h>
34 #include "system.h"
35 #include "thread.h"
36 #include "file.h"
37 #include "panic.h"
38 #include "memory.h"
39 #include "lcd.h"
40 #include "font.h"
41 #include "button.h"
42 #include "kernel.h"
43 #include "tree.h"
44 #include "debug.h"
45 #include "sprintf.h"
46 #include "settings.h"
47 #include "codecs.h"
48 #include "audio.h"
49 #include "buffering.h"
50 #include "voice_thread.h"
51 #include "mp3_playback.h"
52 #include "usb.h"
53 #include "status.h"
54 #include "ata.h"
55 #include "screens.h"
56 #include "playlist.h"
57 #include "playback.h"
58 #include "pcmbuf.h"
59 #include "buffer.h"
60 #include "dsp.h"
61 #include "abrepeat.h"
62 #include "cuesheet.h"
63 #ifdef HAVE_TAGCACHE
64 #include "tagcache.h"
65 #endif
66 #ifdef HAVE_LCD_BITMAP
67 #include "icons.h"
68 #include "peakmeter.h"
69 #include "action.h"
70 #include "albumart.h"
71 #endif
72 #include "lang.h"
73 #include "bookmark.h"
74 #include "misc.h"
75 #include "sound.h"
76 #include "metadata.h"
77 #include "splash.h"
78 #include "talk.h"
79 #include "ata_idle_notify.h"
81 #ifdef HAVE_RECORDING
82 #include "recording.h"
83 #include "talk.h"
84 #endif
86 #define PLAYBACK_VOICE
88 /* default point to start buffer refill */
89 #define AUDIO_DEFAULT_WATERMARK (1024*512)
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_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
151 /* As defined in plugins/lib/xxx2wav.h */
152 #if MEM > 1
153 #define MALLOC_BUFSIZE (512*1024)
154 #define GUARD_BUFSIZE (32*1024)
155 #else
156 #define MALLOC_BUFSIZE (100*1024)
157 #define GUARD_BUFSIZE (8*1024)
158 #endif
160 /* As defined in plugin.lds */
161 #if defined(CPU_PP)
162 #define CODEC_IRAM_ORIGIN ((unsigned char *)0x4000c000)
163 #define CODEC_IRAM_SIZE ((size_t)0xc000)
164 #elif defined(IAUDIO_X5) || defined(IAUDIO_M5)
165 #define CODEC_IRAM_ORIGIN ((unsigned char *)0x10010000)
166 #define CODEC_IRAM_SIZE ((size_t)0x10000)
167 #else
168 #define CODEC_IRAM_ORIGIN ((unsigned char *)0x1000c000)
169 #define CODEC_IRAM_SIZE ((size_t)0xc000)
170 #endif
172 bool audio_is_initialized = false;
173 static bool audio_thread_ready NOCACHEBSS_ATTR = false;
175 /* Variables are commented with the threads that use them: *
176 * A=audio, C=codec, V=voice. A suffix of - indicates that *
177 * the variable is read but not updated on that thread. */
178 /* TBD: Split out "audio" and "playback" (ie. calling) threads */
180 /* Main state control */
181 static volatile bool audio_codec_loaded NOCACHEBSS_ATTR = false; /* Codec loaded? (C/A-) */
182 static volatile bool playing NOCACHEBSS_ATTR = false; /* Is audio playing? (A) */
183 static volatile bool paused NOCACHEBSS_ATTR = false; /* Is audio paused? (A/C-) */
185 /* Ring buffer where compressed audio and codecs are loaded */
186 static unsigned char *filebuf = NULL; /* Start of buffer (A/C-) */
187 static unsigned char *malloc_buf = NULL; /* Start of malloc buffer (A/C-) */
188 /* FIXME: make filebuflen static */
189 size_t filebuflen = 0; /* Size of buffer (A/C-) */
190 /* FIXME: make buf_ridx (C/A-) */
192 /* Possible arrangements of the buffer */
193 #define BUFFER_STATE_TRASHED -1 /* trashed; must be reset */
194 #define BUFFER_STATE_INITIALIZED 0 /* voice+audio OR audio-only */
195 #define BUFFER_STATE_VOICED_ONLY 1 /* voice-only */
196 static int buffer_state = BUFFER_STATE_TRASHED; /* Buffer state */
198 /* Used to keep the WPS up-to-date during track transtition */
199 static struct mp3entry prevtrack_id3;
201 /* Used to provide the codec with a pointer */
202 static struct mp3entry curtrack_id3;
204 /* Used to make next track info available while playing last track on buffer */
205 static struct mp3entry lasttrack_id3;
207 /* Track info structure about songs in the file buffer (A/C-) */
208 struct track_info {
209 int audio_hid; /* The ID for the track's buffer handle */
210 int id3_hid; /* The ID for the track's metadata handle */
211 int codec_hid; /* The ID for the track's codec handle */
212 #ifdef HAVE_ALBUMART
213 int aa_hid; /* The ID for the track's album art handle */
214 #endif
216 size_t filesize; /* File total length */
218 bool taginfo_ready; /* Is metadata read */
220 bool event_sent; /* Was this track's buffered event sent */
223 static struct track_info tracks[MAX_TRACK];
224 static volatile int track_ridx = 0; /* Track being decoded (A/C-) */
225 static int track_widx = 0; /* Track being buffered (A) */
227 #define CUR_TI (&tracks[track_ridx]) /* Playing track info pointer (A/C-) */
228 static struct track_info *prev_ti = NULL; /* Pointer to the previously played
229 track */
231 /* Set by the audio thread when the current track information has updated
232 * and the WPS may need to update its cached information */
233 static bool track_changed = false;
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 /* Track change controls */
243 static bool automatic_skip = false; /* Who initiated in-progress skip? (C/A-) */
244 static bool playlist_end = false; /* Has the current playlist ended? (A) */
245 static bool dir_skip = false; /* Is a directory skip pending? (A) */
246 static bool new_playlist = false; /* Are we starting a new playlist? (A) */
247 static int wps_offset = 0; /* Pending track change offset, to keep WPS responsive (A) */
248 static bool skipped_during_pause = false; /* Do we need to clear the PCM buffer when playback resumes (A) */
250 /* Callbacks which applications or plugins may set */
251 /* When the playing track has changed from the user's perspective */
252 void (*track_changed_callback)(struct mp3entry *id3) = NULL;
253 /* When a track has been buffered */
254 void (*track_buffer_callback)(struct mp3entry *id3) = NULL;
255 /* When a track's buffer has been overwritten or cleared */
256 void (*track_unbuffer_callback)(struct mp3entry *id3) = NULL;
258 static size_t buffer_margin = 0; /* Buffer margin aka anti-skip buffer (A/C-) */
260 /* Multiple threads */
261 /* Set the watermark to trigger buffer fill (A/C) FIXME */
262 static void set_filebuf_watermark(int seconds, size_t max);
264 /* Audio thread */
265 static struct event_queue audio_queue NOCACHEBSS_ATTR;
266 static struct queue_sender_list audio_queue_sender_list NOCACHEBSS_ATTR;
267 static long audio_stack[(DEFAULT_STACK_SIZE + 0x1000)/sizeof(long)];
268 static const char audio_thread_name[] = "audio";
270 static void audio_thread(void);
271 static void audio_initiate_track_change(long direction);
272 static bool audio_have_tracks(void);
273 static void audio_reset_buffer(void);
275 /* Codec thread */
276 extern struct codec_api ci;
277 static struct event_queue codec_queue NOCACHEBSS_ATTR;
278 static struct queue_sender_list codec_queue_sender_list;
279 static long codec_stack[(DEFAULT_STACK_SIZE + 0x2000)/sizeof(long)]
280 IBSS_ATTR;
281 static const char codec_thread_name[] = "codec";
282 struct thread_entry *codec_thread_p; /* For modifying thread priority later. */
284 /* --- Helper functions --- */
286 static struct mp3entry *bufgetid3(int handle_id)
288 if (handle_id < 0)
289 return NULL;
291 struct mp3entry *id3;
292 ssize_t ret = bufgetdata(handle_id, 0, (void *)&id3);
294 if (ret < 0 || ret != sizeof(struct mp3entry))
295 return NULL;
297 return id3;
300 static bool clear_track_info(struct track_info *track)
302 /* bufclose returns true if the handle is not found, or if it is closed
303 * successfully, so these checks are safe on non-existant handles */
304 if (!track)
305 return false;
307 if (track->codec_hid >= 0) {
308 if (bufclose(track->codec_hid))
309 track->codec_hid = -1;
310 else
311 return false;
314 if (track->id3_hid >= 0) {
315 if (track->event_sent && track_unbuffer_callback) {
316 /* If there is an unbuffer callback, call it */
317 track_unbuffer_callback(bufgetid3(track->id3_hid));
320 if (bufclose(track->id3_hid))
321 track->id3_hid = -1;
322 else
323 return false;
326 if (track->audio_hid >= 0) {
327 if (bufclose(track->audio_hid))
328 track->audio_hid = -1;
329 else
330 return false;
333 #ifdef HAVE_ALBUMART
334 if (track->aa_hid >= 0) {
335 if (bufclose(track->aa_hid))
336 track->aa_hid = -1;
337 else
338 return false;
340 #endif
342 track->filesize = 0;
343 track->taginfo_ready = false;
344 track->event_sent = false;
346 return true;
349 /* --- External interfaces --- */
351 /* This sends a stop message and the audio thread will dump all it's
352 subsequenct messages */
353 void audio_hard_stop(void)
355 /* Stop playback */
356 LOGFQUEUE("audio >| audio Q_AUDIO_STOP: 1");
357 queue_send(&audio_queue, Q_AUDIO_STOP, 1);
358 #ifdef PLAYBACK_VOICE
359 voice_stop();
360 #endif
363 bool audio_restore_playback(int type)
365 switch (type)
367 case AUDIO_WANT_PLAYBACK:
368 if (buffer_state != BUFFER_STATE_INITIALIZED)
369 audio_reset_buffer();
370 return true;
371 case AUDIO_WANT_VOICE:
372 if (buffer_state == BUFFER_STATE_TRASHED)
373 audio_reset_buffer();
374 return true;
375 default:
376 return false;
380 unsigned char *audio_get_buffer(bool talk_buf, size_t *buffer_size)
382 unsigned char *buf, *end;
384 if (audio_is_initialized)
386 audio_hard_stop();
388 /* else buffer_state will be BUFFER_STATE_TRASHED at this point */
390 if (buffer_size == NULL)
392 /* Special case for talk_init to use since it already knows it's
393 trashed */
394 buffer_state = BUFFER_STATE_TRASHED;
395 return NULL;
398 if (talk_buf || buffer_state == BUFFER_STATE_TRASHED
399 || !talk_voice_required())
401 logf("get buffer: talk, audio");
402 /* Ok to use everything from audiobuf to audiobufend - voice is loaded,
403 the talk buffer is not needed because voice isn't being used, or
404 could be BUFFER_STATE_TRASHED already. If state is
405 BUFFER_STATE_VOICED_ONLY, no problem as long as memory isn't written
406 without the caller knowing what's going on. Changing certain settings
407 may move it to a worse condition but the memory in use by something
408 else will remain undisturbed.
410 if (buffer_state != BUFFER_STATE_TRASHED)
412 talk_buffer_steal();
413 buffer_state = BUFFER_STATE_TRASHED;
416 buf = audiobuf;
417 end = audiobufend;
419 else
421 /* Safe to just return this if already BUFFER_STATE_VOICED_ONLY or
422 still BUFFER_STATE_INITIALIZED */
423 /* Skip talk buffer and move pcm buffer to end to maximize available
424 contiguous memory - no audio running means voice will not need the
425 swap space */
426 logf("get buffer: audio");
427 buf = audiobuf + talk_get_bufsize();
428 end = audiobufend - pcmbuf_init(audiobufend);
429 buffer_state = BUFFER_STATE_VOICED_ONLY;
432 *buffer_size = end - buf;
434 return buf;
437 #ifdef HAVE_RECORDING
438 unsigned char *audio_get_recording_buffer(size_t *buffer_size)
440 /* Stop audio, voice and obtain all available buffer space */
441 audio_hard_stop();
442 talk_buffer_steal();
444 unsigned char *end = audiobufend;
445 buffer_state = BUFFER_STATE_TRASHED;
446 *buffer_size = end - audiobuf;
448 return (unsigned char *)audiobuf;
451 bool audio_load_encoder(int afmt)
453 #ifndef SIMULATOR
454 const char *enc_fn = get_codec_filename(afmt | CODEC_TYPE_ENCODER);
455 if (!enc_fn)
456 return false;
458 audio_remove_encoder();
459 ci.enc_codec_loaded = 0; /* clear any previous error condition */
461 LOGFQUEUE("codec > Q_ENCODER_LOAD_DISK");
462 queue_post(&codec_queue, Q_ENCODER_LOAD_DISK, (intptr_t)enc_fn);
464 while (ci.enc_codec_loaded == 0)
465 yield();
467 logf("codec loaded: %d", ci.enc_codec_loaded);
469 return ci.enc_codec_loaded > 0;
470 #else
471 (void)afmt;
472 return true;
473 #endif
474 } /* audio_load_encoder */
476 void audio_remove_encoder(void)
478 #ifndef SIMULATOR
479 /* force encoder codec unload (if currently loaded) */
480 if (ci.enc_codec_loaded <= 0)
481 return;
483 ci.stop_encoder = true;
484 while (ci.enc_codec_loaded > 0)
485 yield();
486 #endif
487 } /* audio_remove_encoder */
489 #endif /* HAVE_RECORDING */
491 #ifdef HAVE_ALBUMART
492 int audio_current_aa_hid(void)
494 int cur_idx;
495 int offset = ci.new_track + wps_offset;
497 cur_idx = track_ridx + offset;
498 cur_idx &= MAX_TRACK_MASK;
500 return tracks[cur_idx].aa_hid;
502 #endif
504 struct mp3entry* audio_current_track(void)
506 const char *filename;
507 const char *p;
508 static struct mp3entry temp_id3;
509 int cur_idx;
510 int offset = ci.new_track + wps_offset;
512 cur_idx = (track_ridx + offset) & MAX_TRACK_MASK;
514 if (cur_idx == track_ridx && *curtrack_id3.path)
516 /* The usual case */
517 return &curtrack_id3;
519 else if (offset == -1 && *prevtrack_id3.path)
521 /* We're in a track transition. The codec has moved on to the nex track,
522 but the audio being played is still the same (now previous) track.
523 prevtrack_id3.elapsed is being updated in an ISR by
524 codec_pcmbuf_position_callback */
525 return &prevtrack_id3;
527 else if (tracks[cur_idx].id3_hid >= 0)
529 /* Get the ID3 metadata from the main buffer */
530 return bufgetid3(tracks[cur_idx].id3_hid);
533 /* We didn't find the ID3 metadata, so we fill temp_id3 with the little info
534 we have and return that. */
536 memset(&temp_id3, 0, sizeof(struct mp3entry));
538 filename = playlist_peek(0);
539 if (!filename)
540 filename = "No file!";
542 #ifdef HAVE_TC_RAMCACHE
543 if (tagcache_fill_tags(&temp_id3, filename))
544 return &temp_id3;
545 #endif
547 p = strrchr(filename, '/');
548 if (!p)
549 p = filename;
550 else
551 p++;
553 strncpy(temp_id3.path, p, sizeof(temp_id3.path)-1);
554 temp_id3.title = &temp_id3.path[0];
556 return &temp_id3;
559 struct mp3entry* audio_next_track(void)
561 int next_idx = track_ridx;
563 if (!audio_have_tracks())
564 return NULL;
566 if (wps_offset == -1 && *prevtrack_id3.path)
568 /* We're in a track transition. The next track for the WPS is the one
569 currently being decoded. */
570 return &curtrack_id3;
573 next_idx = (next_idx + 1) & MAX_TRACK_MASK;
575 if (next_idx == track_widx)
577 /* The next track hasn't been buffered yet, so we return the static
578 version of its metadata. */
579 return &lasttrack_id3;
582 if (tracks[next_idx].id3_hid < 0)
583 return NULL;
584 else
585 return bufgetid3(tracks[next_idx].id3_hid);
588 bool audio_has_changed_track(void)
590 if (track_changed)
592 track_changed = false;
593 return true;
596 return false;
599 void audio_play(long offset)
601 logf("audio_play");
603 #ifdef PLAYBACK_VOICE
604 /* Truncate any existing voice output so we don't have spelling
605 * etc. over the first part of the played track */
606 talk_force_shutup();
607 #endif
609 /* Start playback */
610 LOGFQUEUE("audio >| audio Q_AUDIO_PLAY: %ld", offset);
611 /* Don't return until playback has actually started */
612 queue_send(&audio_queue, Q_AUDIO_PLAY, offset);
615 void audio_stop(void)
617 /* Stop playback */
618 LOGFQUEUE("audio >| audio Q_AUDIO_STOP");
619 /* Don't return until playback has actually stopped */
620 queue_send(&audio_queue, Q_AUDIO_STOP, 0);
623 void audio_pause(void)
625 LOGFQUEUE("audio >| audio Q_AUDIO_PAUSE");
626 /* Don't return until playback has actually paused */
627 queue_send(&audio_queue, Q_AUDIO_PAUSE, true);
630 void audio_resume(void)
632 LOGFQUEUE("audio >| audio Q_AUDIO_PAUSE resume");
633 /* Don't return until playback has actually resumed */
634 queue_send(&audio_queue, Q_AUDIO_PAUSE, false);
637 void audio_next(void)
639 if (playlist_check(ci.new_track + wps_offset + 1))
641 if (global_settings.beep)
642 pcmbuf_beep(5000, 100, 2500*global_settings.beep);
644 LOGFQUEUE("audio > audio Q_AUDIO_SKIP 1");
645 queue_post(&audio_queue, Q_AUDIO_SKIP, 1);
646 /* Update wps while our message travels inside deep playback queues. */
647 wps_offset++;
648 track_changed = true;
650 else
652 /* No more tracks. */
653 if (global_settings.beep)
654 pcmbuf_beep(1000, 100, 1000*global_settings.beep);
658 void audio_prev(void)
660 if (playlist_check(ci.new_track + wps_offset - 1))
662 if (global_settings.beep)
663 pcmbuf_beep(5000, 100, 2500*global_settings.beep);
665 LOGFQUEUE("audio > audio Q_AUDIO_SKIP -1");
666 queue_post(&audio_queue, Q_AUDIO_SKIP, -1);
667 /* Update wps while our message travels inside deep playback queues. */
668 wps_offset--;
669 track_changed = true;
671 else
673 /* No more tracks. */
674 if (global_settings.beep)
675 pcmbuf_beep(1000, 100, 1000*global_settings.beep);
679 void audio_next_dir(void)
681 LOGFQUEUE("audio > audio Q_AUDIO_DIR_SKIP 1");
682 queue_post(&audio_queue, Q_AUDIO_DIR_SKIP, 1);
685 void audio_prev_dir(void)
687 LOGFQUEUE("audio > audio Q_AUDIO_DIR_SKIP -1");
688 queue_post(&audio_queue, Q_AUDIO_DIR_SKIP, -1);
691 void audio_pre_ff_rewind(void)
693 LOGFQUEUE("audio > audio Q_AUDIO_PRE_FF_REWIND");
694 queue_post(&audio_queue, Q_AUDIO_PRE_FF_REWIND, 0);
697 void audio_ff_rewind(long newpos)
699 LOGFQUEUE("audio > audio Q_AUDIO_FF_REWIND");
700 queue_post(&audio_queue, Q_AUDIO_FF_REWIND, newpos);
703 void audio_flush_and_reload_tracks(void)
705 LOGFQUEUE("audio > audio Q_AUDIO_FLUSH");
706 queue_post(&audio_queue, Q_AUDIO_FLUSH, 0);
709 void audio_error_clear(void)
711 #ifdef AUDIO_HAVE_RECORDING
712 pcm_rec_error_clear();
713 #endif
716 int audio_status(void)
718 int ret = 0;
720 if (playing)
721 ret |= AUDIO_STATUS_PLAY;
723 if (paused)
724 ret |= AUDIO_STATUS_PAUSE;
726 #ifdef HAVE_RECORDING
727 /* Do this here for constitency with mpeg.c version */
728 ret |= pcm_rec_status();
729 #endif
731 return ret;
734 int audio_get_file_pos(void)
736 return 0;
739 #ifndef HAVE_FLASH_STORAGE
740 void audio_set_buffer_margin(int setting)
742 static const int lookup[] = {5, 15, 30, 60, 120, 180, 300, 600};
743 buffer_margin = lookup[setting];
744 logf("buffer margin: %ld", (long)buffer_margin);
745 set_filebuf_watermark(buffer_margin, 0);
747 #endif
749 /* Take nescessary steps to enable or disable the crossfade setting */
750 void audio_set_crossfade(int enable)
752 size_t offset;
753 bool was_playing;
754 size_t size;
756 /* Tell it the next setting to use */
757 pcmbuf_crossfade_enable(enable);
759 /* Return if size hasn't changed or this is too early to determine
760 which in the second case there's no way we could be playing
761 anything at all */
762 if (pcmbuf_is_same_size())
764 /* This function is a copout and just syncs some variables -
765 to be removed at a later date */
766 pcmbuf_crossfade_enable_finished();
767 return;
770 offset = 0;
771 was_playing = playing;
773 /* Playback has to be stopped before changing the buffer size */
774 if (was_playing)
776 /* Store the track resume position */
777 offset = curtrack_id3.offset;
778 gui_syncsplash(0, str(LANG_RESTARTING_PLAYBACK));
781 /* Blast it - audio buffer will have to be setup again next time
782 something plays */
783 audio_get_buffer(true, &size);
785 /* Restart playback if audio was running previously */
786 if (was_playing)
787 audio_play(offset);
790 /* --- Routines called from multiple threads --- */
792 static void set_filebuf_watermark(int seconds, size_t max)
794 size_t bytes;
796 if (!filebuf)
797 return; /* Audio buffers not yet set up */
799 bytes = seconds?MAX(curtrack_id3.bitrate * seconds * (1000/8), max):max;
800 bytes = MIN(bytes, filebuflen / 2);
801 buf_set_watermark(bytes);
804 const char * get_codec_filename(int cod_spec)
806 const char *fname;
808 #ifdef HAVE_RECORDING
809 /* Can choose decoder or encoder if one available */
810 int type = cod_spec & CODEC_TYPE_MASK;
811 int afmt = cod_spec & CODEC_AFMT_MASK;
813 if ((unsigned)afmt >= AFMT_NUM_CODECS)
814 type = AFMT_UNKNOWN | (type & CODEC_TYPE_MASK);
816 fname = (type == CODEC_TYPE_ENCODER) ?
817 audio_formats[afmt].codec_enc_root_fn :
818 audio_formats[afmt].codec_root_fn;
820 logf("%s: %d - %s",
821 (type == CODEC_TYPE_ENCODER) ? "Encoder" : "Decoder",
822 afmt, fname ? fname : "<unknown>");
823 #else /* !HAVE_RECORDING */
824 /* Always decoder */
825 if ((unsigned)cod_spec >= AFMT_NUM_CODECS)
826 cod_spec = AFMT_UNKNOWN;
827 fname = audio_formats[cod_spec].codec_root_fn;
828 logf("Codec: %d - %s", cod_spec, fname ? fname : "<unknown>");
829 #endif /* HAVE_RECORDING */
831 return fname;
832 } /* get_codec_filename */
834 /* --- Codec thread --- */
835 static bool codec_pcmbuf_insert_callback(
836 const void *ch1, const void *ch2, int count)
838 const char *src[2] = { ch1, ch2 };
840 while (count > 0)
842 int out_count = dsp_output_count(ci.dsp, count);
843 int inp_count;
844 char *dest;
846 /* Prevent audio from a previous track from playing */
847 if (ci.new_track || ci.stop_codec)
848 return true;
850 while ((dest = pcmbuf_request_buffer(&out_count)) == NULL)
852 cancel_cpu_boost();
853 sleep(1);
854 if (ci.seek_time || ci.new_track || ci.stop_codec)
855 return true;
858 /* Get the real input_size for output_size bytes, guarding
859 * against resampling buffer overflows. */
860 inp_count = dsp_input_count(ci.dsp, out_count);
862 if (inp_count <= 0)
863 return true;
865 /* Input size has grown, no error, just don't write more than length */
866 if (inp_count > count)
867 inp_count = count;
869 out_count = dsp_process(ci.dsp, dest, src, inp_count);
871 if (out_count <= 0)
872 return true;
874 pcmbuf_write_complete(out_count);
876 count -= inp_count;
879 return true;
880 } /* codec_pcmbuf_insert_callback */
882 static void* codec_get_memory_callback(size_t *size)
884 *size = MALLOC_BUFSIZE;
885 return malloc_buf;
888 /* Between the codec and PCM track change, we need to keep updating the
889 "elapsed" value of the previous (to the codec, but current to the
890 user/PCM/WPS) track, so that the progressbar reaches the end.
891 During that transition, the WPS will display prevtrack_id3. */
892 static void codec_pcmbuf_position_callback(size_t size) ICODE_ATTR;
893 static void codec_pcmbuf_position_callback(size_t size)
895 /* This is called from an ISR, so be quick */
896 unsigned int time = size * 1000 / 4 / NATIVE_FREQUENCY +
897 prevtrack_id3.elapsed;
899 if (time >= prevtrack_id3.length)
901 pcmbuf_set_position_callback(NULL);
902 prevtrack_id3.elapsed = prevtrack_id3.length;
904 else
905 prevtrack_id3.elapsed = time;
908 static void codec_set_elapsed_callback(unsigned int value)
910 unsigned int latency;
911 if (ci.seek_time)
912 return;
914 #ifdef AB_REPEAT_ENABLE
915 ab_position_report(value);
916 #endif
918 latency = pcmbuf_get_latency();
919 if (value < latency)
920 curtrack_id3.elapsed = 0;
921 else if (value - latency > curtrack_id3.elapsed ||
922 value - latency < curtrack_id3.elapsed - 2)
924 curtrack_id3.elapsed = value - latency;
928 static void codec_set_offset_callback(size_t value)
930 unsigned int latency;
932 if (ci.seek_time)
933 return;
935 latency = pcmbuf_get_latency() * curtrack_id3.bitrate / 8;
936 if (value < latency)
937 curtrack_id3.offset = 0;
938 else
939 curtrack_id3.offset = value - latency;
942 static void codec_advance_buffer_counters(size_t amount)
944 bufadvance(CUR_TI->audio_hid, amount);
945 ci.curpos += amount;
948 /* copy up-to size bytes into ptr and return the actual size copied */
949 static size_t codec_filebuf_callback(void *ptr, size_t size)
951 ssize_t copy_n;
953 if (ci.stop_codec || !playing)
954 return 0;
956 copy_n = bufread(CUR_TI->audio_hid, size, ptr);
958 /* Nothing requested OR nothing left */
959 if (copy_n == 0)
960 return 0;
962 /* Update read and other position pointers */
963 codec_advance_buffer_counters(copy_n);
965 /* Return the actual amount of data copied to the buffer */
966 return copy_n;
967 } /* codec_filebuf_callback */
969 static void* codec_request_buffer_callback(size_t *realsize, size_t reqsize)
971 size_t copy_n = reqsize;
972 ssize_t ret;
973 void *ptr;
975 if (!playing)
977 *realsize = 0;
978 return NULL;
981 ret = bufgetdata(CUR_TI->audio_hid, reqsize, &ptr);
982 if (ret >= 0)
983 copy_n = MIN((size_t)ret, reqsize);
985 if (copy_n == 0)
987 *realsize = 0;
988 return NULL;
991 *realsize = copy_n;
993 return ptr;
994 } /* codec_request_buffer_callback */
996 static int get_codec_base_type(int type)
998 switch (type) {
999 case AFMT_MPA_L1:
1000 case AFMT_MPA_L2:
1001 case AFMT_MPA_L3:
1002 return AFMT_MPA_L3;
1005 return type;
1008 static void codec_advance_buffer_callback(size_t amount)
1010 codec_advance_buffer_counters(amount);
1011 codec_set_offset_callback(ci.curpos);
1014 static void codec_advance_buffer_loc_callback(void *ptr)
1016 size_t amount = buf_get_offset(CUR_TI->audio_hid, ptr);
1017 codec_advance_buffer_callback(amount);
1020 /* Copied from mpeg.c. Should be moved somewhere else. */
1021 static int codec_get_file_pos(void)
1023 int pos = -1;
1024 struct mp3entry *id3 = audio_current_track();
1026 if (id3->vbr)
1028 if (id3->has_toc)
1030 /* Use the TOC to find the new position */
1031 unsigned int percent, remainder;
1032 int curtoc, nexttoc, plen;
1034 percent = (id3->elapsed*100)/id3->length;
1035 if (percent > 99)
1036 percent = 99;
1038 curtoc = id3->toc[percent];
1040 if (percent < 99)
1041 nexttoc = id3->toc[percent+1];
1042 else
1043 nexttoc = 256;
1045 pos = (id3->filesize/256)*curtoc;
1047 /* Use the remainder to get a more accurate position */
1048 remainder = (id3->elapsed*100)%id3->length;
1049 remainder = (remainder*100)/id3->length;
1050 plen = (nexttoc - curtoc)*(id3->filesize/256);
1051 pos += (plen/100)*remainder;
1053 else
1055 /* No TOC exists, estimate the new position */
1056 pos = (id3->filesize / (id3->length / 1000)) *
1057 (id3->elapsed / 1000);
1060 else if (id3->bitrate)
1061 pos = id3->elapsed * (id3->bitrate / 8);
1062 else
1063 return -1;
1065 pos += id3->first_frame_offset;
1067 /* Don't seek right to the end of the file so that we can
1068 transition properly to the next song */
1069 if (pos >= (int)(id3->filesize - id3->id3v1len))
1070 pos = id3->filesize - id3->id3v1len - 1;
1072 return pos;
1075 static off_t codec_mp3_get_filepos_callback(int newtime)
1077 off_t newpos;
1079 curtrack_id3.elapsed = newtime;
1080 newpos = codec_get_file_pos();
1082 return newpos;
1085 static void codec_seek_complete_callback(void)
1087 logf("seek_complete");
1088 if (pcm_is_paused())
1090 /* If this is not a seamless seek, clear the buffer */
1091 pcmbuf_play_stop();
1092 dsp_configure(ci.dsp, DSP_FLUSH, 0);
1094 /* If playback was not 'deliberately' paused, unpause now */
1095 if (!paused)
1096 pcmbuf_pause(false);
1098 ci.seek_time = 0;
1101 static bool codec_seek_buffer_callback(size_t newpos)
1103 logf("codec_seek_buffer_callback");
1105 int ret = bufseek(CUR_TI->audio_hid, newpos);
1106 if (ret == 0) {
1107 ci.curpos = newpos;
1108 return true;
1110 else {
1111 return false;
1115 static void codec_configure_callback(int setting, intptr_t value)
1117 switch (setting) {
1118 case CODEC_SET_FILEBUF_WATERMARK:
1119 set_filebuf_watermark(buffer_margin, value);
1120 break;
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 codec_track_changed();
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 if (ci.seek_time)
1203 codec_seek_complete_callback();
1205 #ifdef AB_REPEAT_ENABLE
1206 ab_end_of_track_report();
1207 #endif
1209 logf("Request new track");
1211 if (ci.new_track == 0)
1213 ci.new_track++;
1214 automatic_skip = true;
1217 if (!ci.stop_codec)
1219 trigger_cpu_boost();
1220 LOGFQUEUE("codec >| audio Q_AUDIO_CHECK_NEW_TRACK");
1221 result = queue_send(&audio_queue, Q_AUDIO_CHECK_NEW_TRACK, 0);
1224 switch (result)
1226 case Q_CODEC_REQUEST_COMPLETE:
1227 LOGFQUEUE("codec |< Q_CODEC_REQUEST_COMPLETE");
1228 codec_track_skip_done(!automatic_skip);
1229 return true;
1231 case Q_CODEC_REQUEST_FAILED:
1232 LOGFQUEUE("codec |< Q_CODEC_REQUEST_FAILED");
1233 ci.new_track = 0;
1234 ci.stop_codec = true;
1235 return false;
1237 default:
1238 LOGFQUEUE("codec |< default");
1239 ci.stop_codec = true;
1240 return false;
1244 static bool codec_request_next_track_callback(void)
1246 int prev_codectype;
1248 if (ci.stop_codec || !playing)
1249 return false;
1251 prev_codectype = get_codec_base_type(curtrack_id3.codectype);
1253 if (!codec_load_next_track())
1254 return false;
1256 /* Seek to the beginning of the new track because if the struct mp3entry was
1257 buffered, "elapsed" might not be zero (if the track has been played
1258 already but not unbuffered) */
1259 codec_seek_buffer_callback(curtrack_id3.first_frame_offset);
1261 /* Check if the next codec is the same file. */
1262 if (prev_codectype == get_codec_base_type(curtrack_id3.codectype))
1264 logf("New track loaded");
1265 codec_discard_codec_callback();
1266 return true;
1268 else
1270 logf("New codec:%d/%d", curtrack_id3.codectype, prev_codectype);
1271 return false;
1275 static void codec_thread(void)
1277 struct queue_event ev;
1278 int status;
1280 while (1) {
1281 status = 0;
1282 cancel_cpu_boost();
1283 queue_wait(&codec_queue, &ev);
1285 switch (ev.id) {
1286 case Q_CODEC_LOAD_DISK:
1287 LOGFQUEUE("codec < Q_CODEC_LOAD_DISK");
1288 queue_reply(&codec_queue, 1);
1289 audio_codec_loaded = true;
1290 ci.stop_codec = false;
1291 status = codec_load_file((const char *)ev.data, &ci);
1292 break;
1294 case Q_CODEC_LOAD:
1295 LOGFQUEUE("codec < Q_CODEC_LOAD");
1296 if (CUR_TI->codec_hid < 0) {
1297 logf("Codec slot is empty!");
1298 /* Wait for the pcm buffer to go empty */
1299 while (pcm_is_playing())
1300 yield();
1301 /* This must be set to prevent an infinite loop */
1302 ci.stop_codec = true;
1303 LOGFQUEUE("codec > codec Q_AUDIO_PLAY");
1304 queue_post(&codec_queue, Q_AUDIO_PLAY, 0);
1305 break;
1308 audio_codec_loaded = true;
1309 ci.stop_codec = false;
1310 status = codec_load_buf(CUR_TI->codec_hid, &ci);
1311 break;
1313 #ifdef AUDIO_HAVE_RECORDING
1314 case Q_ENCODER_LOAD_DISK:
1315 LOGFQUEUE("codec < Q_ENCODER_LOAD_DISK");
1316 audio_codec_loaded = false; /* Not audio codec! */
1317 logf("loading encoder");
1318 ci.stop_encoder = false;
1319 status = codec_load_file((const char *)ev.data, &ci);
1320 logf("encoder stopped");
1321 break;
1322 #endif /* AUDIO_HAVE_RECORDING */
1324 default:
1325 LOGFQUEUE("codec < default");
1328 if (audio_codec_loaded)
1330 if (ci.stop_codec)
1332 status = CODEC_OK;
1333 if (!playing)
1334 pcmbuf_play_stop();
1337 audio_codec_loaded = false;
1340 switch (ev.id) {
1341 case Q_CODEC_LOAD_DISK:
1342 case Q_CODEC_LOAD:
1343 LOGFQUEUE("codec < Q_CODEC_LOAD");
1344 if (playing)
1346 if (ci.new_track || status != CODEC_OK)
1348 if (!ci.new_track)
1350 logf("Codec failure");
1351 gui_syncsplash(HZ*2, "Codec failure");
1354 if (!codec_load_next_track())
1356 LOGFQUEUE("codec > audio Q_AUDIO_STOP");
1357 /* End of playlist */
1358 queue_post(&audio_queue, Q_AUDIO_STOP, 0);
1359 break;
1362 else
1364 logf("Codec finished");
1365 if (ci.stop_codec)
1367 /* Wait for the audio to stop playing before
1368 * triggering the WPS exit */
1369 while(pcm_is_playing())
1371 curtrack_id3.elapsed =
1372 curtrack_id3.length - pcmbuf_get_latency();
1373 sleep(1);
1375 LOGFQUEUE("codec > audio Q_AUDIO_STOP");
1376 /* End of playlist */
1377 queue_post(&audio_queue, Q_AUDIO_STOP, 0);
1378 break;
1382 if (CUR_TI->codec_hid >= 0)
1384 LOGFQUEUE("codec > codec Q_CODEC_LOAD");
1385 queue_post(&codec_queue, Q_CODEC_LOAD, 0);
1387 else
1389 const char *codec_fn =
1390 get_codec_filename(curtrack_id3.codectype);
1391 LOGFQUEUE("codec > codec Q_CODEC_LOAD_DISK");
1392 queue_post(&codec_queue, Q_CODEC_LOAD_DISK,
1393 (intptr_t)codec_fn);
1396 break;
1398 #ifdef AUDIO_HAVE_RECORDING
1399 case Q_ENCODER_LOAD_DISK:
1400 LOGFQUEUE("codec < Q_ENCODER_LOAD_DISK");
1402 if (status == CODEC_OK)
1403 break;
1405 logf("Encoder failure");
1406 gui_syncsplash(HZ*2, "Encoder failure");
1408 if (ci.enc_codec_loaded < 0)
1409 break;
1411 logf("Encoder failed to load");
1412 ci.enc_codec_loaded = -1;
1413 break;
1414 #endif /* AUDIO_HAVE_RECORDING */
1416 default:
1417 LOGFQUEUE("codec < default");
1419 } /* end switch */
1424 /* --- Audio thread --- */
1426 static bool audio_have_tracks(void)
1428 return (audio_track_count() != 0);
1431 static int audio_free_track_count(void)
1433 /* Used tracks + free tracks adds up to MAX_TRACK - 1 */
1434 return MAX_TRACK - 1 - audio_track_count();
1437 int audio_track_count(void)
1439 /* Calculate difference from track_ridx to track_widx
1440 * taking into account a possible wrap-around. */
1441 return (MAX_TRACK + track_widx - track_ridx) & MAX_TRACK_MASK;
1444 long audio_filebufused(void)
1446 return (long) buf_used();
1449 /* Update track info after successful a codec track change */
1450 static void audio_update_trackinfo(void)
1452 /* Load the curent track's metadata into curtrack_id3 */
1453 CUR_TI->taginfo_ready = (CUR_TI->id3_hid >= 0);
1454 if (CUR_TI->id3_hid >= 0)
1455 copy_mp3entry(&curtrack_id3, bufgetid3(CUR_TI->id3_hid));
1457 int next_idx = (track_ridx + 1) & MAX_TRACK_MASK;
1458 tracks[next_idx].taginfo_ready = (tracks[next_idx].id3_hid >= 0);
1460 /* Reset current position */
1461 curtrack_id3.elapsed = 0;
1462 curtrack_id3.offset = 0;
1464 /* Update the codec API */
1465 ci.filesize = CUR_TI->filesize;
1466 ci.id3 = &curtrack_id3;
1467 ci.curpos = 0;
1468 ci.taginfo_ready = &CUR_TI->taginfo_ready;
1471 static void buffering_audio_callback(enum callback_event ev, int value)
1473 (void)value;
1474 logf("buffering_audio_callback");
1476 switch (ev)
1478 case EVENT_BUFFER_LOW:
1479 LOGFQUEUE("buffering > audio Q_AUDIO_FILL_BUFFER");
1480 queue_post(&audio_queue, Q_AUDIO_FILL_BUFFER, 0);
1481 break;
1483 case EVENT_HANDLE_REBUFFER:
1484 LOGFQUEUE("audio >| audio Q_AUDIO_FLUSH");
1485 queue_send(&audio_queue, Q_AUDIO_FLUSH, 0);
1486 break;
1488 case EVENT_HANDLE_FINISHED:
1489 strip_tags(value);
1490 break;
1492 default:
1493 break;
1497 /* Clear tracks between write and read, non inclusive */
1498 static void audio_clear_track_entries(bool clear_unbuffered)
1500 int cur_idx = track_widx;
1502 logf("Clearing tracks:%d/%d, %d", track_ridx, track_widx, clear_unbuffered);
1504 /* Loop over all tracks from write-to-read */
1505 while (1)
1507 cur_idx = (cur_idx + 1) & MAX_TRACK_MASK;
1509 if (cur_idx == track_ridx)
1510 break;
1512 /* If the track is buffered, conditionally clear/notify,
1513 * otherwise clear the track if that option is selected */
1514 if (tracks[cur_idx].event_sent || clear_unbuffered)
1515 clear_track_info(&tracks[cur_idx]);
1519 /* Clear all tracks */
1520 static bool audio_release_tracks(void)
1522 int i, cur_idx;
1524 logf("releasing all tracks");
1526 for(i = 0; i < MAX_TRACK; i++)
1528 cur_idx = (track_ridx + i) & MAX_TRACK_MASK;
1529 if (!clear_track_info(&tracks[cur_idx]))
1530 return false;
1533 return true;
1536 static bool audio_loadcodec(bool start_play)
1538 int prev_track;
1539 char codec_path[MAX_PATH]; /* Full path to codec */
1541 if (tracks[track_widx].id3_hid < 0) {
1542 return false;
1545 const char * codec_fn =
1546 get_codec_filename(bufgetid3(tracks[track_widx].id3_hid)->codectype);
1547 if (codec_fn == NULL)
1548 return false;
1550 tracks[track_widx].codec_hid = -1;
1552 if (start_play)
1554 /* Load the codec directly from disk and save some memory. */
1555 track_ridx = track_widx;
1556 ci.filesize = CUR_TI->filesize;
1557 ci.id3 = &curtrack_id3;
1558 ci.taginfo_ready = &CUR_TI->taginfo_ready;
1559 ci.curpos = 0;
1560 LOGFQUEUE("codec > codec Q_CODEC_LOAD_DISK");
1561 queue_post(&codec_queue, Q_CODEC_LOAD_DISK, (intptr_t)codec_fn);
1562 return true;
1564 else
1566 /* If we already have another track than this one buffered */
1567 if (track_widx != track_ridx)
1569 prev_track = (track_widx - 1) & MAX_TRACK_MASK;
1571 /* If the previous codec is the same as this one, there is no need
1572 * to put another copy of it on the file buffer */
1573 if (get_codec_base_type(
1574 bufgetid3(tracks[track_widx].id3_hid)->codectype) ==
1575 get_codec_base_type(
1576 bufgetid3(tracks[prev_track].id3_hid)->codectype)
1577 && audio_codec_loaded)
1579 logf("Reusing prev. codec");
1580 return true;
1585 codec_get_full_path(codec_path, codec_fn);
1587 tracks[track_widx].codec_hid = bufopen(codec_path, 0, TYPE_CODEC);
1588 if (tracks[track_widx].codec_hid < 0)
1589 return false;
1591 logf("Loaded codec");
1593 return true;
1596 /* TODO: Copied from mpeg.c. Should be moved somewhere else. */
1597 static void audio_set_elapsed(struct mp3entry* id3)
1599 unsigned long offset = id3->offset > id3->first_frame_offset ?
1600 id3->offset - id3->first_frame_offset : 0;
1602 if ( id3->vbr ) {
1603 if ( id3->has_toc ) {
1604 /* calculate elapsed time using TOC */
1605 int i;
1606 unsigned int remainder, plen, relpos, nextpos;
1608 /* find wich percent we're at */
1609 for (i=0; i<100; i++ )
1610 if ( offset < id3->toc[i] * (id3->filesize / 256) )
1611 break;
1613 i--;
1614 if (i < 0)
1615 i = 0;
1617 relpos = id3->toc[i];
1619 if (i < 99)
1620 nextpos = id3->toc[i+1];
1621 else
1622 nextpos = 256;
1624 remainder = offset - (relpos * (id3->filesize / 256));
1626 /* set time for this percent (divide before multiply to prevent
1627 overflow on long files. loss of precision is negligible on
1628 short files) */
1629 id3->elapsed = i * (id3->length / 100);
1631 /* calculate remainder time */
1632 plen = (nextpos - relpos) * (id3->filesize / 256);
1633 id3->elapsed += (((remainder * 100) / plen) *
1634 (id3->length / 10000));
1636 else {
1637 /* no TOC exists. set a rough estimate using average bitrate */
1638 int tpk = id3->length /
1639 ((id3->filesize - id3->first_frame_offset - id3->id3v1len) /
1640 1024);
1641 id3->elapsed = offset / 1024 * tpk;
1644 else
1646 /* constant bitrate, use exact calculation */
1647 if (id3->bitrate != 0)
1648 id3->elapsed = offset / (id3->bitrate / 8);
1652 /* Load one track by making the appropriate bufopen calls. Return true if
1653 everything required was loaded correctly, false if not. */
1654 static bool audio_load_track(int offset, bool start_play)
1656 char *trackname;
1657 char msgbuf[80];
1658 int fd = -1;
1659 int file_offset = 0;
1660 struct mp3entry id3;
1662 /* Stop buffer filling if there is no free track entries.
1663 Don't fill up the last track entry (we wan't to store next track
1664 metadata there). */
1665 if (!audio_free_track_count())
1667 logf("No free tracks");
1668 return false;
1671 last_peek_offset++;
1672 peek_again:
1673 logf("Buffering track:%d/%d", track_widx, track_ridx);
1674 /* Get track name from current playlist read position. */
1675 while ((trackname = playlist_peek(last_peek_offset)) != NULL)
1677 /* Handle broken playlists. */
1678 fd = open(trackname, O_RDONLY);
1679 if (fd < 0)
1681 logf("Open failed");
1682 /* Skip invalid entry from playlist. */
1683 playlist_skip_entry(NULL, last_peek_offset);
1685 else
1686 break;
1689 if (!trackname)
1691 logf("End-of-playlist");
1692 playlist_end = true;
1693 memset(&lasttrack_id3, 0, sizeof(struct mp3entry));
1694 return false;
1697 tracks[track_widx].filesize = filesize(fd);
1699 /* Set default values */
1700 if (start_play)
1702 buf_set_watermark(AUDIO_DEFAULT_WATERMARK);
1703 dsp_configure(ci.dsp, DSP_RESET, 0);
1704 track_changed = true;
1705 playlist_update_resume_info(audio_current_track());
1708 /* Get track metadata if we don't already have it. */
1709 if (tracks[track_widx].id3_hid < 0)
1711 if (get_metadata(&id3, fd, trackname))
1713 if (track_buffer_callback)
1714 track_buffer_callback(&id3);
1716 tracks[track_widx].id3_hid =
1717 bufalloc(&id3, sizeof(struct mp3entry), TYPE_ID3);
1718 tracks[track_widx].taginfo_ready = (tracks[track_widx].id3_hid >= 0);
1720 if (tracks[track_widx].id3_hid < 0)
1722 last_peek_offset--;
1723 close(fd);
1724 copy_mp3entry(&lasttrack_id3, &id3);
1725 return false;
1728 if (track_widx == track_ridx)
1729 copy_mp3entry(&curtrack_id3, &id3);
1731 if (start_play)
1733 track_changed = true;
1734 playlist_update_resume_info(audio_current_track());
1737 else
1739 logf("mde:%s!",trackname);
1741 /* Skip invalid entry from playlist. */
1742 playlist_skip_entry(NULL, last_peek_offset);
1743 tracks[track_widx].taginfo_ready = false;
1744 close(fd);
1745 goto peek_again;
1750 close(fd);
1752 #if 0
1753 if (cuesheet_is_enabled() && tracks[track_widx].id3.cuesheet_type == 1)
1755 char cuepath[MAX_PATH];
1757 struct cuesheet *cue = start_play ? curr_cue : temp_cue;
1759 if (look_for_cuesheet_file(trackname, cuepath) &&
1760 parse_cuesheet(cuepath, cue))
1762 strcpy((cue)->audio_filename, trackname);
1763 if (start_play)
1764 cue_spoof_id3(curr_cue, &tracks[track_widx].id3);
1767 #endif
1769 struct mp3entry *track_id3;
1771 if (track_widx == track_ridx)
1772 track_id3 = &curtrack_id3;
1773 else
1774 track_id3 = bufgetid3(tracks[track_widx].id3_hid);
1776 #ifdef HAVE_ALBUMART
1777 if (tracks[track_widx].aa_hid < 0 && gui_sync_wps_uses_albumart())
1779 char aa_path[MAX_PATH];
1780 if (find_albumart(track_id3, aa_path, sizeof(aa_path)))
1781 tracks[track_widx].aa_hid = bufopen(aa_path, 0, TYPE_BITMAP);
1783 #endif
1785 /* Load the codec. */
1786 if (!audio_loadcodec(start_play))
1788 if (tracks[track_widx].codec_hid == ERR_BUFFER_FULL)
1790 /* No space for codec on buffer, not an error */
1791 return false;
1794 /* This is an error condition, either no codec was found, or reading
1795 * the codec file failed part way through, either way, skip the track */
1796 snprintf(msgbuf, sizeof(msgbuf)-1, "No codec for: %s", trackname);
1797 /* We should not use gui_syncplash from audio thread! */
1798 gui_syncsplash(HZ*2, msgbuf);
1799 /* Skip invalid entry from playlist. */
1800 playlist_skip_entry(NULL, last_peek_offset);
1801 tracks[track_widx].taginfo_ready = false;
1802 goto peek_again;
1805 track_id3->elapsed = 0;
1807 enum data_type type = TYPE_PACKET_AUDIO;
1809 switch (track_id3->codectype) {
1810 case AFMT_MPA_L1:
1811 case AFMT_MPA_L2:
1812 case AFMT_MPA_L3:
1813 if (offset > 0) {
1814 file_offset = offset;
1815 track_id3->offset = offset;
1816 audio_set_elapsed(track_id3);
1818 break;
1820 case AFMT_WAVPACK:
1821 if (offset > 0) {
1822 file_offset = offset;
1823 track_id3->offset = offset;
1824 track_id3->elapsed = track_id3->length / 2;
1826 break;
1828 case AFMT_OGG_VORBIS:
1829 case AFMT_SPEEX:
1830 case AFMT_FLAC:
1831 case AFMT_PCM_WAV:
1832 case AFMT_A52:
1833 case AFMT_AAC:
1834 case AFMT_MPC:
1835 case AFMT_APE:
1836 if (offset > 0)
1837 track_id3->offset = offset;
1838 break;
1840 case AFMT_NSF:
1841 case AFMT_SPC:
1842 case AFMT_SID:
1843 logf("Loading atomic %d",track_id3->codectype);
1844 type = TYPE_ATOMIC_AUDIO;
1845 break;
1848 logf("alt:%s", trackname);
1850 if (file_offset > AUDIO_REBUFFER_GUESS_SIZE)
1851 file_offset -= AUDIO_REBUFFER_GUESS_SIZE;
1852 else if (track_id3->first_frame_offset)
1853 file_offset = track_id3->first_frame_offset;
1854 else
1855 file_offset = 0;
1857 tracks[track_widx].audio_hid = bufopen(trackname, file_offset, type);
1859 if (tracks[track_widx].audio_hid < 0)
1860 return false;
1862 if (start_play)
1864 ci.curpos=file_offset;
1865 buf_request_buffer_handle(tracks[track_widx].audio_hid);
1868 track_widx = (track_widx + 1) & MAX_TRACK_MASK;
1870 return true;
1873 /* Send callback events to notify about new tracks. */
1874 static void audio_generate_postbuffer_events(void)
1876 int cur_idx;
1878 logf("Postbuffer:%d/%d",track_ridx,track_widx);
1880 if (audio_have_tracks())
1882 cur_idx = track_ridx;
1884 while (1) {
1885 if (!tracks[cur_idx].event_sent)
1887 /* Mark the event 'sent' even if we don't really send one */
1888 tracks[cur_idx].event_sent = true;
1890 if (cur_idx == track_widx)
1891 break;
1892 cur_idx = (cur_idx + 1) & MAX_TRACK_MASK;
1897 static void audio_fill_file_buffer(bool start_play, size_t offset)
1899 struct queue_event ev;
1900 bool had_next_track = audio_next_track() != NULL;
1901 bool continue_buffering;
1903 /* Must reset the buffer before use if trashed or voice only - voice
1904 file size shouldn't have changed so we can go straight from
1905 BUFFER_STATE_VOICED_ONLY to BUFFER_STATE_INITIALIZED */
1906 if (buffer_state != BUFFER_STATE_INITIALIZED)
1907 audio_reset_buffer();
1909 logf("Starting buffer fill");
1911 if (!start_play)
1912 audio_clear_track_entries(false);
1914 /* Save the current resume position once. */
1915 playlist_update_resume_info(audio_current_track());
1917 do {
1918 continue_buffering = audio_load_track(offset, start_play);
1919 start_play = false;
1920 offset = 0;
1921 sleep(1);
1922 if (queue_peek(&audio_queue, &ev)) {
1923 if (ev.id != Q_AUDIO_FILL_BUFFER)
1925 /* There's a message in the queue. break the loop to treat it,
1926 and go back to filling after that. */
1927 LOGFQUEUE("buffering > audio Q_AUDIO_FILL_BUFFER");
1928 queue_post(&audio_queue, Q_AUDIO_FILL_BUFFER, 0);
1930 break;
1932 } while (continue_buffering);
1934 if (!had_next_track && audio_next_track())
1935 track_changed = true;
1937 audio_generate_postbuffer_events();
1940 static void audio_rebuffer(void)
1942 logf("Forcing rebuffer");
1944 clear_track_info(CUR_TI);
1946 /* Reset track pointers */
1947 track_widx = track_ridx;
1948 audio_clear_track_entries(true);
1950 /* Fill the buffer */
1951 last_peek_offset = -1;
1952 ci.curpos = 0;
1954 if (!CUR_TI->taginfo_ready)
1955 memset(&curtrack_id3, 0, sizeof(struct mp3entry));
1957 audio_fill_file_buffer(false, 0);
1960 /* Called on request from the codec to get a new track. This is the codec part
1961 of the track transition. */
1962 static int audio_check_new_track(void)
1964 int track_count = audio_track_count();
1965 int old_track_ridx = track_ridx;
1966 int i, idx;
1967 bool forward;
1969 if (dir_skip)
1971 dir_skip = false;
1972 if (playlist_next_dir(ci.new_track))
1974 ci.new_track = 0;
1975 audio_rebuffer();
1976 goto skip_done;
1978 else
1980 LOGFQUEUE("audio >|= codec Q_CODEC_REQUEST_FAILED");
1981 return Q_CODEC_REQUEST_FAILED;
1985 if (new_playlist)
1986 ci.new_track = 0;
1988 /* If the playlist isn't that big */
1989 if (!playlist_check(ci.new_track))
1991 if (ci.new_track >= 0)
1993 LOGFQUEUE("audio >|= codec Q_CODEC_REQUEST_FAILED");
1994 return Q_CODEC_REQUEST_FAILED;
1996 /* Find the beginning backward if the user over-skips it */
1997 while (!playlist_check(++ci.new_track))
1998 if (ci.new_track >= 0)
2000 LOGFQUEUE("audio >|= codec Q_CODEC_REQUEST_FAILED");
2001 return Q_CODEC_REQUEST_FAILED;
2004 /* Update the playlist */
2005 last_peek_offset -= ci.new_track;
2007 if (playlist_next(ci.new_track) < 0)
2009 LOGFQUEUE("audio >|= codec Q_CODEC_REQUEST_FAILED");
2010 return Q_CODEC_REQUEST_FAILED;
2013 if (new_playlist)
2015 ci.new_track = 1;
2016 new_playlist = false;
2019 /* Save the track metadata to allow the WPS to display it
2020 while PCM finishes playing that track */
2021 copy_mp3entry(&prevtrack_id3, &curtrack_id3);
2023 /* Update the main buffer copy of the track metadata with the one
2024 the codec has been using (for the unbuffer callbacks) */
2025 if (CUR_TI->id3_hid >= 0)
2026 copy_mp3entry(bufgetid3(CUR_TI->id3_hid), &curtrack_id3);
2028 /* Save a pointer to the old track to allow later clearing */
2029 prev_ti = CUR_TI;
2031 for (i = 0; i < ci.new_track; i++)
2033 idx = (track_ridx + i) & MAX_TRACK_MASK;
2034 struct mp3entry *id3 = bufgetid3(tracks[idx].id3_hid);
2035 ssize_t offset = buf_handle_offset(tracks[idx].audio_hid);
2036 if (!id3 || offset < 0 || (unsigned)offset > id3->first_frame_offset)
2038 /* We don't have all the audio data for that track, so clear it,
2039 but keep the metadata. */
2040 if (tracks[idx].audio_hid >= 0 && bufclose(tracks[idx].audio_hid))
2042 tracks[idx].audio_hid = -1;
2043 tracks[idx].filesize = 0;
2048 /* Move to the new track */
2049 track_ridx = (track_ridx + ci.new_track) & MAX_TRACK_MASK;
2051 buf_set_base_handle(CUR_TI->audio_hid);
2053 if (automatic_skip)
2055 playlist_end = false;
2056 wps_offset = -ci.new_track;
2059 track_changed = true;
2061 /* If it is not safe to even skip this many track entries */
2062 if (ci.new_track >= track_count || ci.new_track <= track_count - MAX_TRACK)
2064 ci.new_track = 0;
2065 audio_rebuffer();
2066 goto skip_done;
2069 forward = ci.new_track > 0;
2070 ci.new_track = 0;
2072 /* If the target track is clearly not in memory */
2073 if (CUR_TI->filesize == 0 || !CUR_TI->taginfo_ready)
2075 audio_rebuffer();
2076 goto skip_done;
2079 /* When skipping backwards, it is possible that we've found a track that's
2080 * buffered, but which is around the track-wrap and therefor not the track
2081 * we are looking for */
2082 if (!forward)
2084 int cur_idx = track_ridx;
2085 bool taginfo_ready = true;
2086 /* We've wrapped the buffer backwards if new > old */
2087 bool wrap = track_ridx > old_track_ridx;
2089 while (1)
2091 cur_idx = (cur_idx + 1) & MAX_TRACK_MASK;
2093 /* if we've advanced past the wrap when cur_idx is zeroed */
2094 if (!cur_idx)
2095 wrap = false;
2097 /* if we aren't still on the wrap and we've caught the old track */
2098 if (!(wrap || cur_idx < old_track_ridx))
2099 break;
2101 /* If we hit a track in between without valid tag info, bail */
2102 if (!tracks[cur_idx].taginfo_ready)
2104 taginfo_ready = false;
2105 break;
2108 if (!taginfo_ready)
2110 audio_rebuffer();
2114 skip_done:
2115 audio_update_trackinfo();
2116 LOGFQUEUE("audio >|= codec Q_CODEC_REQUEST_COMPLETE");
2117 return Q_CODEC_REQUEST_COMPLETE;
2120 void audio_set_track_buffer_event(void (*handler)(struct mp3entry *id3))
2122 track_buffer_callback = handler;
2125 void audio_set_track_unbuffer_event(void (*handler)(struct mp3entry *id3))
2127 track_unbuffer_callback = handler;
2130 void audio_set_track_changed_event(void (*handler)(struct mp3entry *id3))
2132 track_changed_callback = handler;
2135 unsigned long audio_prev_elapsed(void)
2137 return prev_track_elapsed;
2140 static void audio_stop_codec_flush(void)
2142 ci.stop_codec = true;
2143 pcmbuf_pause(true);
2145 while (audio_codec_loaded)
2146 yield();
2148 /* If the audio codec is not loaded any more, and the audio is still
2149 * playing, it is now and _only_ now safe to call this function from the
2150 * audio thread */
2151 if (pcm_is_playing())
2152 pcmbuf_play_stop();
2153 pcmbuf_pause(paused);
2156 static void audio_stop_playback(void)
2158 /* If we were playing, save resume information */
2159 if (playing)
2161 struct mp3entry *id3 = NULL;
2163 if (!playlist_end || !ci.stop_codec)
2165 /* Set this early, the outside code yields and may allow the codec
2166 to try to wait for a reply on a buffer wait */
2167 ci.stop_codec = true;
2168 id3 = audio_current_track();
2171 /* Save the current playing spot, or NULL if the playlist has ended */
2172 playlist_update_resume_info(id3);
2174 prev_track_elapsed = curtrack_id3.elapsed;
2176 /* At end of playlist save current id3 (id3.elapsed!) to buffer and
2177 * Increment index so runtime info is saved in audio_clear_track_entries().
2179 if ((playlist_end) && (tracks[track_ridx].id3_hid >= 0)) {
2180 copy_mp3entry(bufgetid3(tracks[track_ridx].id3_hid), &curtrack_id3);
2181 track_ridx = (track_ridx + 1) & MAX_TRACK_MASK;
2185 paused = false;
2186 audio_stop_codec_flush();
2187 playing = false;
2189 /* Mark all entries null. */
2190 audio_clear_track_entries(false);
2192 /* Close all tracks */
2193 audio_release_tracks();
2195 unregister_buffering_callback(buffering_audio_callback);
2197 memset(&curtrack_id3, 0, sizeof(struct mp3entry));
2200 static void audio_play_start(size_t offset)
2202 int i;
2204 #if INPUT_SRC_CAPS != 0
2205 audio_set_input_source(AUDIO_SRC_PLAYBACK, SRCF_PLAYBACK);
2206 audio_set_output_source(AUDIO_SRC_PLAYBACK);
2207 #endif
2209 /* Wait for any previously playing audio to flush - TODO: Not necessary? */
2210 paused = false;
2211 audio_stop_codec_flush();
2213 track_changed = true;
2214 playlist_end = false;
2216 playing = true;
2218 ci.new_track = 0;
2219 ci.seek_time = 0;
2220 wps_offset = 0;
2222 sound_set_volume(global_settings.volume);
2223 track_widx = track_ridx = 0;
2225 /* Clear all track entries. */
2226 for (i = 0; i < MAX_TRACK; i++) {
2227 clear_track_info(&tracks[i]);
2230 last_peek_offset = -1;
2232 /* Officially playing */
2233 queue_reply(&audio_queue, 1);
2235 #ifndef HAVE_FLASH_STORAGE
2236 set_filebuf_watermark(buffer_margin, 0);
2237 #endif
2238 audio_fill_file_buffer(true, offset);
2239 register_buffering_callback(buffering_audio_callback);
2241 LOGFQUEUE("audio > audio Q_AUDIO_TRACK_CHANGED");
2242 queue_post(&audio_queue, Q_AUDIO_TRACK_CHANGED, 0);
2246 /* Invalidates all but currently playing track. */
2247 static void audio_invalidate_tracks(void)
2249 if (audio_have_tracks())
2251 last_peek_offset = 0;
2252 playlist_end = false;
2253 track_widx = track_ridx;
2255 /* Mark all other entries null (also buffered wrong metadata). */
2256 audio_clear_track_entries(true);
2258 track_widx = (track_widx + 1) & MAX_TRACK_MASK;
2260 audio_fill_file_buffer(false, 0);
2264 static void audio_new_playlist(void)
2266 /* Prepare to start a new fill from the beginning of the playlist */
2267 last_peek_offset = -1;
2268 if (audio_have_tracks())
2270 if (paused)
2271 skipped_during_pause = true;
2272 playlist_end = false;
2273 track_widx = track_ridx;
2274 audio_clear_track_entries(true);
2276 track_widx = (track_widx + 1) & MAX_TRACK_MASK;
2278 /* Mark the current track as invalid to prevent skipping back to it */
2279 CUR_TI->taginfo_ready = false;
2282 /* Signal the codec to initiate a track change forward */
2283 new_playlist = true;
2284 ci.new_track = 1;
2286 /* Officially playing */
2287 queue_reply(&audio_queue, 1);
2289 audio_fill_file_buffer(false, 0);
2292 static void audio_initiate_track_change(long direction)
2294 playlist_end = false;
2295 ci.new_track += direction;
2296 wps_offset -= direction;
2297 if (paused)
2298 skipped_during_pause = true;
2301 static void audio_initiate_dir_change(long direction)
2303 playlist_end = false;
2304 dir_skip = true;
2305 ci.new_track = direction;
2306 if (paused)
2307 skipped_during_pause = true;
2310 /* Called when PCM track change is complete */
2311 static void audio_finalise_track_change(void)
2313 logf("audio_finalise_track_change");
2315 if (automatic_skip)
2317 wps_offset = 0;
2318 automatic_skip = false;
2321 /* Invalidate prevtrack_id3 */
2322 prevtrack_id3.path[0] = 0;
2324 if (prev_ti && prev_ti->audio_hid < 0)
2326 /* No audio left so we clear all the track info. */
2327 clear_track_info(prev_ti);
2330 if (track_changed_callback)
2331 track_changed_callback(&curtrack_id3);
2333 track_changed = true;
2334 playlist_update_resume_info(audio_current_track());
2338 * Layout audio buffer as follows - iram buffer depends on target:
2339 * [|SWAP:iram][|TALK]|MALLOC|FILE|GUARD|PCM|[SWAP:dram[|iram]|]
2341 static void audio_reset_buffer(void)
2343 /* see audio_get_recording_buffer if this is modified */
2344 logf("audio_reset_buffer");
2346 /* If the setup of anything allocated before the file buffer is
2347 changed, do check the adjustments after the buffer_alloc call
2348 as it will likely be affected and need sliding over */
2350 /* Initially set up file buffer as all space available */
2351 malloc_buf = audiobuf + talk_get_bufsize();
2352 /* Align the malloc buf to line size. Especially important to cf
2353 targets that do line reads/writes. */
2354 malloc_buf = (unsigned char *)(((uintptr_t)malloc_buf + 15) & ~15);
2355 filebuf = malloc_buf + MALLOC_BUFSIZE; /* filebuf line align implied */
2356 filebuflen = audiobufend - filebuf;
2358 filebuflen &= ~15;
2360 /* Subtract whatever the pcm buffer says it used plus the guard buffer */
2361 filebuflen -= pcmbuf_init(filebuf + filebuflen) + GUARD_BUFSIZE;
2363 /* Make sure filebuflen is a longword multiple after adjustment - filebuf
2364 will already be line aligned */
2365 filebuflen &= ~3;
2367 buffering_reset(filebuf, filebuflen);
2369 /* Clear any references to the file buffer */
2370 buffer_state = BUFFER_STATE_INITIALIZED;
2372 #if defined(ROCKBOX_HAS_LOGF) && defined(LOGF_ENABLE)
2373 /* Make sure everything adds up - yes, some info is a bit redundant but
2374 aids viewing and the sumation of certain variables should add up to
2375 the location of others. */
2377 size_t pcmbufsize;
2378 unsigned char * pcmbuf = pcmbuf_get_meminfo(&pcmbufsize);
2379 logf("mabuf: %08X", (unsigned)malloc_buf);
2380 logf("mabufe: %08X", (unsigned)(malloc_buf + MALLOC_BUFSIZE));
2381 logf("fbuf: %08X", (unsigned)filebuf);
2382 logf("fbufe: %08X", (unsigned)(filebuf + filebuflen));
2383 logf("gbuf: %08X", (unsigned)(filebuf + filebuflen));
2384 logf("gbufe: %08X", (unsigned)(filebuf + filebuflen + GUARD_BUFSIZE));
2385 logf("pcmb: %08X", (unsigned)pcmbuf);
2386 logf("pcmbe: %08X", (unsigned)(pcmbuf + pcmbufsize));
2388 #endif
2391 static void audio_thread(void)
2393 struct queue_event ev;
2395 pcm_postinit();
2397 audio_thread_ready = true;
2399 while (1)
2401 cancel_cpu_boost();
2402 queue_wait_w_tmo(&audio_queue, &ev, HZ/2);
2404 switch (ev.id) {
2405 case Q_AUDIO_FILL_BUFFER:
2406 LOGFQUEUE("audio < Q_AUDIO_FILL_BUFFER");
2407 if (!playing || playlist_end || ci.stop_codec)
2408 break;
2409 audio_fill_file_buffer(false, 0);
2410 break;
2412 case Q_AUDIO_PLAY:
2413 LOGFQUEUE("audio < Q_AUDIO_PLAY");
2414 if (playing && ev.data <= 0)
2415 audio_new_playlist();
2416 else
2418 audio_stop_playback();
2419 audio_play_start((size_t)ev.data);
2421 break;
2423 case Q_AUDIO_STOP:
2424 LOGFQUEUE("audio < Q_AUDIO_STOP");
2425 if (playing)
2426 audio_stop_playback();
2427 if (ev.data != 0)
2428 queue_clear(&audio_queue);
2429 break;
2431 case Q_AUDIO_PAUSE:
2432 LOGFQUEUE("audio < Q_AUDIO_PAUSE");
2433 if (!(bool) ev.data && skipped_during_pause && !pcmbuf_is_crossfade_active())
2434 pcmbuf_play_stop(); /* Flush old track on resume after skip */
2435 skipped_during_pause = false;
2436 if (!playing)
2437 break;
2438 pcmbuf_pause((bool)ev.data);
2439 paused = (bool)ev.data;
2440 break;
2442 case Q_AUDIO_SKIP:
2443 LOGFQUEUE("audio < Q_AUDIO_SKIP");
2444 audio_initiate_track_change((long)ev.data);
2445 break;
2447 case Q_AUDIO_PRE_FF_REWIND:
2448 LOGFQUEUE("audio < Q_AUDIO_PRE_FF_REWIND");
2449 if (!playing)
2450 break;
2451 pcmbuf_pause(true);
2452 break;
2454 case Q_AUDIO_FF_REWIND:
2455 LOGFQUEUE("audio < Q_AUDIO_FF_REWIND");
2456 if (!playing)
2457 break;
2458 ci.seek_time = (long)ev.data+1;
2459 break;
2461 case Q_AUDIO_CHECK_NEW_TRACK:
2462 LOGFQUEUE("audio < Q_AUDIO_CHECK_NEW_TRACK");
2463 queue_reply(&audio_queue, audio_check_new_track());
2464 break;
2466 case Q_AUDIO_DIR_SKIP:
2467 LOGFQUEUE("audio < Q_AUDIO_DIR_SKIP");
2468 playlist_end = false;
2469 audio_initiate_dir_change(ev.data);
2470 break;
2472 case Q_AUDIO_FLUSH:
2473 LOGFQUEUE("audio < Q_AUDIO_FLUSH");
2474 audio_invalidate_tracks();
2475 break;
2477 case Q_AUDIO_TRACK_CHANGED:
2478 /* PCM track change done */
2479 LOGFQUEUE("audio < Q_AUDIO_TRACK_CHANGED");
2480 audio_finalise_track_change();
2481 break;
2483 #ifndef SIMULATOR
2484 case SYS_USB_CONNECTED:
2485 LOGFQUEUE("audio < SYS_USB_CONNECTED");
2486 if (playing)
2487 audio_stop_playback();
2488 #ifdef PLAYBACK_VOICE
2489 voice_stop();
2490 #endif
2491 usb_acknowledge(SYS_USB_CONNECTED_ACK);
2492 usb_wait_for_disconnect(&audio_queue);
2494 /* Mark all entries null. */
2495 audio_clear_track_entries(false);
2497 /* release tracks to make sure all handles are closed */
2498 audio_release_tracks();
2499 break;
2500 #endif
2502 case SYS_TIMEOUT:
2503 LOGFQUEUE_SYS_TIMEOUT("audio < SYS_TIMEOUT");
2504 break;
2506 default:
2507 LOGFQUEUE("audio < default");
2508 break;
2509 } /* end switch */
2510 } /* end while */
2513 #ifdef ROCKBOX_HAS_LOGF
2514 static void audio_test_track_changed_event(struct mp3entry *id3)
2516 (void)id3;
2518 logf("tce:%s", id3->path);
2520 #endif
2522 /* Initialize the audio system - called from init() in main.c.
2523 * Last function because of all the references to internal symbols
2525 void audio_init(void)
2527 struct thread_entry *audio_thread_p;
2529 /* Can never do this twice */
2530 if (audio_is_initialized)
2532 logf("audio: already initialized");
2533 return;
2536 logf("audio: initializing");
2538 /* Initialize queues before giving control elsewhere in case it likes
2539 to send messages. Thread creation will be delayed however so nothing
2540 starts running until ready if something yields such as talk_init. */
2541 queue_init(&audio_queue, true);
2542 queue_enable_queue_send(&audio_queue, &audio_queue_sender_list);
2543 queue_init(&codec_queue, false);
2544 queue_enable_queue_send(&codec_queue, &codec_queue_sender_list);
2546 pcm_init();
2548 #ifdef ROCKBOX_HAS_LOGF
2549 audio_set_track_changed_event(audio_test_track_changed_event);
2550 #endif
2552 /* Initialize codec api. */
2553 ci.read_filebuf = codec_filebuf_callback;
2554 ci.pcmbuf_insert = codec_pcmbuf_insert_callback;
2555 ci.get_codec_memory = codec_get_memory_callback;
2556 ci.request_buffer = codec_request_buffer_callback;
2557 ci.advance_buffer = codec_advance_buffer_callback;
2558 ci.advance_buffer_loc = codec_advance_buffer_loc_callback;
2559 ci.request_next_track = codec_request_next_track_callback;
2560 ci.mp3_get_filepos = codec_mp3_get_filepos_callback;
2561 ci.seek_buffer = codec_seek_buffer_callback;
2562 ci.seek_complete = codec_seek_complete_callback;
2563 ci.set_elapsed = codec_set_elapsed_callback;
2564 ci.set_offset = codec_set_offset_callback;
2565 ci.configure = codec_configure_callback;
2566 ci.discard_codec = codec_discard_codec_callback;
2567 ci.dsp = (struct dsp_config *)dsp_configure(NULL, DSP_MYDSP,
2568 CODEC_IDX_AUDIO);
2570 /* initialize the buffer */
2571 filebuf = audiobuf;
2573 /* audio_reset_buffer must to know the size of voice buffer so init
2574 talk first */
2575 talk_init();
2577 codec_thread_p = create_thread(
2578 codec_thread, codec_stack, sizeof(codec_stack),
2579 CREATE_THREAD_FROZEN,
2580 codec_thread_name IF_PRIO(, PRIORITY_PLAYBACK)
2581 IF_COP(, CPU));
2583 audio_thread_p = create_thread(audio_thread, audio_stack,
2584 sizeof(audio_stack), CREATE_THREAD_FROZEN,
2585 audio_thread_name IF_PRIO(, PRIORITY_SYSTEM)
2586 IF_COP(, CPU));
2588 #ifdef PLAYBACK_VOICE
2589 voice_thread_init();
2590 #endif
2592 /* Set crossfade setting for next buffer init which should be about... */
2593 pcmbuf_crossfade_enable(global_settings.crossfade);
2595 /* initialize the buffering system */
2597 buffering_init();
2598 /* ...now! Set up the buffers */
2599 audio_reset_buffer();
2601 int i;
2602 for(i = 0; i < MAX_TRACK; i++)
2604 tracks[i].audio_hid = -1;
2605 tracks[i].id3_hid = -1;
2606 tracks[i].codec_hid = -1;
2607 #ifdef HAVE_ALBUMART
2608 tracks[i].aa_hid = -1;
2609 #endif
2612 /* Probably safe to say */
2613 audio_is_initialized = true;
2615 sound_settings_apply();
2616 #ifndef HAVE_FLASH_STORAGE
2617 audio_set_buffer_margin(global_settings.buffer_margin);
2618 #endif
2620 /* it's safe to let the threads run now */
2621 #ifdef PLAYBACK_VOICE
2622 voice_thread_resume();
2623 #endif
2624 thread_thaw(codec_thread_p);
2625 thread_thaw(audio_thread_p);
2627 } /* audio_init */
2629 void audio_wait_for_init(void)
2631 /* audio thread will only set this once after it finished the final
2632 * audio hardware init so this little construct is safe - even
2633 * cross-core. */
2634 while (!audio_thread_ready)
2636 sleep(0);