set YOFS to 0 for portrait LCDs.
[kugel-rb.git] / apps / playback.c
blobcee89d3bbba4868d9f140290b26c8ee457926199
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 strlcpy(write_id3->path, filename, sizeof(write_id3->path));
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 seeking-while-playing, pcm playback is actually paused (pcm_is_paused())
1102 * but the paused flag is not set. If seeking-while-paused, the (paused) flag is
1103 * set, but pcm playback may have actually stopped due to a previous buffer clear.
1104 * The buffer clear below occurs with either condition. A seemless seek skips
1105 * this section and no buffer clear occurs.
1107 if (pcm_is_paused() || paused)
1109 /* Clear the buffer */
1110 pcmbuf_play_stop();
1111 dsp_configure(ci.dsp, DSP_FLUSH, 0);
1113 /* If seeking-while-playing, resume pcm playback */
1114 if (!paused)
1115 pcmbuf_pause(false);
1117 ci.seek_time = 0;
1120 static bool codec_seek_buffer_callback(size_t newpos)
1122 logf("codec_seek_buffer_callback");
1124 int ret = bufseek(CUR_TI->audio_hid, newpos);
1125 if (ret == 0) {
1126 ci.curpos = newpos;
1127 return true;
1129 else {
1130 return false;
1134 static void codec_configure_callback(int setting, intptr_t value)
1136 switch (setting) {
1137 default:
1138 if (!dsp_configure(ci.dsp, setting, value))
1139 { logf("Illegal key:%d", setting); }
1143 static void codec_track_changed(void)
1145 LOGFQUEUE("codec > audio Q_AUDIO_TRACK_CHANGED");
1146 queue_post(&audio_queue, Q_AUDIO_TRACK_CHANGED, 0);
1149 static void codec_pcmbuf_track_changed_callback(void)
1151 pcmbuf_set_position_callback(NULL);
1152 pcmbuf_callback_queue_post(Q_AUDIO_TRACK_CHANGED, 0);
1155 static void codec_discard_codec_callback(void)
1157 if (CUR_TI->codec_hid >= 0)
1159 bufclose(CUR_TI->codec_hid);
1160 CUR_TI->codec_hid = -1;
1164 static inline void codec_gapless_track_change(void)
1166 /* callback keeps the progress bar moving while the pcmbuf empties */
1167 pcmbuf_set_position_callback(codec_pcmbuf_position_callback);
1168 /* set the pcmbuf callback for when the track really changes */
1169 pcmbuf_set_event_handler(codec_pcmbuf_track_changed_callback);
1172 static inline void codec_crossfade_track_change(void)
1174 /* Initiate automatic crossfade mode */
1175 pcmbuf_crossfade_init(false);
1176 /* Notify the wps that the track change starts now */
1177 codec_track_changed();
1180 static void codec_track_skip_done(bool was_manual)
1182 /* Manual track change (always crossfade or flush audio). */
1183 if (was_manual)
1185 pcmbuf_crossfade_init(true);
1186 LOGFQUEUE("codec > audio Q_AUDIO_TRACK_CHANGED");
1187 queue_post(&audio_queue, Q_AUDIO_TRACK_CHANGED, 0);
1189 /* Automatic track change w/crossfade, if not in "Track Skip Only" mode. */
1190 else if (pcmbuf_is_crossfade_enabled() && !pcmbuf_is_crossfade_active()
1191 && global_settings.crossfade != CROSSFADE_ENABLE_TRACKSKIP)
1193 if (global_settings.crossfade == CROSSFADE_ENABLE_SHUFFLE_AND_TRACKSKIP)
1195 if (global_settings.playlist_shuffle)
1196 /* shuffle mode is on, so crossfade: */
1197 codec_crossfade_track_change();
1198 else
1199 /* shuffle mode is off, so do a gapless track change */
1200 codec_gapless_track_change();
1202 else
1203 /* normal crossfade: */
1204 codec_crossfade_track_change();
1206 else
1207 /* normal gapless playback. */
1208 codec_gapless_track_change();
1211 static bool codec_load_next_track(void)
1213 intptr_t result = Q_CODEC_REQUEST_FAILED;
1215 prev_track_elapsed = thistrack_id3->elapsed;
1217 #ifdef AB_REPEAT_ENABLE
1218 ab_end_of_track_report();
1219 #endif
1221 logf("Request new track");
1223 if (ci.new_track == 0)
1225 ci.new_track++;
1226 automatic_skip = true;
1229 if (!ci.stop_codec)
1231 trigger_cpu_boost();
1232 LOGFQUEUE("codec >| audio Q_AUDIO_CHECK_NEW_TRACK");
1233 result = queue_send(&audio_queue, Q_AUDIO_CHECK_NEW_TRACK, 0);
1236 switch (result)
1238 case Q_CODEC_REQUEST_COMPLETE:
1239 LOGFQUEUE("codec |< Q_CODEC_REQUEST_COMPLETE");
1240 codec_track_skip_done(!automatic_skip);
1241 return true;
1243 case Q_CODEC_REQUEST_FAILED:
1244 LOGFQUEUE("codec |< Q_CODEC_REQUEST_FAILED");
1245 ci.new_track = 0;
1246 ci.stop_codec = true;
1247 codec_requested_stop = true;
1248 return false;
1250 default:
1251 LOGFQUEUE("codec |< default");
1252 ci.stop_codec = true;
1253 codec_requested_stop = true;
1254 return false;
1258 static bool codec_request_next_track_callback(void)
1260 int prev_codectype;
1262 if (ci.stop_codec || !playing)
1263 return false;
1265 prev_codectype = get_codec_base_type(thistrack_id3->codectype);
1266 if (!codec_load_next_track())
1267 return false;
1269 /* Seek to the beginning of the new track because if the struct
1270 mp3entry was buffered, "elapsed" might not be zero (if the track has
1271 been played already but not unbuffered) */
1272 codec_seek_buffer_callback(thistrack_id3->first_frame_offset);
1273 /* Check if the next codec is the same file. */
1274 if (prev_codectype == get_codec_base_type(thistrack_id3->codectype))
1276 logf("New track loaded");
1277 codec_discard_codec_callback();
1278 return true;
1280 else
1282 logf("New codec:%d/%d", thistrack_id3->codectype, prev_codectype);
1283 return false;
1287 static void codec_thread(void)
1289 struct queue_event ev;
1290 int status;
1292 while (1) {
1293 status = 0;
1295 if (!pcmbuf_is_crossfade_active()) {
1296 cancel_cpu_boost();
1299 queue_wait(&codec_queue, &ev);
1300 codec_requested_stop = false;
1302 switch (ev.id) {
1303 case Q_CODEC_LOAD_DISK:
1304 LOGFQUEUE("codec < Q_CODEC_LOAD_DISK");
1305 queue_reply(&codec_queue, 1);
1306 audio_codec_loaded = true;
1307 ci.stop_codec = false;
1308 status = codec_load_file((const char *)ev.data, &ci);
1309 LOGFQUEUE("codec_load_file %s %d\n", (const char *)ev.data, status);
1310 break;
1312 case Q_CODEC_LOAD:
1313 LOGFQUEUE("codec < Q_CODEC_LOAD");
1314 if (CUR_TI->codec_hid < 0) {
1315 logf("Codec slot is empty!");
1316 /* Wait for the pcm buffer to go empty */
1317 while (pcm_is_playing())
1318 yield();
1319 /* This must be set to prevent an infinite loop */
1320 ci.stop_codec = true;
1321 LOGFQUEUE("codec > codec Q_AUDIO_PLAY");
1322 queue_post(&codec_queue, Q_AUDIO_PLAY, 0);
1323 break;
1326 audio_codec_loaded = true;
1327 ci.stop_codec = false;
1328 status = codec_load_buf(CUR_TI->codec_hid, &ci);
1329 LOGFQUEUE("codec_load_buf %d\n", status);
1330 break;
1332 case Q_CODEC_DO_CALLBACK:
1333 LOGFQUEUE("codec < Q_CODEC_DO_CALLBACK");
1334 queue_reply(&codec_queue, 1);
1335 if ((void*)ev.data != NULL)
1337 cpucache_invalidate();
1338 ((void (*)(void))ev.data)();
1339 cpucache_flush();
1341 break;
1343 #ifdef AUDIO_HAVE_RECORDING
1344 case Q_ENCODER_LOAD_DISK:
1345 LOGFQUEUE("codec < Q_ENCODER_LOAD_DISK");
1346 audio_codec_loaded = false; /* Not audio codec! */
1347 logf("loading encoder");
1348 ci.stop_encoder = false;
1349 status = codec_load_file((const char *)ev.data, &ci);
1350 logf("encoder stopped");
1351 break;
1352 #endif /* AUDIO_HAVE_RECORDING */
1354 default:
1355 LOGFQUEUE("codec < default");
1358 if (audio_codec_loaded)
1360 if (ci.stop_codec)
1362 status = CODEC_OK;
1363 if (!playing)
1364 pcmbuf_play_stop();
1367 audio_codec_loaded = false;
1370 switch (ev.id) {
1371 case Q_CODEC_LOAD_DISK:
1372 case Q_CODEC_LOAD:
1373 LOGFQUEUE("codec < Q_CODEC_LOAD");
1374 if (playing)
1376 if (ci.new_track || status != CODEC_OK)
1378 if (!ci.new_track)
1380 logf("Codec failure, %d %d", ci.new_track, status);
1381 splash(HZ*2, "Codec failure");
1384 if (!codec_load_next_track())
1386 LOGFQUEUE("codec > audio Q_AUDIO_STOP");
1387 /* End of playlist */
1388 queue_post(&audio_queue, Q_AUDIO_STOP, 0);
1389 break;
1392 else
1394 logf("Codec finished");
1395 if (ci.stop_codec)
1397 /* Wait for the audio to stop playing before
1398 * triggering the WPS exit */
1399 while(pcm_is_playing())
1401 /* There has been one too many struct pointer swaps by now
1402 * so even though it says othertrack_id3, its the correct one! */
1403 othertrack_id3->elapsed =
1404 othertrack_id3->length - pcmbuf_get_latency();
1405 sleep(1);
1408 if (codec_requested_stop)
1410 LOGFQUEUE("codec > audio Q_AUDIO_STOP");
1411 queue_post(&audio_queue, Q_AUDIO_STOP, 0);
1413 break;
1417 if (CUR_TI->codec_hid >= 0)
1419 LOGFQUEUE("codec > codec Q_CODEC_LOAD");
1420 queue_post(&codec_queue, Q_CODEC_LOAD, 0);
1422 else
1424 const char *codec_fn =
1425 get_codec_filename(thistrack_id3->codectype);
1426 if (codec_fn)
1428 LOGFQUEUE("codec > codec Q_CODEC_LOAD_DISK");
1429 queue_post(&codec_queue, Q_CODEC_LOAD_DISK,
1430 (intptr_t)codec_fn);
1434 break;
1436 #ifdef AUDIO_HAVE_RECORDING
1437 case Q_ENCODER_LOAD_DISK:
1438 LOGFQUEUE("codec < Q_ENCODER_LOAD_DISK");
1440 if (status == CODEC_OK)
1441 break;
1443 logf("Encoder failure");
1444 splash(HZ*2, "Encoder failure");
1446 if (ci.enc_codec_loaded < 0)
1447 break;
1449 logf("Encoder failed to load");
1450 ci.enc_codec_loaded = -1;
1451 break;
1452 #endif /* AUDIO_HAVE_RECORDING */
1454 default:
1455 LOGFQUEUE("codec < default");
1457 } /* end switch */
1461 /* Borrow the codec thread and return the ID */
1462 void codec_thread_do_callback(void (*fn)(void), unsigned int *id)
1464 /* Set id before telling thread to call something; it may be
1465 * needed before this function returns. */
1466 if (id != NULL)
1467 *id = codec_thread_id;
1469 /* Codec thread will signal just before entering callback */
1470 LOGFQUEUE("codec >| Q_CODEC_DO_CALLBACK");
1471 queue_send(&codec_queue, Q_CODEC_DO_CALLBACK, (intptr_t)fn);
1474 /* --- Buffering callbacks --- */
1476 static void buffering_low_buffer_callback(void *data)
1478 (void)data;
1479 logf("low buffer callback");
1481 if (filling == STATE_FULL || filling == STATE_END_OF_PLAYLIST) {
1482 /* force a refill */
1483 LOGFQUEUE("buffering > audio Q_AUDIO_FILL_BUFFER");
1484 queue_post(&audio_queue, Q_AUDIO_FILL_BUFFER, 0);
1488 static void buffering_handle_rebuffer_callback(void *data)
1490 (void)data;
1491 LOGFQUEUE("audio >| audio Q_AUDIO_FLUSH");
1492 queue_post(&audio_queue, Q_AUDIO_FLUSH, 0);
1495 static void buffering_handle_finished_callback(int *data)
1497 logf("handle %d finished buffering", *data);
1499 if (*data == tracks[track_widx].id3_hid)
1501 int offset = ci.new_track + wps_offset;
1502 int next_idx = (track_ridx + offset + 1) & MAX_TRACK_MASK;
1503 /* The metadata handle for the last loaded track has been buffered.
1504 We can ask the audio thread to load the rest of the track's data. */
1505 LOGFQUEUE("audio >| audio Q_AUDIO_FINISH_LOAD");
1506 queue_post(&audio_queue, Q_AUDIO_FINISH_LOAD, 0);
1507 if (tracks[next_idx].id3_hid == *data)
1508 send_event(PLAYBACK_EVENT_NEXTTRACKID3_AVAILABLE, NULL);
1510 else
1512 /* This is most likely an audio handle, so we strip the useless
1513 trailing tags that are left. */
1514 strip_tags(*data);
1516 if (*data == tracks[track_widx-1].audio_hid
1517 && filling == STATE_END_OF_PLAYLIST)
1519 /* This was the last track in the playlist.
1520 We now have all the data we need. */
1521 logf("last track finished buffering");
1522 filling = STATE_FINISHED;
1528 /* --- Audio thread --- */
1530 static bool audio_have_tracks(void)
1532 return (audio_track_count() != 0);
1535 static int audio_free_track_count(void)
1537 /* Used tracks + free tracks adds up to MAX_TRACK - 1 */
1538 return MAX_TRACK - 1 - audio_track_count();
1541 int audio_track_count(void)
1543 /* Calculate difference from track_ridx to track_widx
1544 * taking into account a possible wrap-around. */
1545 return (MAX_TRACK + track_widx - track_ridx) & MAX_TRACK_MASK;
1548 long audio_filebufused(void)
1550 return (long) buf_used();
1553 /* Update track info after successful a codec track change */
1554 static void audio_update_trackinfo(void)
1556 /* Load the curent track's metadata into curtrack_id3 */
1557 if (CUR_TI->id3_hid >= 0)
1558 copy_mp3entry(thistrack_id3, bufgetid3(CUR_TI->id3_hid));
1560 /* Reset current position */
1561 thistrack_id3->elapsed = 0;
1562 thistrack_id3->offset = 0;
1564 /* Update the codec API */
1565 ci.filesize = CUR_TI->filesize;
1566 ci.id3 = thistrack_id3;
1567 ci.curpos = 0;
1568 ci.taginfo_ready = &CUR_TI->taginfo_ready;
1571 /* Clear tracks between write and read, non inclusive */
1572 static void audio_clear_track_entries(void)
1574 int cur_idx = track_widx;
1576 logf("Clearing tracks:%d/%d", track_ridx, track_widx);
1578 /* Loop over all tracks from write-to-read */
1579 while (1)
1581 cur_idx = (cur_idx + 1) & MAX_TRACK_MASK;
1583 if (cur_idx == track_ridx)
1584 break;
1586 clear_track_info(&tracks[cur_idx]);
1590 /* Clear all tracks */
1591 static bool audio_release_tracks(void)
1593 int i, cur_idx;
1595 logf("releasing all tracks");
1597 for(i = 0; i < MAX_TRACK; i++)
1599 cur_idx = (track_ridx + i) & MAX_TRACK_MASK;
1600 if (!clear_track_info(&tracks[cur_idx]))
1601 return false;
1604 return true;
1607 static bool audio_loadcodec(bool start_play)
1609 int prev_track;
1610 char codec_path[MAX_PATH]; /* Full path to codec */
1611 const struct mp3entry *id3, *prev_id3;
1613 if (tracks[track_widx].id3_hid < 0) {
1614 return false;
1617 id3 = bufgetid3(tracks[track_widx].id3_hid);
1618 if (!id3)
1619 return false;
1621 const char *codec_fn = get_codec_filename(id3->codectype);
1622 if (codec_fn == NULL)
1623 return false;
1625 tracks[track_widx].codec_hid = -1;
1627 if (start_play)
1629 /* Load the codec directly from disk and save some memory. */
1630 track_ridx = track_widx;
1631 ci.filesize = CUR_TI->filesize;
1632 ci.id3 = thistrack_id3;
1633 ci.taginfo_ready = &CUR_TI->taginfo_ready;
1634 ci.curpos = 0;
1635 LOGFQUEUE("codec > codec Q_CODEC_LOAD_DISK");
1636 queue_post(&codec_queue, Q_CODEC_LOAD_DISK, (intptr_t)codec_fn);
1637 return true;
1639 else
1641 /* If we already have another track than this one buffered */
1642 if (track_widx != track_ridx)
1644 prev_track = (track_widx - 1) & MAX_TRACK_MASK;
1646 id3 = bufgetid3(tracks[track_widx].id3_hid);
1647 prev_id3 = bufgetid3(tracks[prev_track].id3_hid);
1649 /* If the previous codec is the same as this one, there is no need
1650 * to put another copy of it on the file buffer */
1651 if (id3 && prev_id3 &&
1652 get_codec_base_type(id3->codectype) ==
1653 get_codec_base_type(prev_id3->codectype)
1654 && audio_codec_loaded)
1656 logf("Reusing prev. codec");
1657 return true;
1662 codec_get_full_path(codec_path, codec_fn);
1664 tracks[track_widx].codec_hid = bufopen(codec_path, 0, TYPE_CODEC);
1665 if (tracks[track_widx].codec_hid < 0)
1666 return false;
1668 logf("Loaded codec");
1670 return true;
1673 /* Load metadata for the next track (with bufopen). The rest of the track
1674 loading will be handled by audio_finish_load_track once the metadata has been
1675 actually loaded by the buffering thread. */
1676 static bool audio_load_track(size_t offset, bool start_play)
1678 const char *trackname;
1679 int fd = -1;
1681 if (track_load_started) {
1682 /* There is already a track load in progress, so track_widx hasn't been
1683 incremented yet. Loading another track would overwrite the one that
1684 hasn't finished loading. */
1685 logf("audio_load_track(): a track load is already in progress");
1686 return false;
1689 start_play_g = start_play; /* will be read by audio_finish_load_track */
1691 /* Stop buffer filling if there is no free track entries.
1692 Don't fill up the last track entry (we wan't to store next track
1693 metadata there). */
1694 if (!audio_free_track_count())
1696 logf("No free tracks");
1697 return false;
1700 last_peek_offset++;
1701 tracks[track_widx].taginfo_ready = false;
1703 logf("Buffering track:%d/%d", track_widx, track_ridx);
1704 /* Get track name from current playlist read position. */
1705 while ((trackname = playlist_peek(last_peek_offset)) != NULL)
1707 /* Handle broken playlists. */
1708 fd = open(trackname, O_RDONLY);
1709 if (fd < 0)
1711 logf("Open failed");
1712 /* Skip invalid entry from playlist. */
1713 playlist_skip_entry(NULL, last_peek_offset);
1715 else
1716 break;
1719 if (!trackname)
1721 logf("End-of-playlist");
1722 memset(&unbuffered_id3, 0, sizeof(struct mp3entry));
1723 filling = STATE_END_OF_PLAYLIST;
1725 if (thistrack_id3->length == 0 && thistrack_id3->filesize == 0)
1727 /* Stop playback if no valid track was found. */
1728 audio_stop_playback();
1731 return false;
1734 tracks[track_widx].filesize = filesize(fd);
1736 if (offset > tracks[track_widx].filesize)
1737 offset = 0;
1739 /* Set default values */
1740 if (start_play)
1742 buf_set_watermark(filebuflen/2);
1743 dsp_configure(ci.dsp, DSP_RESET, 0);
1744 playlist_update_resume_info(audio_current_track());
1747 /* Get track metadata if we don't already have it. */
1748 if (tracks[track_widx].id3_hid < 0)
1750 tracks[track_widx].id3_hid = bufopen(trackname, 0, TYPE_ID3);
1752 if (tracks[track_widx].id3_hid < 0)
1754 /* Buffer is full. */
1755 get_metadata(&unbuffered_id3, fd, trackname);
1756 last_peek_offset--;
1757 close(fd);
1758 logf("buffer is full for now");
1759 filling = STATE_FULL;
1760 return false;
1763 if (track_widx == track_ridx)
1765 /* TODO: Superfluos buffering call? */
1766 buf_request_buffer_handle(tracks[track_widx].id3_hid);
1767 struct mp3entry *id3 = bufgetid3(tracks[track_widx].id3_hid);
1768 if (id3)
1770 copy_mp3entry(thistrack_id3, id3);
1771 thistrack_id3->offset = offset;
1773 else
1774 memset(thistrack_id3, 0, sizeof(struct mp3entry));
1777 if (start_play)
1779 playlist_update_resume_info(audio_current_track());
1783 close(fd);
1784 track_load_started = true; /* Remember that we've started loading a track */
1785 return true;
1788 /* Second part of the track loading: We now have the metadata available, so we
1789 can load the codec, the album art and finally the audio data.
1790 This is called on the audio thread after the buffering thread calls the
1791 buffering_handle_finished_callback callback. */
1792 static void audio_finish_load_track(void)
1794 size_t file_offset = 0;
1795 size_t offset = 0;
1796 bool start_play = start_play_g;
1798 track_load_started = false;
1800 if (tracks[track_widx].id3_hid < 0) {
1801 logf("no metatdata");
1802 return;
1805 struct mp3entry *track_id3;
1807 if (track_widx == track_ridx)
1808 track_id3 = thistrack_id3;
1809 else
1810 track_id3 = bufgetid3(tracks[track_widx].id3_hid);
1812 if (track_id3->length == 0 && track_id3->filesize == 0)
1814 logf("audio_finish_load_track: invalid metadata");
1816 /* Invalid metadata */
1817 bufclose(tracks[track_widx].id3_hid);
1818 tracks[track_widx].id3_hid = -1;
1820 /* Skip invalid entry from playlist. */
1821 playlist_skip_entry(NULL, last_peek_offset--);
1823 /* load next track */
1824 LOGFQUEUE("audio > audio Q_AUDIO_FILL_BUFFER %d", (int)start_play);
1825 queue_post(&audio_queue, Q_AUDIO_FILL_BUFFER, start_play);
1827 return;
1830 #ifdef HAVE_ALBUMART
1831 if (tracks[track_widx].aa_hid < 0 && gui_sync_wps_uses_albumart())
1833 char aa_path[MAX_PATH];
1834 if (find_albumart(track_id3, aa_path, sizeof(aa_path)))
1836 tracks[track_widx].aa_hid = bufopen(aa_path, 0, TYPE_BITMAP);
1838 if(tracks[track_widx].aa_hid == ERR_BUFFER_FULL)
1840 filling = STATE_FULL;
1841 logf("buffer is full for now");
1842 return; /* No space for track's album art, not an error */
1844 else if (tracks[track_widx].aa_hid < 0)
1846 /* another error, ignore AlbumArt */
1847 logf("Album art loading failed");
1851 #endif
1853 /* Load the codec. */
1854 if (!audio_loadcodec(start_play))
1856 if (tracks[track_widx].codec_hid == ERR_BUFFER_FULL)
1858 /* No space for codec on buffer, not an error */
1859 filling = STATE_FULL;
1860 return;
1863 /* This is an error condition, either no codec was found, or reading
1864 * the codec file failed part way through, either way, skip the track */
1865 /* FIXME: We should not use splashf from audio thread! */
1866 splashf(HZ*2, "No codec for: %s", track_id3->path);
1867 /* Skip invalid entry from playlist. */
1868 playlist_skip_entry(NULL, last_peek_offset);
1869 return;
1872 track_id3->elapsed = 0;
1873 offset = track_id3->offset;
1875 enum data_type type = TYPE_PACKET_AUDIO;
1877 switch (track_id3->codectype) {
1878 case AFMT_MPA_L1:
1879 case AFMT_MPA_L2:
1880 case AFMT_MPA_L3:
1881 if (offset > 0) {
1882 file_offset = offset;
1883 track_id3->offset = offset;
1885 break;
1887 case AFMT_WAVPACK:
1888 if (offset > 0) {
1889 file_offset = offset;
1890 track_id3->offset = offset;
1891 track_id3->elapsed = track_id3->length / 2;
1893 break;
1895 case AFMT_OGG_VORBIS:
1896 case AFMT_SPEEX:
1897 case AFMT_FLAC:
1898 case AFMT_PCM_WAV:
1899 case AFMT_A52:
1900 case AFMT_AAC:
1901 case AFMT_MPC:
1902 case AFMT_APE:
1903 case AFMT_WMA:
1904 if (offset > 0)
1905 track_id3->offset = offset;
1906 break;
1908 case AFMT_NSF:
1909 case AFMT_SPC:
1910 case AFMT_SID:
1911 logf("Loading atomic %d",track_id3->codectype);
1912 type = TYPE_ATOMIC_AUDIO;
1913 break;
1916 logf("alt:%s", track_id3->path);
1918 if (file_offset > AUDIO_REBUFFER_GUESS_SIZE)
1919 file_offset -= AUDIO_REBUFFER_GUESS_SIZE;
1920 else if (track_id3->first_frame_offset)
1921 file_offset = track_id3->first_frame_offset;
1922 else
1923 file_offset = 0;
1925 tracks[track_widx].audio_hid = bufopen(track_id3->path, file_offset, type);
1927 /* No space left, not an error */
1928 if (tracks[track_widx].audio_hid == ERR_BUFFER_FULL)
1930 filling = STATE_FULL;
1931 logf("buffer is full for now");
1932 return;
1934 else if (tracks[track_widx].audio_hid < 0)
1936 /* another error, do not continue either */
1937 logf("Could not add audio data handle");
1938 return;
1941 /* All required data is now available for the codec. */
1942 tracks[track_widx].taginfo_ready = true;
1944 if (start_play)
1946 ci.curpos=file_offset;
1947 buf_request_buffer_handle(tracks[track_widx].audio_hid);
1950 track_widx = (track_widx + 1) & MAX_TRACK_MASK;
1952 send_event(PLAYBACK_EVENT_TRACK_BUFFER, track_id3);
1954 /* load next track */
1955 LOGFQUEUE("audio > audio Q_AUDIO_FILL_BUFFER");
1956 queue_post(&audio_queue, Q_AUDIO_FILL_BUFFER, 0);
1958 return;
1961 static void audio_fill_file_buffer(bool start_play, size_t offset)
1963 trigger_cpu_boost();
1965 /* No need to rebuffer if there are track skips pending,
1966 * however don't cancel buffering on skipping while filling. */
1967 if (ci.new_track != 0 && filling != STATE_FILLING)
1968 return;
1969 filling = STATE_FILLING;
1971 /* Must reset the buffer before use if trashed or voice only - voice
1972 file size shouldn't have changed so we can go straight from
1973 AUDIOBUF_STATE_VOICED_ONLY to AUDIOBUF_STATE_INITIALIZED */
1974 if (buffer_state != AUDIOBUF_STATE_INITIALIZED)
1975 audio_reset_buffer();
1977 logf("Starting buffer fill");
1979 if (!start_play)
1980 audio_clear_track_entries();
1982 /* Save the current resume position once. */
1983 playlist_update_resume_info(audio_current_track());
1985 audio_load_track(offset, start_play);
1988 static void audio_rebuffer(void)
1990 logf("Forcing rebuffer");
1992 clear_track_info(CUR_TI);
1994 /* Reset track pointers */
1995 track_widx = track_ridx;
1996 audio_clear_track_entries();
1998 /* Reset a possibly interrupted track load */
1999 track_load_started = false;
2001 /* Fill the buffer */
2002 last_peek_offset = -1;
2003 ci.curpos = 0;
2005 if (!CUR_TI->taginfo_ready)
2006 memset(thistrack_id3, 0, sizeof(struct mp3entry));
2008 audio_fill_file_buffer(false, 0);
2011 /* Called on request from the codec to get a new track. This is the codec part
2012 of the track transition. */
2013 static int audio_check_new_track(void)
2015 int track_count = audio_track_count();
2016 int old_track_ridx = track_ridx;
2017 int i, idx;
2018 bool forward;
2019 struct mp3entry *temp = thistrack_id3;
2021 /* Now it's good time to send track finish events. */
2022 send_event(PLAYBACK_EVENT_TRACK_FINISH, thistrack_id3);
2023 /* swap the mp3entry pointers */
2024 thistrack_id3 = othertrack_id3;
2025 othertrack_id3 = temp;
2026 ci.id3 = thistrack_id3;
2027 memset(thistrack_id3, 0, sizeof(struct mp3entry));
2029 if (dir_skip)
2031 dir_skip = false;
2032 /* regardless of the return value we need to rebuffer.
2033 if it fails the old playlist will resume, else the
2034 next dir will start playing */
2035 playlist_next_dir(ci.new_track);
2036 ci.new_track = 0;
2037 audio_rebuffer();
2038 goto skip_done;
2041 if (new_playlist)
2042 ci.new_track = 0;
2044 /* If the playlist isn't that big */
2045 if (automatic_skip)
2047 while (!playlist_check(ci.new_track))
2049 if (ci.new_track >= 0)
2051 LOGFQUEUE("audio >|= codec Q_CODEC_REQUEST_FAILED");
2052 return Q_CODEC_REQUEST_FAILED;
2054 ci.new_track++;
2058 /* Update the playlist */
2059 last_peek_offset -= ci.new_track;
2061 if (playlist_next(ci.new_track) < 0)
2063 LOGFQUEUE("audio >|= codec Q_CODEC_REQUEST_FAILED");
2064 return Q_CODEC_REQUEST_FAILED;
2067 if (new_playlist)
2069 ci.new_track = 1;
2070 new_playlist = false;
2073 /* Save a pointer to the old track to allow later clearing */
2074 prev_ti = CUR_TI;
2076 for (i = 0; i < ci.new_track; i++)
2078 idx = (track_ridx + i) & MAX_TRACK_MASK;
2079 struct mp3entry *id3 = bufgetid3(tracks[idx].id3_hid);
2080 ssize_t offset = buf_handle_offset(tracks[idx].audio_hid);
2081 if (!id3 || offset < 0 || (unsigned)offset > id3->first_frame_offset)
2083 /* We don't have all the audio data for that track, so clear it,
2084 but keep the metadata. */
2085 if (tracks[idx].audio_hid >= 0 && bufclose(tracks[idx].audio_hid))
2087 tracks[idx].audio_hid = -1;
2088 tracks[idx].filesize = 0;
2093 /* Move to the new track */
2094 track_ridx = (track_ridx + ci.new_track) & MAX_TRACK_MASK;
2096 buf_set_base_handle(CUR_TI->audio_hid);
2098 if (automatic_skip)
2100 wps_offset = -ci.new_track;
2103 /* If it is not safe to even skip this many track entries */
2104 if (ci.new_track >= track_count || ci.new_track <= track_count - MAX_TRACK)
2106 ci.new_track = 0;
2107 audio_rebuffer();
2108 goto skip_done;
2111 forward = ci.new_track > 0;
2112 ci.new_track = 0;
2114 /* If the target track is clearly not in memory */
2115 if (CUR_TI->filesize == 0 || !CUR_TI->taginfo_ready)
2117 audio_rebuffer();
2118 goto skip_done;
2121 /* When skipping backwards, it is possible that we've found a track that's
2122 * buffered, but which is around the track-wrap and therefore not the track
2123 * we are looking for */
2124 if (!forward)
2126 int cur_idx = track_ridx;
2127 bool taginfo_ready = true;
2128 /* We've wrapped the buffer backwards if new > old */
2129 bool wrap = track_ridx > old_track_ridx;
2131 while (1)
2133 cur_idx = (cur_idx + 1) & MAX_TRACK_MASK;
2135 /* if we've advanced past the wrap when cur_idx is zeroed */
2136 if (!cur_idx)
2137 wrap = false;
2139 /* if we aren't still on the wrap and we've caught the old track */
2140 if (!(wrap || cur_idx < old_track_ridx))
2141 break;
2143 /* If we hit a track in between without valid tag info, bail */
2144 if (!tracks[cur_idx].taginfo_ready)
2146 taginfo_ready = false;
2147 break;
2150 if (!taginfo_ready)
2152 audio_rebuffer();
2156 skip_done:
2157 audio_update_trackinfo();
2158 LOGFQUEUE("audio >|= codec Q_CODEC_REQUEST_COMPLETE");
2159 return Q_CODEC_REQUEST_COMPLETE;
2162 unsigned long audio_prev_elapsed(void)
2164 return prev_track_elapsed;
2167 static void audio_stop_codec_flush(void)
2169 ci.stop_codec = true;
2170 pcmbuf_pause(true);
2172 while (audio_codec_loaded)
2173 yield();
2175 /* If the audio codec is not loaded any more, and the audio is still
2176 * playing, it is now and _only_ now safe to call this function from the
2177 * audio thread */
2178 if (pcm_is_playing())
2180 pcmbuf_play_stop();
2181 pcmbuf_queue_clear();
2183 pcmbuf_pause(paused);
2186 static void audio_stop_playback(void)
2188 if (playing)
2190 /* If still actively playing here, play out the last samples in the track
2191 * before stopping. A manual stop is actually paused at this point, so
2192 * don't continue playback.
2194 if (!paused)
2195 pcmbuf_play_remainder();
2197 /* If we were playing, save resume information */
2198 struct mp3entry *id3 = NULL;
2200 if (!ci.stop_codec)
2202 /* Set this early, the outside code yields and may allow the codec
2203 to try to wait for a reply on a buffer wait */
2204 ci.stop_codec = true;
2205 id3 = audio_current_track();
2208 /* Save the current playing spot, or NULL if the playlist has ended */
2209 playlist_update_resume_info(id3);
2211 /* TODO: Create auto bookmark too? */
2213 prev_track_elapsed = othertrack_id3->elapsed;
2215 remove_event(BUFFER_EVENT_BUFFER_LOW, buffering_low_buffer_callback);
2218 audio_stop_codec_flush();
2219 paused = false;
2220 playing = false;
2221 track_load_started = false;
2223 filling = STATE_IDLE;
2225 /* Mark all entries null. */
2226 audio_clear_track_entries();
2228 /* Close all tracks */
2229 audio_release_tracks();
2232 static void audio_play_start(size_t offset)
2234 int i;
2236 #if INPUT_SRC_CAPS != 0
2237 audio_set_input_source(AUDIO_SRC_PLAYBACK, SRCF_PLAYBACK);
2238 audio_set_output_source(AUDIO_SRC_PLAYBACK);
2239 #endif
2241 /* Wait for any previously playing audio to flush - TODO: Not necessary? */
2242 paused = false;
2243 audio_stop_codec_flush();
2245 playing = true;
2246 track_load_started = false;
2248 ci.new_track = 0;
2249 ci.seek_time = 0;
2250 wps_offset = 0;
2252 sound_set_volume(global_settings.volume);
2253 track_widx = track_ridx = 0;
2255 /* Clear all track entries. */
2256 for (i = 0; i < MAX_TRACK; i++) {
2257 clear_track_info(&tracks[i]);
2260 last_peek_offset = -1;
2262 /* Officially playing */
2263 queue_reply(&audio_queue, 1);
2265 audio_fill_file_buffer(true, offset);
2267 add_event(BUFFER_EVENT_BUFFER_LOW, false, buffering_low_buffer_callback);
2269 LOGFQUEUE("audio > audio Q_AUDIO_TRACK_CHANGED");
2270 queue_post(&audio_queue, Q_AUDIO_TRACK_CHANGED, 0);
2274 /* Invalidates all but currently playing track. */
2275 static void audio_invalidate_tracks(void)
2277 if (audio_have_tracks())
2279 last_peek_offset = 0;
2280 track_widx = track_ridx;
2282 /* Mark all other entries null (also buffered wrong metadata). */
2283 audio_clear_track_entries();
2285 track_widx = (track_widx + 1) & MAX_TRACK_MASK;
2287 audio_fill_file_buffer(false, 0);
2291 static void audio_new_playlist(void)
2293 /* Prepare to start a new fill from the beginning of the playlist */
2294 last_peek_offset = -1;
2295 if (audio_have_tracks())
2297 if (paused)
2298 skipped_during_pause = true;
2299 track_widx = track_ridx;
2300 audio_clear_track_entries();
2302 track_widx = (track_widx + 1) & MAX_TRACK_MASK;
2304 /* Mark the current track as invalid to prevent skipping back to it */
2305 CUR_TI->taginfo_ready = false;
2308 /* Signal the codec to initiate a track change forward */
2309 new_playlist = true;
2310 ci.new_track = 1;
2312 /* Officially playing */
2313 queue_reply(&audio_queue, 1);
2315 audio_fill_file_buffer(false, 0);
2318 /* Called on manual track skip */
2319 static void audio_initiate_track_change(long direction)
2321 logf("audio_initiate_track_change(%ld)", direction);
2323 ci.new_track += direction;
2324 wps_offset -= direction;
2325 if (paused)
2326 skipped_during_pause = true;
2329 /* Called on manual dir skip */
2330 static void audio_initiate_dir_change(long direction)
2332 dir_skip = true;
2333 ci.new_track = direction;
2334 if (paused)
2335 skipped_during_pause = true;
2338 /* Called when PCM track change is complete */
2339 static void audio_finalise_track_change(void)
2341 logf("audio_finalise_track_change");
2343 if (automatic_skip)
2345 wps_offset = 0;
2346 automatic_skip = false;
2348 /* Invalidate prevtrack_id3 */
2349 memset(othertrack_id3, 0, sizeof(struct mp3entry));
2351 if (prev_ti && prev_ti->audio_hid < 0)
2353 /* No audio left so we clear all the track info. */
2354 clear_track_info(prev_ti);
2357 send_event(PLAYBACK_EVENT_TRACK_CHANGE, thistrack_id3);
2358 playlist_update_resume_info(audio_current_track());
2362 * Layout audio buffer as follows - iram buffer depends on target:
2363 * [|SWAP:iram][|TALK]|FILE|GUARD|PCM|[SWAP:dram[|iram]|]
2365 static void audio_reset_buffer(void)
2367 /* see audio_get_recording_buffer if this is modified */
2368 logf("audio_reset_buffer");
2370 /* If the setup of anything allocated before the file buffer is
2371 changed, do check the adjustments after the buffer_alloc call
2372 as it will likely be affected and need sliding over */
2374 /* Initially set up file buffer as all space available */
2375 malloc_buf = audiobuf + talk_get_bufsize();
2376 /* Align the malloc buf to line size. Especially important to cf
2377 targets that do line reads/writes. */
2378 malloc_buf = (unsigned char *)(((uintptr_t)malloc_buf + 15) & ~15);
2379 filebuf = malloc_buf; /* filebuf line align implied */
2380 filebuflen = audiobufend - filebuf;
2382 filebuflen &= ~15;
2384 /* Subtract whatever the pcm buffer says it used plus the guard buffer */
2385 const size_t pcmbuf_size = pcmbuf_init(filebuf + filebuflen) +GUARD_BUFSIZE;
2387 #ifdef DEBUG
2388 if(pcmbuf_size > filebuflen)
2389 panicf("Not enough memory for pcmbuf_init() : %d > %d",
2390 (int)pcmbuf_size, (int)filebuflen);
2391 #endif
2393 filebuflen -= pcmbuf_size;
2395 /* Make sure filebuflen is a longword multiple after adjustment - filebuf
2396 will already be line aligned */
2397 filebuflen &= ~3;
2399 buffering_reset(filebuf, filebuflen);
2401 /* Clear any references to the file buffer */
2402 buffer_state = AUDIOBUF_STATE_INITIALIZED;
2404 #if defined(ROCKBOX_HAS_LOGF) && defined(LOGF_ENABLE)
2405 /* Make sure everything adds up - yes, some info is a bit redundant but
2406 aids viewing and the sumation of certain variables should add up to
2407 the location of others. */
2409 size_t pcmbufsize;
2410 const unsigned char *pcmbuf = pcmbuf_get_meminfo(&pcmbufsize);
2411 logf("mabuf: %08X", (unsigned)malloc_buf);
2412 logf("fbuf: %08X", (unsigned)filebuf);
2413 logf("fbufe: %08X", (unsigned)(filebuf + filebuflen));
2414 logf("gbuf: %08X", (unsigned)(filebuf + filebuflen));
2415 logf("gbufe: %08X", (unsigned)(filebuf + filebuflen + GUARD_BUFSIZE));
2416 logf("pcmb: %08X", (unsigned)pcmbuf);
2417 logf("pcmbe: %08X", (unsigned)(pcmbuf + pcmbufsize));
2419 #endif
2422 static void audio_thread(void)
2424 struct queue_event ev;
2426 pcm_postinit();
2428 audio_thread_ready = true;
2430 while (1)
2432 if (filling != STATE_FILLING) {
2433 /* End of buffering, let's calculate the watermark and unboost */
2434 set_filebuf_watermark();
2435 cancel_cpu_boost();
2438 if (!pcmbuf_queue_scan(&ev))
2439 queue_wait_w_tmo(&audio_queue, &ev, HZ/2);
2441 switch (ev.id) {
2443 case Q_AUDIO_FILL_BUFFER:
2444 LOGFQUEUE("audio < Q_AUDIO_FILL_BUFFER %d", (int)ev.data);
2445 audio_fill_file_buffer((bool)ev.data, 0);
2446 break;
2448 case Q_AUDIO_FINISH_LOAD:
2449 LOGFQUEUE("audio < Q_AUDIO_FINISH_LOAD");
2450 audio_finish_load_track();
2451 break;
2453 case Q_AUDIO_PLAY:
2454 LOGFQUEUE("audio < Q_AUDIO_PLAY");
2455 if (playing && ev.data <= 0)
2456 audio_new_playlist();
2457 else
2459 audio_stop_playback();
2460 audio_play_start((size_t)ev.data);
2462 break;
2464 case Q_AUDIO_STOP:
2465 LOGFQUEUE("audio < Q_AUDIO_STOP");
2466 if (playing)
2467 audio_stop_playback();
2468 if (ev.data != 0)
2469 queue_clear(&audio_queue);
2470 break;
2472 case Q_AUDIO_PAUSE:
2473 LOGFQUEUE("audio < Q_AUDIO_PAUSE");
2474 if (!(bool) ev.data && skipped_during_pause && !pcmbuf_is_crossfade_active())
2475 pcmbuf_play_stop(); /* Flush old track on resume after skip */
2476 skipped_during_pause = false;
2477 if (!playing)
2478 break;
2479 pcmbuf_pause((bool)ev.data);
2480 paused = (bool)ev.data;
2481 break;
2483 case Q_AUDIO_SKIP:
2484 LOGFQUEUE("audio < Q_AUDIO_SKIP");
2485 audio_initiate_track_change((long)ev.data);
2486 break;
2488 case Q_AUDIO_PRE_FF_REWIND:
2489 LOGFQUEUE("audio < Q_AUDIO_PRE_FF_REWIND");
2490 if (!playing)
2491 break;
2492 pcmbuf_pause(true);
2493 break;
2495 case Q_AUDIO_FF_REWIND:
2496 LOGFQUEUE("audio < Q_AUDIO_FF_REWIND");
2497 if (!playing)
2498 break;
2499 if (automatic_skip)
2501 /* An automatic track skip is in progress. Finalize it,
2502 then go back to the previous track */
2503 audio_finalise_track_change();
2504 ci.new_track = -1;
2506 ci.seek_time = (long)ev.data+1;
2507 break;
2509 case Q_AUDIO_CHECK_NEW_TRACK:
2510 LOGFQUEUE("audio < Q_AUDIO_CHECK_NEW_TRACK");
2511 queue_reply(&audio_queue, audio_check_new_track());
2512 break;
2514 case Q_AUDIO_DIR_SKIP:
2515 LOGFQUEUE("audio < Q_AUDIO_DIR_SKIP");
2516 audio_initiate_dir_change(ev.data);
2517 break;
2519 case Q_AUDIO_FLUSH:
2520 LOGFQUEUE("audio < Q_AUDIO_FLUSH");
2521 audio_invalidate_tracks();
2522 break;
2524 case Q_AUDIO_TRACK_CHANGED:
2525 /* PCM track change done */
2526 LOGFQUEUE("audio < Q_AUDIO_TRACK_CHANGED");
2527 audio_finalise_track_change();
2528 break;
2530 #ifndef SIMULATOR
2531 case SYS_USB_CONNECTED:
2532 LOGFQUEUE("audio < SYS_USB_CONNECTED");
2533 if (playing)
2534 audio_stop_playback();
2535 #ifdef PLAYBACK_VOICE
2536 voice_stop();
2537 #endif
2538 usb_acknowledge(SYS_USB_CONNECTED_ACK);
2539 usb_wait_for_disconnect(&audio_queue);
2541 /* Mark all entries null. */
2542 audio_clear_track_entries();
2544 /* release tracks to make sure all handles are closed */
2545 audio_release_tracks();
2546 break;
2547 #endif
2549 case SYS_TIMEOUT:
2550 LOGFQUEUE_SYS_TIMEOUT("audio < SYS_TIMEOUT");
2551 break;
2553 default:
2554 LOGFQUEUE("audio < default");
2555 break;
2556 } /* end switch */
2557 } /* end while */
2560 /* Initialize the audio system - called from init() in main.c.
2561 * Last function because of all the references to internal symbols
2563 void audio_init(void)
2565 unsigned int audio_thread_id;
2567 /* Can never do this twice */
2568 if (audio_is_initialized)
2570 logf("audio: already initialized");
2571 return;
2574 logf("audio: initializing");
2576 /* Initialize queues before giving control elsewhere in case it likes
2577 to send messages. Thread creation will be delayed however so nothing
2578 starts running until ready if something yields such as talk_init. */
2579 queue_init(&audio_queue, true);
2580 queue_init(&codec_queue, false);
2581 queue_init(&pcmbuf_queue, false);
2583 pcm_init();
2585 /* Initialize codec api. */
2586 ci.read_filebuf = codec_filebuf_callback;
2587 ci.pcmbuf_insert = codec_pcmbuf_insert_callback;
2588 ci.codec_get_buffer = codec_get_buffer;
2589 ci.request_buffer = codec_request_buffer_callback;
2590 ci.advance_buffer = codec_advance_buffer_callback;
2591 ci.advance_buffer_loc = codec_advance_buffer_loc_callback;
2592 ci.request_next_track = codec_request_next_track_callback;
2593 ci.seek_buffer = codec_seek_buffer_callback;
2594 ci.seek_complete = codec_seek_complete_callback;
2595 ci.set_elapsed = codec_set_elapsed_callback;
2596 ci.set_offset = codec_set_offset_callback;
2597 ci.configure = codec_configure_callback;
2598 ci.discard_codec = codec_discard_codec_callback;
2599 ci.dsp = (struct dsp_config *)dsp_configure(NULL, DSP_MYDSP,
2600 CODEC_IDX_AUDIO);
2602 thistrack_id3 = &mp3entry_buf[0];
2603 othertrack_id3 = &mp3entry_buf[1];
2605 /* initialize the buffer */
2606 filebuf = audiobuf;
2608 /* audio_reset_buffer must to know the size of voice buffer so init
2609 talk first */
2610 talk_init();
2612 codec_thread_id = create_thread(
2613 codec_thread, codec_stack, sizeof(codec_stack),
2614 CREATE_THREAD_FROZEN,
2615 codec_thread_name IF_PRIO(, PRIORITY_PLAYBACK)
2616 IF_COP(, CPU));
2618 queue_enable_queue_send(&codec_queue, &codec_queue_sender_list,
2619 codec_thread_id);
2621 audio_thread_id = create_thread(audio_thread, audio_stack,
2622 sizeof(audio_stack), CREATE_THREAD_FROZEN,
2623 audio_thread_name IF_PRIO(, PRIORITY_USER_INTERFACE)
2624 IF_COP(, CPU));
2626 queue_enable_queue_send(&audio_queue, &audio_queue_sender_list,
2627 audio_thread_id);
2629 #ifdef PLAYBACK_VOICE
2630 voice_thread_init();
2631 #endif
2633 /* Set crossfade setting for next buffer init which should be about... */
2634 pcmbuf_crossfade_enable(global_settings.crossfade);
2636 /* initialize the buffering system */
2638 buffering_init();
2639 /* ...now! Set up the buffers */
2640 audio_reset_buffer();
2642 int i;
2643 for(i = 0; i < MAX_TRACK; i++)
2645 tracks[i].audio_hid = -1;
2646 tracks[i].id3_hid = -1;
2647 tracks[i].codec_hid = -1;
2648 #ifdef HAVE_ALBUMART
2649 tracks[i].aa_hid = -1;
2650 #endif
2653 add_event(BUFFER_EVENT_REBUFFER, false, buffering_handle_rebuffer_callback);
2654 add_event(BUFFER_EVENT_FINISHED, false, buffering_handle_finished_callback);
2656 /* Probably safe to say */
2657 audio_is_initialized = true;
2659 sound_settings_apply();
2660 #ifdef HAVE_DISK_STORAGE
2661 audio_set_buffer_margin(global_settings.buffer_margin);
2662 #endif
2664 /* it's safe to let the threads run now */
2665 #ifdef PLAYBACK_VOICE
2666 voice_thread_resume();
2667 #endif
2668 thread_thaw(codec_thread_id);
2669 thread_thaw(audio_thread_id);
2671 } /* audio_init */
2673 bool audio_is_thread_ready(void)
2675 return audio_thread_ready;