1 /***************************************************************************
3 * Open \______ \ ____ ____ | | _\_ |__ _______ ___
4 * Source | _// _ \_/ ___\| |/ /| __ \ / _ \ \/ /
5 * Jukebox | | ( <_> ) \___| < | \_\ ( <_> > < <
6 * Firmware |____|_ /\____/ \___ >__|_ \|___ /\____/__/\_ \
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 */
46 #include "buffering.h"
47 #include "appevents.h"
48 #include "voice_thread.h"
49 #include "mp3_playback.h"
64 #ifdef HAVE_LCD_BITMAP
66 #include "peakmeter.h"
77 #include "ata_idle_notify.h"
80 #include "recording.h"
82 #include "pcm_record.h"
85 #ifdef IPOD_ACCESSORY_PROTOCOL
89 #define PLAYBACK_VOICE
91 /* amount of guess-space to allow for codecs that must hunt and peck
92 * for their correct seeek target, 32k seems a good size */
93 #define AUDIO_REBUFFER_GUESS_SIZE (1024*32)
95 /* Define LOGF_ENABLE to enable logf output in this file */
96 /*#define LOGF_ENABLE*/
99 /* macros to enable logf for queues
100 logging on SYS_TIMEOUT can be disabled */
102 /* Define this for logf output of all queuing except SYS_TIMEOUT */
103 #define PLAYBACK_LOGQUEUES
104 /* Define this to logf SYS_TIMEOUT messages */
105 /*#define PLAYBACK_LOGQUEUES_SYS_TIMEOUT*/
108 #ifdef PLAYBACK_LOGQUEUES
109 #define LOGFQUEUE logf
111 #define LOGFQUEUE(...)
114 #ifdef PLAYBACK_LOGQUEUES_SYS_TIMEOUT
115 #define LOGFQUEUE_SYS_TIMEOUT logf
117 #define LOGFQUEUE_SYS_TIMEOUT(...)
121 /* Define one constant that includes recording related functionality */
122 #if defined(HAVE_RECORDING) && !defined(SIMULATOR)
123 #define AUDIO_HAVE_RECORDING
132 Q_AUDIO_PRE_FF_REWIND
,
134 Q_AUDIO_CHECK_NEW_TRACK
,
136 Q_AUDIO_TRACK_CHANGED
,
141 Q_CODEC_REQUEST_COMPLETE
,
142 Q_CODEC_REQUEST_FAILED
,
147 #ifdef AUDIO_HAVE_RECORDING
156 STATE_IDLE
, /* audio is stopped: nothing to do */
157 STATE_FILLING
, /* adding tracks to the buffer */
158 STATE_FULL
, /* can't add any more tracks */
159 STATE_END_OF_PLAYLIST
, /* all remaining tracks have been added */
160 STATE_FINISHED
, /* all remaining tracks are fully buffered */
163 #define MAX_TRACK 128
165 #define MAX_TRACK_MASK (MAX_TRACK-1)
167 /* As defined in plugins/lib/xxx2wav.h */
168 #define GUARD_BUFSIZE (32*1024)
170 /* As defined in plugin.lds */
172 #define CODEC_IRAM_ORIGIN ((unsigned char *)0x4000c000)
173 #define CODEC_IRAM_SIZE ((size_t)0xc000)
174 #elif defined(IAUDIO_X5) || defined(IAUDIO_M5)
175 #define CODEC_IRAM_ORIGIN ((unsigned char *)0x10010000)
176 #define CODEC_IRAM_SIZE ((size_t)0x10000)
178 #define CODEC_IRAM_ORIGIN ((unsigned char *)0x1000c000)
179 #define CODEC_IRAM_SIZE ((size_t)0xc000)
182 bool audio_is_initialized
= false;
183 static bool audio_thread_ready SHAREDBSS_ATTR
= false;
185 /* Variables are commented with the threads that use them: *
186 * A=audio, C=codec, V=voice. A suffix of - indicates that *
187 * the variable is read but not updated on that thread. */
188 /* TBD: Split out "audio" and "playback" (ie. calling) threads */
190 /* Main state control */
191 static volatile bool audio_codec_loaded SHAREDBSS_ATTR
= false; /* Codec loaded? (C/A-) */
192 static volatile bool playing SHAREDBSS_ATTR
= false; /* Is audio playing? (A) */
193 static volatile bool paused SHAREDBSS_ATTR
= false; /* Is audio paused? (A/C-) */
195 /* Ring buffer where compressed audio and codecs are loaded */
196 static unsigned char *filebuf
= NULL
; /* Start of buffer (A/C-) */
197 static unsigned char *malloc_buf
= NULL
; /* Start of malloc buffer (A/C-) */
198 /* FIXME: make filebuflen static */
199 size_t filebuflen
= 0; /* Size of buffer (A/C-) */
200 /* FIXME: make buf_ridx (C/A-) */
202 /* Possible arrangements of the buffer */
203 static int buffer_state
= AUDIOBUF_STATE_TRASHED
; /* Buffer state */
205 /* Used to keep the WPS up-to-date during track transtition */
206 static struct mp3entry prevtrack_id3
;
208 /* Used to provide the codec with a pointer */
209 static struct mp3entry curtrack_id3
;
211 /* Used to make next track info available while playing last track on buffer */
212 static struct mp3entry lasttrack_id3
;
214 /* Track info structure about songs in the file buffer (A/C-) */
216 int audio_hid
; /* The ID for the track's buffer handle */
217 int id3_hid
; /* The ID for the track's metadata handle */
218 int codec_hid
; /* The ID for the track's codec handle */
220 int aa_hid
; /* The ID for the track's album art handle */
223 size_t filesize
; /* File total length */
225 bool taginfo_ready
; /* Is metadata read */
228 static struct track_info tracks
[MAX_TRACK
];
229 static volatile int track_ridx
= 0; /* Track being decoded (A/C-) */
230 static int track_widx
= 0; /* Track being buffered (A) */
232 #define CUR_TI (&tracks[track_ridx]) /* Playing track info pointer (A/C-) */
233 static struct track_info
*prev_ti
= NULL
; /* Pointer to the previously played
236 /* Set by the audio thread when the current track information has updated
237 * and the WPS may need to update its cached information */
238 static bool track_changed
= false;
240 /* Information used only for filling the buffer */
241 /* Playlist steps from playing track to next track to be buffered (A) */
242 static int last_peek_offset
= 0;
244 /* Scrobbler support */
245 static unsigned long prev_track_elapsed
= 0; /* Previous track elapsed time (C/A-)*/
247 static enum filling_state filling
;
249 /* Track change controls */
250 static bool automatic_skip
= false; /* Who initiated in-progress skip? (C/A-) */
251 static bool dir_skip
= false; /* Is a directory skip pending? (A) */
252 static bool new_playlist
= false; /* Are we starting a new playlist? (A) */
253 static int wps_offset
= 0; /* Pending track change offset, to keep WPS responsive (A) */
254 static bool skipped_during_pause
= false; /* Do we need to clear the PCM buffer when playback resumes (A) */
256 static bool start_play_g
= false; /* Used by audio_load_track to notify
257 audio_finish_load_track about start_play */
259 /* True when a track load is in progress, i.e. audio_load_track() has returned
260 * but audio_finish_load_track() hasn't been called yet. Used to avoid allowing
261 * audio_load_track() to get called twice in a row, which would cause problems.
263 static bool track_load_started
= false;
265 /* Set to true if the codec thread should send an audio stop request
266 * (typically because the end of the playlist has been reached).
268 static bool codec_requested_stop
= false;
270 #ifdef HAVE_DISK_STORAGE
271 static size_t buffer_margin
= 0; /* Buffer margin aka anti-skip buffer (A/C-) */
274 /* Multiple threads */
275 /* Set the watermark to trigger buffer fill (A/C) */
276 static void set_filebuf_watermark(void);
279 static struct event_queue audio_queue SHAREDBSS_ATTR
;
280 static struct queue_sender_list audio_queue_sender_list SHAREDBSS_ATTR
;
281 static long audio_stack
[(DEFAULT_STACK_SIZE
+ 0x1000)/sizeof(long)];
282 static const char audio_thread_name
[] = "audio";
284 static void audio_thread(void);
285 static void audio_initiate_track_change(long direction
);
286 static bool audio_have_tracks(void);
287 static void audio_reset_buffer(void);
288 static void audio_stop_playback(void);
291 extern struct codec_api ci
;
292 static struct event_queue codec_queue SHAREDBSS_ATTR
;
293 static struct queue_sender_list codec_queue_sender_list
;
294 static long codec_stack
[(DEFAULT_STACK_SIZE
+ 0x2000)/sizeof(long)]
296 static const char codec_thread_name
[] = "codec";
297 unsigned int codec_thread_id
; /* For modifying thread priority later. */
299 /* PCM buffer messaging */
300 static struct event_queue pcmbuf_queue SHAREDBSS_ATTR
;
302 /* Function to be called by pcm buffer callbacks.
303 * Permissible Context(s): Audio interrupt
305 static void pcmbuf_callback_queue_post(long id
, intptr_t data
)
307 /* No lock since we're already in audio interrupt context */
308 queue_post(&pcmbuf_queue
, id
, data
);
311 /* Scan the pcmbuf queue and return true if a message pulled.
312 * Permissible Context(s): Thread
314 static bool pcmbuf_queue_scan(struct queue_event
*ev
)
316 if (!queue_empty(&pcmbuf_queue
))
318 /* Transfer message to audio queue */
320 /* Pull message - never, ever any blocking call! */
321 queue_wait_w_tmo(&pcmbuf_queue
, ev
, 0);
329 /* Clear the pcmbuf queue of messages
330 * Permissible Context(s): Thread
332 static void pcmbuf_queue_clear(void)
335 queue_clear(&pcmbuf_queue
);
339 /* --- Helper functions --- */
341 static struct mp3entry
*bufgetid3(int handle_id
)
346 struct mp3entry
*id3
;
347 ssize_t ret
= bufgetdata(handle_id
, 0, (void *)&id3
);
349 if (ret
< 0 || ret
!= sizeof(struct mp3entry
))
355 static bool clear_track_info(struct track_info
*track
)
357 /* bufclose returns true if the handle is not found, or if it is closed
358 * successfully, so these checks are safe on non-existant handles */
362 if (track
->codec_hid
>= 0) {
363 if (bufclose(track
->codec_hid
))
364 track
->codec_hid
= -1;
369 if (track
->id3_hid
>= 0) {
370 if (bufclose(track
->id3_hid
))
376 if (track
->audio_hid
>= 0) {
377 if (bufclose(track
->audio_hid
))
378 track
->audio_hid
= -1;
384 if (track
->aa_hid
>= 0) {
385 if (bufclose(track
->aa_hid
))
393 track
->taginfo_ready
= false;
398 /* --- External interfaces --- */
400 /* This sends a stop message and the audio thread will dump all it's
401 subsequenct messages */
402 void audio_hard_stop(void)
405 LOGFQUEUE("audio >| audio Q_AUDIO_STOP: 1");
406 queue_send(&audio_queue
, Q_AUDIO_STOP
, 1);
407 #ifdef PLAYBACK_VOICE
412 bool audio_restore_playback(int type
)
416 case AUDIO_WANT_PLAYBACK
:
417 if (buffer_state
!= AUDIOBUF_STATE_INITIALIZED
)
418 audio_reset_buffer();
420 case AUDIO_WANT_VOICE
:
421 if (buffer_state
== AUDIOBUF_STATE_TRASHED
)
422 audio_reset_buffer();
429 unsigned char *audio_get_buffer(bool talk_buf
, size_t *buffer_size
)
431 unsigned char *buf
, *end
;
433 if (audio_is_initialized
)
437 /* else buffer_state will be AUDIOBUF_STATE_TRASHED at this point */
439 /* Reset the buffering thread so that it doesn't try to use the data */
440 buffering_reset(filebuf
, filebuflen
);
442 if (buffer_size
== NULL
)
444 /* Special case for talk_init to use since it already knows it's
446 buffer_state
= AUDIOBUF_STATE_TRASHED
;
450 if (talk_buf
|| buffer_state
== AUDIOBUF_STATE_TRASHED
451 || !talk_voice_required())
453 logf("get buffer: talk, audio");
454 /* Ok to use everything from audiobuf to audiobufend - voice is loaded,
455 the talk buffer is not needed because voice isn't being used, or
456 could be AUDIOBUF_STATE_TRASHED already. If state is
457 AUDIOBUF_STATE_VOICED_ONLY, no problem as long as memory isn't written
458 without the caller knowing what's going on. Changing certain settings
459 may move it to a worse condition but the memory in use by something
460 else will remain undisturbed.
462 if (buffer_state
!= AUDIOBUF_STATE_TRASHED
)
465 buffer_state
= AUDIOBUF_STATE_TRASHED
;
473 /* Safe to just return this if already AUDIOBUF_STATE_VOICED_ONLY or
474 still AUDIOBUF_STATE_INITIALIZED */
475 /* Skip talk buffer and move pcm buffer to end to maximize available
476 contiguous memory - no audio running means voice will not need the
478 logf("get buffer: audio");
479 buf
= audiobuf
+ talk_get_bufsize();
480 end
= audiobufend
- pcmbuf_init(audiobufend
);
481 buffer_state
= AUDIOBUF_STATE_VOICED_ONLY
;
484 *buffer_size
= end
- buf
;
489 int audio_buffer_state(void)
494 #ifdef HAVE_RECORDING
495 unsigned char *audio_get_recording_buffer(size_t *buffer_size
)
497 /* Stop audio, voice and obtain all available buffer space */
501 unsigned char *end
= audiobufend
;
502 buffer_state
= AUDIOBUF_STATE_TRASHED
;
503 *buffer_size
= end
- audiobuf
;
505 return (unsigned char *)audiobuf
;
508 bool audio_load_encoder(int afmt
)
511 const char *enc_fn
= get_codec_filename(afmt
| CODEC_TYPE_ENCODER
);
515 audio_remove_encoder();
516 ci
.enc_codec_loaded
= 0; /* clear any previous error condition */
518 LOGFQUEUE("codec > Q_ENCODER_LOAD_DISK");
519 queue_post(&codec_queue
, Q_ENCODER_LOAD_DISK
, (intptr_t)enc_fn
);
521 while (ci
.enc_codec_loaded
== 0)
524 logf("codec loaded: %d", ci
.enc_codec_loaded
);
526 return ci
.enc_codec_loaded
> 0;
531 } /* audio_load_encoder */
533 void audio_remove_encoder(void)
536 /* force encoder codec unload (if currently loaded) */
537 if (ci
.enc_codec_loaded
<= 0)
540 ci
.stop_encoder
= true;
541 while (ci
.enc_codec_loaded
> 0)
544 } /* audio_remove_encoder */
546 #endif /* HAVE_RECORDING */
549 int audio_current_aa_hid(void)
552 int offset
= ci
.new_track
+ wps_offset
;
554 cur_idx
= track_ridx
+ offset
;
555 cur_idx
&= MAX_TRACK_MASK
;
557 return tracks
[cur_idx
].aa_hid
;
561 struct mp3entry
* audio_current_track(void)
563 const char *filename
;
564 static struct mp3entry temp_id3
;
565 struct playlist_track_info trackinfo
;
567 int offset
= ci
.new_track
+ wps_offset
;
569 cur_idx
= (track_ridx
+ offset
) & MAX_TRACK_MASK
;
571 if (cur_idx
== track_ridx
&& *curtrack_id3
.path
)
574 return &curtrack_id3
;
576 else if (automatic_skip
&& offset
== -1 && *prevtrack_id3
.path
)
578 /* We're in a track transition. The codec has moved on to the nex track,
579 but the audio being played is still the same (now previous) track.
580 prevtrack_id3.elapsed is being updated in an ISR by
581 codec_pcmbuf_position_callback */
582 return &prevtrack_id3
;
584 else if (tracks
[cur_idx
].id3_hid
>= 0)
586 /* Get the ID3 metadata from the main buffer */
587 struct mp3entry
*ret
= bufgetid3(tracks
[cur_idx
].id3_hid
);
591 /* We didn't find the ID3 metadata, so we fill temp_id3 with the little info
592 we have and return that. */
594 memset(&temp_id3
, 0, sizeof(struct mp3entry
));
596 playlist_get_track_info(NULL
, playlist_next(0)+wps_offset
, &trackinfo
);
597 filename
= trackinfo
.filename
;
599 filename
= "No file!";
601 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
602 if (tagcache_fill_tags(&temp_id3
, filename
))
606 strncpy(temp_id3
.path
, filename
, sizeof(temp_id3
.path
)-1);
607 temp_id3
.title
= strrchr(temp_id3
.path
, '/');
609 temp_id3
.title
= &temp_id3
.path
[0];
616 struct mp3entry
* audio_next_track(void)
619 int offset
= ci
.new_track
+ wps_offset
;
621 if (!audio_have_tracks())
624 if (wps_offset
== -1 && *prevtrack_id3
.path
)
626 /* We're in a track transition. The next track for the WPS is the one
627 currently being decoded. */
628 return &curtrack_id3
;
631 next_idx
= (track_ridx
+ offset
+ 1) & MAX_TRACK_MASK
;
633 if (tracks
[next_idx
].id3_hid
>= 0)
634 return bufgetid3(tracks
[next_idx
].id3_hid
);
636 if (next_idx
== track_widx
)
638 /* The next track hasn't been buffered yet, so we return the static
639 version of its metadata. */
640 return &lasttrack_id3
;
646 bool audio_has_changed_track(void)
650 #ifdef IPOD_ACCESSORY_PROTOCOL
653 track_changed
= false;
660 void audio_play(long offset
)
664 #ifdef PLAYBACK_VOICE
665 /* Truncate any existing voice output so we don't have spelling
666 * etc. over the first part of the played track */
671 LOGFQUEUE("audio >| audio Q_AUDIO_PLAY: %ld", offset
);
672 /* Don't return until playback has actually started */
673 queue_send(&audio_queue
, Q_AUDIO_PLAY
, offset
);
676 void audio_stop(void)
679 LOGFQUEUE("audio >| audio Q_AUDIO_STOP");
680 /* Don't return until playback has actually stopped */
681 queue_send(&audio_queue
, Q_AUDIO_STOP
, 0);
684 void audio_pause(void)
686 LOGFQUEUE("audio >| audio Q_AUDIO_PAUSE");
687 /* Don't return until playback has actually paused */
688 queue_send(&audio_queue
, Q_AUDIO_PAUSE
, true);
691 void audio_resume(void)
693 LOGFQUEUE("audio >| audio Q_AUDIO_PAUSE resume");
694 /* Don't return until playback has actually resumed */
695 queue_send(&audio_queue
, Q_AUDIO_PAUSE
, false);
698 void audio_skip(int direction
)
700 if (playlist_check(ci
.new_track
+ wps_offset
+ direction
))
702 if (global_settings
.beep
)
703 pcmbuf_beep(2000, 100, 2500*global_settings
.beep
);
705 LOGFQUEUE("audio > audio Q_AUDIO_SKIP %d", direction
);
706 queue_post(&audio_queue
, Q_AUDIO_SKIP
, direction
);
707 /* Update wps while our message travels inside deep playback queues. */
708 wps_offset
+= direction
;
709 track_changed
= true;
713 /* No more tracks. */
714 if (global_settings
.beep
)
715 pcmbuf_beep(1000, 100, 1500*global_settings
.beep
);
719 void audio_next(void)
724 void audio_prev(void)
729 void audio_next_dir(void)
731 LOGFQUEUE("audio > audio Q_AUDIO_DIR_SKIP 1");
732 queue_post(&audio_queue
, Q_AUDIO_DIR_SKIP
, 1);
735 void audio_prev_dir(void)
737 LOGFQUEUE("audio > audio Q_AUDIO_DIR_SKIP -1");
738 queue_post(&audio_queue
, Q_AUDIO_DIR_SKIP
, -1);
741 void audio_pre_ff_rewind(void)
743 LOGFQUEUE("audio > audio Q_AUDIO_PRE_FF_REWIND");
744 queue_post(&audio_queue
, Q_AUDIO_PRE_FF_REWIND
, 0);
747 void audio_ff_rewind(long newpos
)
749 LOGFQUEUE("audio > audio Q_AUDIO_FF_REWIND");
750 queue_post(&audio_queue
, Q_AUDIO_FF_REWIND
, newpos
);
753 void audio_flush_and_reload_tracks(void)
755 LOGFQUEUE("audio > audio Q_AUDIO_FLUSH");
756 queue_post(&audio_queue
, Q_AUDIO_FLUSH
, 0);
759 void audio_error_clear(void)
761 #ifdef AUDIO_HAVE_RECORDING
762 pcm_rec_error_clear();
766 int audio_status(void)
771 ret
|= AUDIO_STATUS_PLAY
;
774 ret
|= AUDIO_STATUS_PAUSE
;
776 #ifdef HAVE_RECORDING
777 /* Do this here for constitency with mpeg.c version */
778 ret
|= pcm_rec_status();
784 int audio_get_file_pos(void)
789 #ifdef HAVE_DISK_STORAGE
790 void audio_set_buffer_margin(int setting
)
792 static const int lookup
[] = {5, 15, 30, 60, 120, 180, 300, 600};
793 buffer_margin
= lookup
[setting
];
794 logf("buffer margin: %ld", (long)buffer_margin
);
795 set_filebuf_watermark();
799 /* Take necessary steps to enable or disable the crossfade setting */
800 void audio_set_crossfade(int enable
)
806 /* Tell it the next setting to use */
807 pcmbuf_crossfade_enable(enable
);
809 /* Return if size hasn't changed or this is too early to determine
810 which in the second case there's no way we could be playing
812 if (pcmbuf_is_same_size())
814 /* This function is a copout and just syncs some variables -
815 to be removed at a later date */
816 pcmbuf_crossfade_enable_finished();
821 was_playing
= playing
;
823 /* Playback has to be stopped before changing the buffer size */
826 /* Store the track resume position */
827 offset
= curtrack_id3
.offset
;
830 /* Blast it - audio buffer will have to be setup again next time
832 audio_get_buffer(true, &size
);
834 /* Restart playback if audio was running previously */
839 /* --- Routines called from multiple threads --- */
841 static void set_filebuf_watermark(void)
844 return; /* Audio buffers not yet set up */
846 #ifdef HAVE_FLASH_STORAGE
850 int spinup
= ata_spinup_time();
852 seconds
= (spinup
/ HZ
) + 1;
857 /* bitrate of last track in buffer dictates watermark */
858 struct mp3entry
* id3
= NULL
;
859 if (tracks
[track_widx
].taginfo_ready
)
860 id3
= bufgetid3(tracks
[track_widx
].id3_hid
);
862 id3
= bufgetid3(tracks
[track_widx
-1].id3_hid
);
864 logf("fwmark: No id3 for last track (r%d/w%d), aborting!", track_ridx
, track_widx
);
867 size_t bytes
= id3
->bitrate
* (1000/8) * seconds
;
868 buf_set_watermark(bytes
);
869 logf("fwmark: %d", bytes
);
872 const char *get_codec_filename(int cod_spec
)
876 #ifdef HAVE_RECORDING
877 /* Can choose decoder or encoder if one available */
878 int type
= cod_spec
& CODEC_TYPE_MASK
;
879 int afmt
= cod_spec
& CODEC_AFMT_MASK
;
881 if ((unsigned)afmt
>= AFMT_NUM_CODECS
)
882 type
= AFMT_UNKNOWN
| (type
& CODEC_TYPE_MASK
);
884 fname
= (type
== CODEC_TYPE_ENCODER
) ?
885 audio_formats
[afmt
].codec_enc_root_fn
:
886 audio_formats
[afmt
].codec_root_fn
;
889 (type
== CODEC_TYPE_ENCODER
) ? "Encoder" : "Decoder",
890 afmt
, fname
? fname
: "<unknown>");
891 #else /* !HAVE_RECORDING */
893 if ((unsigned)cod_spec
>= AFMT_NUM_CODECS
)
894 cod_spec
= AFMT_UNKNOWN
;
895 fname
= audio_formats
[cod_spec
].codec_root_fn
;
896 logf("Codec: %d - %s", cod_spec
, fname
? fname
: "<unknown>");
897 #endif /* HAVE_RECORDING */
900 } /* get_codec_filename */
902 /* --- Codec thread --- */
903 static bool codec_pcmbuf_insert_callback(
904 const void *ch1
, const void *ch2
, int count
)
906 const char *src
[2] = { ch1
, ch2
};
910 int out_count
= dsp_output_count(ci
.dsp
, count
);
914 /* Prevent audio from a previous track from playing */
915 if (ci
.new_track
|| ci
.stop_codec
)
918 while ((dest
= pcmbuf_request_buffer(&out_count
)) == NULL
)
922 if (ci
.seek_time
|| ci
.new_track
|| ci
.stop_codec
)
926 /* Get the real input_size for output_size bytes, guarding
927 * against resampling buffer overflows. */
928 inp_count
= dsp_input_count(ci
.dsp
, out_count
);
933 /* Input size has grown, no error, just don't write more than length */
934 if (inp_count
> count
)
937 out_count
= dsp_process(ci
.dsp
, dest
, src
, inp_count
);
942 pcmbuf_write_complete(out_count
);
948 } /* codec_pcmbuf_insert_callback */
950 static void* codec_get_buffer(size_t *size
)
952 if (codec_size
>= CODEC_SIZE
)
954 *size
= CODEC_SIZE
- codec_size
;
955 return &codecbuf
[codec_size
];
958 /* Between the codec and PCM track change, we need to keep updating the
959 "elapsed" value of the previous (to the codec, but current to the
960 user/PCM/WPS) track, so that the progressbar reaches the end.
961 During that transition, the WPS will display prevtrack_id3. */
962 static void codec_pcmbuf_position_callback(size_t size
) ICODE_ATTR
;
963 static void codec_pcmbuf_position_callback(size_t size
)
965 /* This is called from an ISR, so be quick */
966 unsigned int time
= size
* 1000 / 4 / NATIVE_FREQUENCY
+
967 prevtrack_id3
.elapsed
;
969 if (time
>= prevtrack_id3
.length
)
971 pcmbuf_set_position_callback(NULL
);
972 prevtrack_id3
.elapsed
= prevtrack_id3
.length
;
975 prevtrack_id3
.elapsed
= time
;
978 static void codec_set_elapsed_callback(unsigned int value
)
980 unsigned int latency
;
984 #ifdef AB_REPEAT_ENABLE
985 ab_position_report(value
);
988 latency
= pcmbuf_get_latency();
990 curtrack_id3
.elapsed
= 0;
991 else if (value
- latency
> curtrack_id3
.elapsed
||
992 value
- latency
< curtrack_id3
.elapsed
- 2)
994 curtrack_id3
.elapsed
= value
- latency
;
998 static void codec_set_offset_callback(size_t value
)
1000 unsigned int latency
;
1005 latency
= pcmbuf_get_latency() * curtrack_id3
.bitrate
/ 8;
1006 if (value
< latency
)
1007 curtrack_id3
.offset
= 0;
1009 curtrack_id3
.offset
= value
- latency
;
1012 static void codec_advance_buffer_counters(size_t amount
)
1014 bufadvance(CUR_TI
->audio_hid
, amount
);
1015 ci
.curpos
+= amount
;
1018 /* copy up-to size bytes into ptr and return the actual size copied */
1019 static size_t codec_filebuf_callback(void *ptr
, size_t size
)
1023 if (ci
.stop_codec
|| !playing
)
1026 copy_n
= bufread(CUR_TI
->audio_hid
, size
, ptr
);
1028 /* Nothing requested OR nothing left */
1032 /* Update read and other position pointers */
1033 codec_advance_buffer_counters(copy_n
);
1035 /* Return the actual amount of data copied to the buffer */
1037 } /* codec_filebuf_callback */
1039 static void* codec_request_buffer_callback(size_t *realsize
, size_t reqsize
)
1041 size_t copy_n
= reqsize
;
1051 ret
= bufgetdata(CUR_TI
->audio_hid
, reqsize
, &ptr
);
1053 copy_n
= MIN((size_t)ret
, reqsize
);
1064 } /* codec_request_buffer_callback */
1066 static int get_codec_base_type(int type
)
1078 static void codec_advance_buffer_callback(size_t amount
)
1080 codec_advance_buffer_counters(amount
);
1081 codec_set_offset_callback(ci
.curpos
);
1084 static void codec_advance_buffer_loc_callback(void *ptr
)
1086 size_t amount
= buf_get_offset(CUR_TI
->audio_hid
, ptr
);
1087 codec_advance_buffer_callback(amount
);
1090 static void codec_seek_complete_callback(void)
1092 logf("seek_complete");
1093 if (pcm_is_paused())
1095 /* If this is not a seamless seek, clear the buffer */
1097 dsp_configure(ci
.dsp
, DSP_FLUSH
, 0);
1099 /* If playback was not 'deliberately' paused, unpause now */
1101 pcmbuf_pause(false);
1106 static bool codec_seek_buffer_callback(size_t newpos
)
1108 logf("codec_seek_buffer_callback");
1110 int ret
= bufseek(CUR_TI
->audio_hid
, newpos
);
1120 static void codec_configure_callback(int setting
, intptr_t value
)
1124 if (!dsp_configure(ci
.dsp
, setting
, value
))
1125 { logf("Illegal key:%d", setting
); }
1129 static void codec_track_changed(void)
1131 LOGFQUEUE("codec > audio Q_AUDIO_TRACK_CHANGED");
1132 queue_post(&audio_queue
, Q_AUDIO_TRACK_CHANGED
, 0);
1135 static void codec_pcmbuf_track_changed_callback(void)
1137 pcmbuf_set_position_callback(NULL
);
1138 pcmbuf_callback_queue_post(Q_AUDIO_TRACK_CHANGED
, 0);
1141 static void codec_discard_codec_callback(void)
1143 if (CUR_TI
->codec_hid
>= 0)
1145 bufclose(CUR_TI
->codec_hid
);
1146 CUR_TI
->codec_hid
= -1;
1150 static inline void codec_gapless_track_change(void)
1152 /* callback keeps the progress bar moving while the pcmbuf empties */
1153 pcmbuf_set_position_callback(codec_pcmbuf_position_callback
);
1154 /* set the pcmbuf callback for when the track really changes */
1155 pcmbuf_set_event_handler(codec_pcmbuf_track_changed_callback
);
1158 static inline void codec_crossfade_track_change(void)
1160 /* Initiate automatic crossfade mode */
1161 pcmbuf_crossfade_init(false);
1162 /* Notify the wps that the track change starts now */
1163 codec_track_changed();
1166 static void codec_track_skip_done(bool was_manual
)
1168 /* Manual track change (always crossfade or flush audio). */
1171 pcmbuf_crossfade_init(true);
1172 LOGFQUEUE("codec > audio Q_AUDIO_TRACK_CHANGED");
1173 queue_post(&audio_queue
, Q_AUDIO_TRACK_CHANGED
, 0);
1175 /* Automatic track change w/crossfade, if not in "Track Skip Only" mode. */
1176 else if (pcmbuf_is_crossfade_enabled() && !pcmbuf_is_crossfade_active()
1177 && global_settings
.crossfade
!= CROSSFADE_ENABLE_TRACKSKIP
)
1179 if (global_settings
.crossfade
== CROSSFADE_ENABLE_SHUFFLE_AND_TRACKSKIP
)
1181 if (global_settings
.playlist_shuffle
)
1182 /* shuffle mode is on, so crossfade: */
1183 codec_crossfade_track_change();
1185 /* shuffle mode is off, so do a gapless track change */
1186 codec_gapless_track_change();
1189 /* normal crossfade: */
1190 codec_crossfade_track_change();
1193 /* normal gapless playback. */
1194 codec_gapless_track_change();
1197 static bool codec_load_next_track(void)
1199 intptr_t result
= Q_CODEC_REQUEST_FAILED
;
1201 prev_track_elapsed
= curtrack_id3
.elapsed
;
1203 #ifdef AB_REPEAT_ENABLE
1204 ab_end_of_track_report();
1207 logf("Request new track");
1209 if (ci
.new_track
== 0)
1212 automatic_skip
= true;
1217 trigger_cpu_boost();
1218 LOGFQUEUE("codec >| audio Q_AUDIO_CHECK_NEW_TRACK");
1219 result
= queue_send(&audio_queue
, Q_AUDIO_CHECK_NEW_TRACK
, 0);
1224 case Q_CODEC_REQUEST_COMPLETE
:
1225 LOGFQUEUE("codec |< Q_CODEC_REQUEST_COMPLETE");
1226 codec_track_skip_done(!automatic_skip
);
1229 case Q_CODEC_REQUEST_FAILED
:
1230 LOGFQUEUE("codec |< Q_CODEC_REQUEST_FAILED");
1232 ci
.stop_codec
= true;
1233 codec_requested_stop
= true;
1237 LOGFQUEUE("codec |< default");
1238 ci
.stop_codec
= true;
1239 codec_requested_stop
= true;
1244 static bool codec_request_next_track_callback(void)
1248 if (ci
.stop_codec
|| !playing
)
1251 prev_codectype
= get_codec_base_type(curtrack_id3
.codectype
);
1253 if (!codec_load_next_track())
1256 /* Seek to the beginning of the new track because if the struct
1257 mp3entry was buffered, "elapsed" might not be zero (if the track has
1258 been played 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();
1270 logf("New codec:%d/%d", curtrack_id3
.codectype
, prev_codectype
);
1275 static void codec_thread(void)
1277 struct queue_event ev
;
1283 if (!pcmbuf_is_crossfade_active()) {
1287 queue_wait(&codec_queue
, &ev
);
1288 codec_requested_stop
= false;
1291 case Q_CODEC_LOAD_DISK
:
1292 LOGFQUEUE("codec < Q_CODEC_LOAD_DISK");
1293 queue_reply(&codec_queue
, 1);
1294 audio_codec_loaded
= true;
1295 ci
.stop_codec
= false;
1296 status
= codec_load_file((const char *)ev
.data
, &ci
);
1300 LOGFQUEUE("codec < Q_CODEC_LOAD");
1301 if (CUR_TI
->codec_hid
< 0) {
1302 logf("Codec slot is empty!");
1303 /* Wait for the pcm buffer to go empty */
1304 while (pcm_is_playing())
1306 /* This must be set to prevent an infinite loop */
1307 ci
.stop_codec
= true;
1308 LOGFQUEUE("codec > codec Q_AUDIO_PLAY");
1309 queue_post(&codec_queue
, Q_AUDIO_PLAY
, 0);
1313 audio_codec_loaded
= true;
1314 ci
.stop_codec
= false;
1315 status
= codec_load_buf(CUR_TI
->codec_hid
, &ci
);
1318 case Q_CODEC_DO_CALLBACK
:
1319 LOGFQUEUE("codec < Q_CODEC_DO_CALLBACK");
1320 queue_reply(&codec_queue
, 1);
1321 if ((void*)ev
.data
!= NULL
)
1323 cpucache_invalidate();
1324 ((void (*)(void))ev
.data
)();
1329 #ifdef AUDIO_HAVE_RECORDING
1330 case Q_ENCODER_LOAD_DISK
:
1331 LOGFQUEUE("codec < Q_ENCODER_LOAD_DISK");
1332 audio_codec_loaded
= false; /* Not audio codec! */
1333 logf("loading encoder");
1334 ci
.stop_encoder
= false;
1335 status
= codec_load_file((const char *)ev
.data
, &ci
);
1336 logf("encoder stopped");
1338 #endif /* AUDIO_HAVE_RECORDING */
1341 LOGFQUEUE("codec < default");
1344 if (audio_codec_loaded
)
1353 audio_codec_loaded
= false;
1357 case Q_CODEC_LOAD_DISK
:
1359 LOGFQUEUE("codec < Q_CODEC_LOAD");
1362 if (ci
.new_track
|| status
!= CODEC_OK
)
1366 logf("Codec failure");
1367 splash(HZ
*2, "Codec failure");
1370 if (!codec_load_next_track())
1372 LOGFQUEUE("codec > audio Q_AUDIO_STOP");
1373 /* End of playlist */
1374 queue_post(&audio_queue
, Q_AUDIO_STOP
, 0);
1380 logf("Codec finished");
1383 /* Wait for the audio to stop playing before
1384 * triggering the WPS exit */
1385 while(pcm_is_playing())
1387 curtrack_id3
.elapsed
=
1388 curtrack_id3
.length
- pcmbuf_get_latency();
1392 if (codec_requested_stop
)
1394 LOGFQUEUE("codec > audio Q_AUDIO_STOP");
1395 queue_post(&audio_queue
, Q_AUDIO_STOP
, 0);
1401 if (CUR_TI
->codec_hid
>= 0)
1403 LOGFQUEUE("codec > codec Q_CODEC_LOAD");
1404 queue_post(&codec_queue
, Q_CODEC_LOAD
, 0);
1408 const char *codec_fn
=
1409 get_codec_filename(curtrack_id3
.codectype
);
1412 LOGFQUEUE("codec > codec Q_CODEC_LOAD_DISK");
1413 queue_post(&codec_queue
, Q_CODEC_LOAD_DISK
,
1414 (intptr_t)codec_fn
);
1420 #ifdef AUDIO_HAVE_RECORDING
1421 case Q_ENCODER_LOAD_DISK
:
1422 LOGFQUEUE("codec < Q_ENCODER_LOAD_DISK");
1424 if (status
== CODEC_OK
)
1427 logf("Encoder failure");
1428 splash(HZ
*2, "Encoder failure");
1430 if (ci
.enc_codec_loaded
< 0)
1433 logf("Encoder failed to load");
1434 ci
.enc_codec_loaded
= -1;
1436 #endif /* AUDIO_HAVE_RECORDING */
1439 LOGFQUEUE("codec < default");
1445 /* Borrow the codec thread and return the ID */
1446 void codec_thread_do_callback(void (*fn
)(void), unsigned int *id
)
1448 /* Set id before telling thread to call something; it may be
1449 * needed before this function returns. */
1451 *id
= codec_thread_id
;
1453 /* Codec thread will signal just before entering callback */
1454 LOGFQUEUE("codec >| Q_CODEC_DO_CALLBACK");
1455 queue_send(&codec_queue
, Q_CODEC_DO_CALLBACK
, (intptr_t)fn
);
1458 /* --- Buffering callbacks --- */
1460 static void buffering_low_buffer_callback(void *data
)
1463 logf("low buffer callback");
1465 if (filling
== STATE_FULL
|| filling
== STATE_END_OF_PLAYLIST
) {
1466 /* force a refill */
1467 LOGFQUEUE("buffering > audio Q_AUDIO_FILL_BUFFER");
1468 queue_post(&audio_queue
, Q_AUDIO_FILL_BUFFER
, 0);
1472 static void buffering_handle_rebuffer_callback(void *data
)
1475 LOGFQUEUE("audio >| audio Q_AUDIO_FLUSH");
1476 queue_post(&audio_queue
, Q_AUDIO_FLUSH
, 0);
1479 static void buffering_handle_finished_callback(int *data
)
1481 logf("handle %d finished buffering", *data
);
1483 if (*data
== tracks
[track_widx
].id3_hid
)
1485 /* The metadata handle for the last loaded track has been buffered.
1486 We can ask the audio thread to load the rest of the track's data. */
1487 LOGFQUEUE("audio >| audio Q_AUDIO_FINISH_LOAD");
1488 queue_post(&audio_queue
, Q_AUDIO_FINISH_LOAD
, 0);
1492 /* This is most likely an audio handle, so we strip the useless
1493 trailing tags that are left. */
1496 if (*data
== tracks
[track_widx
-1].audio_hid
1497 && filling
== STATE_END_OF_PLAYLIST
)
1499 /* This was the last track in the playlist.
1500 We now have all the data we need. */
1501 logf("last track finished buffering");
1502 filling
= STATE_FINISHED
;
1508 /* --- Audio thread --- */
1510 static bool audio_have_tracks(void)
1512 return (audio_track_count() != 0);
1515 static int audio_free_track_count(void)
1517 /* Used tracks + free tracks adds up to MAX_TRACK - 1 */
1518 return MAX_TRACK
- 1 - audio_track_count();
1521 int audio_track_count(void)
1523 /* Calculate difference from track_ridx to track_widx
1524 * taking into account a possible wrap-around. */
1525 return (MAX_TRACK
+ track_widx
- track_ridx
) & MAX_TRACK_MASK
;
1528 long audio_filebufused(void)
1530 return (long) buf_used();
1533 /* Update track info after successful a codec track change */
1534 static void audio_update_trackinfo(void)
1536 /* Load the curent track's metadata into curtrack_id3 */
1537 if (CUR_TI
->id3_hid
>= 0)
1538 copy_mp3entry(&curtrack_id3
, bufgetid3(CUR_TI
->id3_hid
));
1540 /* Reset current position */
1541 curtrack_id3
.elapsed
= 0;
1542 curtrack_id3
.offset
= 0;
1544 /* Update the codec API */
1545 ci
.filesize
= CUR_TI
->filesize
;
1546 ci
.id3
= &curtrack_id3
;
1548 ci
.taginfo_ready
= &CUR_TI
->taginfo_ready
;
1551 /* Clear tracks between write and read, non inclusive */
1552 static void audio_clear_track_entries(void)
1554 int cur_idx
= track_widx
;
1556 logf("Clearing tracks:%d/%d", track_ridx
, track_widx
);
1558 /* Loop over all tracks from write-to-read */
1561 cur_idx
= (cur_idx
+ 1) & MAX_TRACK_MASK
;
1563 if (cur_idx
== track_ridx
)
1566 clear_track_info(&tracks
[cur_idx
]);
1570 /* Clear all tracks */
1571 static bool audio_release_tracks(void)
1575 logf("releasing all tracks");
1577 for(i
= 0; i
< MAX_TRACK
; i
++)
1579 cur_idx
= (track_ridx
+ i
) & MAX_TRACK_MASK
;
1580 if (!clear_track_info(&tracks
[cur_idx
]))
1587 static bool audio_loadcodec(bool start_play
)
1590 char codec_path
[MAX_PATH
]; /* Full path to codec */
1591 const struct mp3entry
*id3
, *prev_id3
;
1593 if (tracks
[track_widx
].id3_hid
< 0) {
1597 id3
= bufgetid3(tracks
[track_widx
].id3_hid
);
1601 const char *codec_fn
= get_codec_filename(id3
->codectype
);
1602 if (codec_fn
== NULL
)
1605 tracks
[track_widx
].codec_hid
= -1;
1609 /* Load the codec directly from disk and save some memory. */
1610 track_ridx
= track_widx
;
1611 ci
.filesize
= CUR_TI
->filesize
;
1612 ci
.id3
= &curtrack_id3
;
1613 ci
.taginfo_ready
= &CUR_TI
->taginfo_ready
;
1615 LOGFQUEUE("codec > codec Q_CODEC_LOAD_DISK");
1616 queue_post(&codec_queue
, Q_CODEC_LOAD_DISK
, (intptr_t)codec_fn
);
1621 /* If we already have another track than this one buffered */
1622 if (track_widx
!= track_ridx
)
1624 prev_track
= (track_widx
- 1) & MAX_TRACK_MASK
;
1626 id3
= bufgetid3(tracks
[track_widx
].id3_hid
);
1627 prev_id3
= bufgetid3(tracks
[prev_track
].id3_hid
);
1629 /* If the previous codec is the same as this one, there is no need
1630 * to put another copy of it on the file buffer */
1631 if (id3
&& prev_id3
&&
1632 get_codec_base_type(id3
->codectype
) ==
1633 get_codec_base_type(prev_id3
->codectype
)
1634 && audio_codec_loaded
)
1636 logf("Reusing prev. codec");
1642 codec_get_full_path(codec_path
, codec_fn
);
1644 tracks
[track_widx
].codec_hid
= bufopen(codec_path
, 0, TYPE_CODEC
);
1645 if (tracks
[track_widx
].codec_hid
< 0)
1648 logf("Loaded codec");
1653 /* Load metadata for the next track (with bufopen). The rest of the track
1654 loading will be handled by audio_finish_load_track once the metadata has been
1655 actually loaded by the buffering thread. */
1656 static bool audio_load_track(size_t offset
, bool start_play
)
1658 const char *trackname
;
1661 if (track_load_started
) {
1662 /* There is already a track load in progress, so track_widx hasn't been
1663 incremented yet. Loading another track would overwrite the one that
1664 hasn't finished loading. */
1665 logf("audio_load_track(): a track load is already in progress");
1669 start_play_g
= start_play
; /* will be read by audio_finish_load_track */
1671 /* Stop buffer filling if there is no free track entries.
1672 Don't fill up the last track entry (we wan't to store next track
1674 if (!audio_free_track_count())
1676 logf("No free tracks");
1681 tracks
[track_widx
].taginfo_ready
= false;
1683 logf("Buffering track:%d/%d", track_widx
, track_ridx
);
1684 /* Get track name from current playlist read position. */
1685 while ((trackname
= playlist_peek(last_peek_offset
)) != NULL
)
1687 /* Handle broken playlists. */
1688 fd
= open(trackname
, O_RDONLY
);
1691 logf("Open failed");
1692 /* Skip invalid entry from playlist. */
1693 playlist_skip_entry(NULL
, last_peek_offset
);
1701 logf("End-of-playlist");
1702 memset(&lasttrack_id3
, 0, sizeof(struct mp3entry
));
1703 filling
= STATE_END_OF_PLAYLIST
;
1705 if (curtrack_id3
.length
== 0 && curtrack_id3
.filesize
== 0)
1707 /* Stop playback if no valid track was found. */
1708 audio_stop_playback();
1714 tracks
[track_widx
].filesize
= filesize(fd
);
1716 if (offset
> tracks
[track_widx
].filesize
)
1719 /* Set default values */
1722 buf_set_watermark(filebuflen
/2);
1723 dsp_configure(ci
.dsp
, DSP_RESET
, 0);
1724 track_changed
= true;
1725 playlist_update_resume_info(audio_current_track());
1728 /* Get track metadata if we don't already have it. */
1729 if (tracks
[track_widx
].id3_hid
< 0)
1731 tracks
[track_widx
].id3_hid
= bufopen(trackname
, 0, TYPE_ID3
);
1733 if (tracks
[track_widx
].id3_hid
< 0)
1735 /* Buffer is full. */
1736 get_metadata(&lasttrack_id3
, fd
, trackname
);
1739 logf("buffer is full for now");
1740 filling
= STATE_FULL
;
1744 if (track_widx
== track_ridx
)
1746 /* TODO: Superfluos buffering call? */
1747 buf_request_buffer_handle(tracks
[track_widx
].id3_hid
);
1748 copy_mp3entry(&curtrack_id3
, bufgetid3(tracks
[track_widx
].id3_hid
));
1749 curtrack_id3
.offset
= offset
;
1754 track_changed
= true;
1755 playlist_update_resume_info(audio_current_track());
1760 track_load_started
= true; /* Remember that we've started loading a track */
1764 /* Second part of the track loading: We now have the metadata available, so we
1765 can load the codec, the album art and finally the audio data.
1766 This is called on the audio thread after the buffering thread calls the
1767 buffering_handle_finished_callback callback. */
1768 static void audio_finish_load_track(void)
1770 size_t file_offset
= 0;
1772 bool start_play
= start_play_g
;
1774 track_load_started
= false;
1776 if (tracks
[track_widx
].id3_hid
< 0) {
1777 logf("no metatdata");
1781 struct mp3entry
*track_id3
;
1783 if (track_widx
== track_ridx
)
1784 track_id3
= &curtrack_id3
;
1786 track_id3
= bufgetid3(tracks
[track_widx
].id3_hid
);
1788 if (track_id3
->length
== 0 && track_id3
->filesize
== 0)
1790 logf("audio_finish_load_track: invalid metadata");
1792 /* Invalid metadata */
1793 bufclose(tracks
[track_widx
].id3_hid
);
1794 tracks
[track_widx
].id3_hid
= -1;
1796 /* Skip invalid entry from playlist. */
1797 playlist_skip_entry(NULL
, last_peek_offset
--);
1799 /* load next track */
1800 LOGFQUEUE("audio > audio Q_AUDIO_FILL_BUFFER %d", (int)start_play
);
1801 queue_post(&audio_queue
, Q_AUDIO_FILL_BUFFER
, start_play
);
1806 #ifdef HAVE_ALBUMART
1807 if (tracks
[track_widx
].aa_hid
< 0 && gui_sync_wps_uses_albumart())
1809 char aa_path
[MAX_PATH
];
1810 if (find_albumart(track_id3
, aa_path
, sizeof(aa_path
)))
1812 tracks
[track_widx
].aa_hid
= bufopen(aa_path
, 0, TYPE_BITMAP
);
1814 if(tracks
[track_widx
].aa_hid
== ERR_BUFFER_FULL
)
1816 filling
= STATE_FULL
;
1817 logf("buffer is full for now");
1818 return; /* No space for track's album art, not an error */
1820 else if (tracks
[track_widx
].aa_hid
< 0)
1822 /* another error, ignore AlbumArt */
1823 logf("Album art loading failed");
1829 /* Load the codec. */
1830 if (!audio_loadcodec(start_play
))
1832 if (tracks
[track_widx
].codec_hid
== ERR_BUFFER_FULL
)
1834 /* No space for codec on buffer, not an error */
1835 filling
= STATE_FULL
;
1839 /* This is an error condition, either no codec was found, or reading
1840 * the codec file failed part way through, either way, skip the track */
1841 /* FIXME: We should not use splashf from audio thread! */
1842 splashf(HZ
*2, "No codec for: %s", track_id3
->path
);
1843 /* Skip invalid entry from playlist. */
1844 playlist_skip_entry(NULL
, last_peek_offset
);
1848 track_id3
->elapsed
= 0;
1849 offset
= track_id3
->offset
;
1851 enum data_type type
= TYPE_PACKET_AUDIO
;
1853 switch (track_id3
->codectype
) {
1858 file_offset
= offset
;
1859 track_id3
->offset
= offset
;
1865 file_offset
= offset
;
1866 track_id3
->offset
= offset
;
1867 track_id3
->elapsed
= track_id3
->length
/ 2;
1871 case AFMT_OGG_VORBIS
:
1881 track_id3
->offset
= offset
;
1887 logf("Loading atomic %d",track_id3
->codectype
);
1888 type
= TYPE_ATOMIC_AUDIO
;
1892 logf("alt:%s", track_id3
->path
);
1894 if (file_offset
> AUDIO_REBUFFER_GUESS_SIZE
)
1895 file_offset
-= AUDIO_REBUFFER_GUESS_SIZE
;
1896 else if (track_id3
->first_frame_offset
)
1897 file_offset
= track_id3
->first_frame_offset
;
1901 tracks
[track_widx
].audio_hid
= bufopen(track_id3
->path
, file_offset
, type
);
1903 /* No space left, not an error */
1904 if (tracks
[track_widx
].audio_hid
== ERR_BUFFER_FULL
)
1906 filling
= STATE_FULL
;
1907 logf("buffer is full for now");
1910 else if (tracks
[track_widx
].audio_hid
< 0)
1912 /* another error, do not continue either */
1913 logf("Could not add audio data handle");
1917 /* All required data is now available for the codec. */
1918 tracks
[track_widx
].taginfo_ready
= true;
1922 ci
.curpos
=file_offset
;
1923 buf_request_buffer_handle(tracks
[track_widx
].audio_hid
);
1926 track_widx
= (track_widx
+ 1) & MAX_TRACK_MASK
;
1928 send_event(PLAYBACK_EVENT_TRACK_BUFFER
, track_id3
);
1930 /* load next track */
1931 LOGFQUEUE("audio > audio Q_AUDIO_FILL_BUFFER");
1932 queue_post(&audio_queue
, Q_AUDIO_FILL_BUFFER
, 0);
1937 static void audio_fill_file_buffer(bool start_play
, size_t offset
)
1939 bool had_next_track
= audio_next_track() != NULL
;
1941 filling
= STATE_FILLING
;
1942 trigger_cpu_boost();
1944 /* No need to rebuffer if there are track skips pending. */
1945 if (ci
.new_track
!= 0)
1948 /* Must reset the buffer before use if trashed or voice only - voice
1949 file size shouldn't have changed so we can go straight from
1950 AUDIOBUF_STATE_VOICED_ONLY to AUDIOBUF_STATE_INITIALIZED */
1951 if (buffer_state
!= AUDIOBUF_STATE_INITIALIZED
)
1952 audio_reset_buffer();
1954 logf("Starting buffer fill");
1957 audio_clear_track_entries();
1959 /* Save the current resume position once. */
1960 playlist_update_resume_info(audio_current_track());
1962 audio_load_track(offset
, start_play
);
1964 if (!had_next_track
&& audio_next_track())
1965 track_changed
= true;
1968 static void audio_rebuffer(void)
1970 logf("Forcing rebuffer");
1972 clear_track_info(CUR_TI
);
1974 /* Reset track pointers */
1975 track_widx
= track_ridx
;
1976 audio_clear_track_entries();
1978 /* Reset a possibly interrupted track load */
1979 track_load_started
= false;
1981 /* Fill the buffer */
1982 last_peek_offset
= -1;
1985 if (!CUR_TI
->taginfo_ready
)
1986 memset(&curtrack_id3
, 0, sizeof(struct mp3entry
));
1988 audio_fill_file_buffer(false, 0);
1991 /* Called on request from the codec to get a new track. This is the codec part
1992 of the track transition. */
1993 static int audio_check_new_track(void)
1995 int track_count
= audio_track_count();
1996 int old_track_ridx
= track_ridx
;
2000 /* Now it's good time to send track finish events. */
2001 send_event(PLAYBACK_EVENT_TRACK_FINISH
, &curtrack_id3
);
2005 /* regardless of the return value we need to rebuffer.
2006 if it fails the old playlist will resume, else the
2007 next dir will start playing */
2008 playlist_next_dir(ci
.new_track
);
2017 /* If the playlist isn't that big */
2020 while (!playlist_check(ci
.new_track
))
2022 if (ci
.new_track
>= 0)
2024 LOGFQUEUE("audio >|= codec Q_CODEC_REQUEST_FAILED");
2025 return Q_CODEC_REQUEST_FAILED
;
2031 /* Update the playlist */
2032 last_peek_offset
-= ci
.new_track
;
2034 if (playlist_next(ci
.new_track
) < 0)
2036 LOGFQUEUE("audio >|= codec Q_CODEC_REQUEST_FAILED");
2037 return Q_CODEC_REQUEST_FAILED
;
2043 new_playlist
= false;
2046 /* Save the track metadata to allow the WPS to display it
2047 while PCM finishes playing that track */
2048 copy_mp3entry(&prevtrack_id3
, &curtrack_id3
);
2050 /* Update the main buffer copy of the track metadata with the one
2051 the codec has been using (for the unbuffer callbacks) */
2052 if (CUR_TI
->id3_hid
>= 0)
2053 copy_mp3entry(bufgetid3(CUR_TI
->id3_hid
), &curtrack_id3
);
2055 /* Save a pointer to the old track to allow later clearing */
2058 for (i
= 0; i
< ci
.new_track
; i
++)
2060 idx
= (track_ridx
+ i
) & MAX_TRACK_MASK
;
2061 struct mp3entry
*id3
= bufgetid3(tracks
[idx
].id3_hid
);
2062 ssize_t offset
= buf_handle_offset(tracks
[idx
].audio_hid
);
2063 if (!id3
|| offset
< 0 || (unsigned)offset
> id3
->first_frame_offset
)
2065 /* We don't have all the audio data for that track, so clear it,
2066 but keep the metadata. */
2067 if (tracks
[idx
].audio_hid
>= 0 && bufclose(tracks
[idx
].audio_hid
))
2069 tracks
[idx
].audio_hid
= -1;
2070 tracks
[idx
].filesize
= 0;
2075 /* Move to the new track */
2076 track_ridx
= (track_ridx
+ ci
.new_track
) & MAX_TRACK_MASK
;
2078 buf_set_base_handle(CUR_TI
->audio_hid
);
2082 wps_offset
= -ci
.new_track
;
2083 track_changed
= true;
2086 /* If it is not safe to even skip this many track entries */
2087 if (ci
.new_track
>= track_count
|| ci
.new_track
<= track_count
- MAX_TRACK
)
2094 forward
= ci
.new_track
> 0;
2097 /* If the target track is clearly not in memory */
2098 if (CUR_TI
->filesize
== 0 || !CUR_TI
->taginfo_ready
)
2104 /* When skipping backwards, it is possible that we've found a track that's
2105 * buffered, but which is around the track-wrap and therefore not the track
2106 * we are looking for */
2109 int cur_idx
= track_ridx
;
2110 bool taginfo_ready
= true;
2111 /* We've wrapped the buffer backwards if new > old */
2112 bool wrap
= track_ridx
> old_track_ridx
;
2116 cur_idx
= (cur_idx
+ 1) & MAX_TRACK_MASK
;
2118 /* if we've advanced past the wrap when cur_idx is zeroed */
2122 /* if we aren't still on the wrap and we've caught the old track */
2123 if (!(wrap
|| cur_idx
< old_track_ridx
))
2126 /* If we hit a track in between without valid tag info, bail */
2127 if (!tracks
[cur_idx
].taginfo_ready
)
2129 taginfo_ready
= false;
2140 audio_update_trackinfo();
2141 LOGFQUEUE("audio >|= codec Q_CODEC_REQUEST_COMPLETE");
2142 return Q_CODEC_REQUEST_COMPLETE
;
2145 unsigned long audio_prev_elapsed(void)
2147 return prev_track_elapsed
;
2150 static void audio_stop_codec_flush(void)
2152 ci
.stop_codec
= true;
2155 while (audio_codec_loaded
)
2158 /* If the audio codec is not loaded any more, and the audio is still
2159 * playing, it is now and _only_ now safe to call this function from the
2161 if (pcm_is_playing())
2164 pcmbuf_queue_clear();
2166 pcmbuf_pause(paused
);
2169 static void audio_stop_playback(void)
2171 /* If we were playing, save resume information */
2174 struct mp3entry
*id3
= NULL
;
2178 /* Set this early, the outside code yields and may allow the codec
2179 to try to wait for a reply on a buffer wait */
2180 ci
.stop_codec
= true;
2181 id3
= audio_current_track();
2184 /* Save the current playing spot, or NULL if the playlist has ended */
2185 playlist_update_resume_info(id3
);
2187 /* TODO: Create auto bookmark too? */
2189 prev_track_elapsed
= curtrack_id3
.elapsed
;
2191 remove_event(BUFFER_EVENT_BUFFER_LOW
, buffering_low_buffer_callback
);
2194 audio_stop_codec_flush();
2197 track_load_started
= false;
2199 filling
= STATE_IDLE
;
2201 /* Mark all entries null. */
2202 audio_clear_track_entries();
2204 /* Close all tracks */
2205 audio_release_tracks();
2207 memset(&curtrack_id3
, 0, sizeof(struct mp3entry
));
2210 static void audio_play_start(size_t offset
)
2214 #if INPUT_SRC_CAPS != 0
2215 audio_set_input_source(AUDIO_SRC_PLAYBACK
, SRCF_PLAYBACK
);
2216 audio_set_output_source(AUDIO_SRC_PLAYBACK
);
2219 /* Wait for any previously playing audio to flush - TODO: Not necessary? */
2221 audio_stop_codec_flush();
2223 track_changed
= true;
2226 track_load_started
= false;
2232 sound_set_volume(global_settings
.volume
);
2233 track_widx
= track_ridx
= 0;
2235 /* Clear all track entries. */
2236 for (i
= 0; i
< MAX_TRACK
; i
++) {
2237 clear_track_info(&tracks
[i
]);
2240 last_peek_offset
= -1;
2242 /* Officially playing */
2243 queue_reply(&audio_queue
, 1);
2245 audio_fill_file_buffer(true, offset
);
2247 add_event(BUFFER_EVENT_BUFFER_LOW
, false, buffering_low_buffer_callback
);
2249 LOGFQUEUE("audio > audio Q_AUDIO_TRACK_CHANGED");
2250 queue_post(&audio_queue
, Q_AUDIO_TRACK_CHANGED
, 0);
2254 /* Invalidates all but currently playing track. */
2255 static void audio_invalidate_tracks(void)
2257 if (audio_have_tracks())
2259 last_peek_offset
= 0;
2260 track_widx
= track_ridx
;
2262 /* Mark all other entries null (also buffered wrong metadata). */
2263 audio_clear_track_entries();
2265 track_widx
= (track_widx
+ 1) & MAX_TRACK_MASK
;
2267 audio_fill_file_buffer(false, 0);
2271 static void audio_new_playlist(void)
2273 /* Prepare to start a new fill from the beginning of the playlist */
2274 last_peek_offset
= -1;
2275 if (audio_have_tracks())
2278 skipped_during_pause
= true;
2279 track_widx
= track_ridx
;
2280 audio_clear_track_entries();
2282 track_widx
= (track_widx
+ 1) & MAX_TRACK_MASK
;
2284 /* Mark the current track as invalid to prevent skipping back to it */
2285 CUR_TI
->taginfo_ready
= false;
2288 /* Signal the codec to initiate a track change forward */
2289 new_playlist
= true;
2292 /* Officially playing */
2293 queue_reply(&audio_queue
, 1);
2295 audio_fill_file_buffer(false, 0);
2298 /* Called on manual track skip */
2299 static void audio_initiate_track_change(long direction
)
2301 logf("audio_initiate_track_change(%ld)", direction
);
2303 ci
.new_track
+= direction
;
2304 wps_offset
-= direction
;
2306 skipped_during_pause
= true;
2309 /* Called on manual dir skip */
2310 static void audio_initiate_dir_change(long direction
)
2313 ci
.new_track
= direction
;
2315 skipped_during_pause
= true;
2318 /* Called when PCM track change is complete */
2319 static void audio_finalise_track_change(void)
2321 logf("audio_finalise_track_change");
2326 automatic_skip
= false;
2328 /* Invalidate prevtrack_id3 */
2329 prevtrack_id3
.path
[0] = 0;
2331 if (prev_ti
&& prev_ti
->audio_hid
< 0)
2333 /* No audio left so we clear all the track info. */
2334 clear_track_info(prev_ti
);
2337 if (prev_ti
&& prev_ti
->id3_hid
>= 0)
2339 /* Reset the elapsed time to force the progressbar to be empty if
2340 the user skips back to this track */
2341 bufgetid3(prev_ti
->id3_hid
)->elapsed
= 0;
2345 send_event(PLAYBACK_EVENT_TRACK_CHANGE
, &curtrack_id3
);
2347 track_changed
= true;
2348 playlist_update_resume_info(audio_current_track());
2352 * Layout audio buffer as follows - iram buffer depends on target:
2353 * [|SWAP:iram][|TALK]|FILE|GUARD|PCM|[SWAP:dram[|iram]|]
2355 static void audio_reset_buffer(void)
2357 /* see audio_get_recording_buffer if this is modified */
2358 logf("audio_reset_buffer");
2360 /* If the setup of anything allocated before the file buffer is
2361 changed, do check the adjustments after the buffer_alloc call
2362 as it will likely be affected and need sliding over */
2364 /* Initially set up file buffer as all space available */
2365 malloc_buf
= audiobuf
+ talk_get_bufsize();
2366 /* Align the malloc buf to line size. Especially important to cf
2367 targets that do line reads/writes. */
2368 malloc_buf
= (unsigned char *)(((uintptr_t)malloc_buf
+ 15) & ~15);
2369 filebuf
= malloc_buf
; /* filebuf line align implied */
2370 filebuflen
= audiobufend
- filebuf
;
2374 /* Subtract whatever the pcm buffer says it used plus the guard buffer */
2375 const size_t pcmbuf_size
= pcmbuf_init(filebuf
+ filebuflen
) +GUARD_BUFSIZE
;
2378 if(pcmbuf_size
> filebuflen
)
2379 panicf("Not enough memory for pcmbuf_init() : %d > %d",
2380 (int)pcmbuf_size
, (int)filebuflen
);
2383 filebuflen
-= pcmbuf_size
;
2385 /* Make sure filebuflen is a longword multiple after adjustment - filebuf
2386 will already be line aligned */
2389 buffering_reset(filebuf
, filebuflen
);
2391 /* Clear any references to the file buffer */
2392 buffer_state
= AUDIOBUF_STATE_INITIALIZED
;
2394 #if defined(ROCKBOX_HAS_LOGF) && defined(LOGF_ENABLE)
2395 /* Make sure everything adds up - yes, some info is a bit redundant but
2396 aids viewing and the sumation of certain variables should add up to
2397 the location of others. */
2400 const unsigned char *pcmbuf
= pcmbuf_get_meminfo(&pcmbufsize
);
2401 logf("mabuf: %08X", (unsigned)malloc_buf
);
2402 logf("fbuf: %08X", (unsigned)filebuf
);
2403 logf("fbufe: %08X", (unsigned)(filebuf
+ filebuflen
));
2404 logf("gbuf: %08X", (unsigned)(filebuf
+ filebuflen
));
2405 logf("gbufe: %08X", (unsigned)(filebuf
+ filebuflen
+ GUARD_BUFSIZE
));
2406 logf("pcmb: %08X", (unsigned)pcmbuf
);
2407 logf("pcmbe: %08X", (unsigned)(pcmbuf
+ pcmbufsize
));
2412 static void audio_thread(void)
2414 struct queue_event ev
;
2418 audio_thread_ready
= true;
2422 if (filling
!= STATE_FILLING
) {
2423 /* End of buffering, let's calculate the watermark and unboost */
2424 set_filebuf_watermark();
2428 if (!pcmbuf_queue_scan(&ev
))
2429 queue_wait_w_tmo(&audio_queue
, &ev
, HZ
/2);
2433 case Q_AUDIO_FILL_BUFFER
:
2434 LOGFQUEUE("audio < Q_AUDIO_FILL_BUFFER %d", (int)ev
.data
);
2435 audio_fill_file_buffer((bool)ev
.data
, 0);
2438 case Q_AUDIO_FINISH_LOAD
:
2439 LOGFQUEUE("audio < Q_AUDIO_FINISH_LOAD");
2440 audio_finish_load_track();
2444 LOGFQUEUE("audio < Q_AUDIO_PLAY");
2445 if (playing
&& ev
.data
<= 0)
2446 audio_new_playlist();
2449 audio_stop_playback();
2450 audio_play_start((size_t)ev
.data
);
2455 LOGFQUEUE("audio < Q_AUDIO_STOP");
2457 audio_stop_playback();
2459 queue_clear(&audio_queue
);
2463 LOGFQUEUE("audio < Q_AUDIO_PAUSE");
2464 if (!(bool) ev
.data
&& skipped_during_pause
&& !pcmbuf_is_crossfade_active())
2465 pcmbuf_play_stop(); /* Flush old track on resume after skip */
2466 skipped_during_pause
= false;
2469 pcmbuf_pause((bool)ev
.data
);
2470 paused
= (bool)ev
.data
;
2474 LOGFQUEUE("audio < Q_AUDIO_SKIP");
2475 audio_initiate_track_change((long)ev
.data
);
2478 case Q_AUDIO_PRE_FF_REWIND
:
2479 LOGFQUEUE("audio < Q_AUDIO_PRE_FF_REWIND");
2485 case Q_AUDIO_FF_REWIND
:
2486 LOGFQUEUE("audio < Q_AUDIO_FF_REWIND");
2491 /* An automatic track skip is in progress. Finalize it,
2492 then go back to the previous track */
2493 audio_finalise_track_change();
2496 ci
.seek_time
= (long)ev
.data
+1;
2499 case Q_AUDIO_CHECK_NEW_TRACK
:
2500 LOGFQUEUE("audio < Q_AUDIO_CHECK_NEW_TRACK");
2501 queue_reply(&audio_queue
, audio_check_new_track());
2504 case Q_AUDIO_DIR_SKIP
:
2505 LOGFQUEUE("audio < Q_AUDIO_DIR_SKIP");
2506 audio_initiate_dir_change(ev
.data
);
2510 LOGFQUEUE("audio < Q_AUDIO_FLUSH");
2511 audio_invalidate_tracks();
2514 case Q_AUDIO_TRACK_CHANGED
:
2515 /* PCM track change done */
2516 LOGFQUEUE("audio < Q_AUDIO_TRACK_CHANGED");
2517 audio_finalise_track_change();
2521 case SYS_USB_CONNECTED
:
2522 LOGFQUEUE("audio < SYS_USB_CONNECTED");
2524 audio_stop_playback();
2525 #ifdef PLAYBACK_VOICE
2528 usb_acknowledge(SYS_USB_CONNECTED_ACK
);
2529 usb_wait_for_disconnect(&audio_queue
);
2531 /* Mark all entries null. */
2532 audio_clear_track_entries();
2534 /* release tracks to make sure all handles are closed */
2535 audio_release_tracks();
2540 LOGFQUEUE_SYS_TIMEOUT("audio < SYS_TIMEOUT");
2544 LOGFQUEUE("audio < default");
2550 /* Initialize the audio system - called from init() in main.c.
2551 * Last function because of all the references to internal symbols
2553 void audio_init(void)
2555 unsigned int audio_thread_id
;
2557 /* Can never do this twice */
2558 if (audio_is_initialized
)
2560 logf("audio: already initialized");
2564 logf("audio: initializing");
2566 /* Initialize queues before giving control elsewhere in case it likes
2567 to send messages. Thread creation will be delayed however so nothing
2568 starts running until ready if something yields such as talk_init. */
2569 queue_init(&audio_queue
, true);
2570 queue_init(&codec_queue
, false);
2571 queue_init(&pcmbuf_queue
, false);
2575 /* Initialize codec api. */
2576 ci
.read_filebuf
= codec_filebuf_callback
;
2577 ci
.pcmbuf_insert
= codec_pcmbuf_insert_callback
;
2578 ci
.codec_get_buffer
= codec_get_buffer
;
2579 ci
.request_buffer
= codec_request_buffer_callback
;
2580 ci
.advance_buffer
= codec_advance_buffer_callback
;
2581 ci
.advance_buffer_loc
= codec_advance_buffer_loc_callback
;
2582 ci
.request_next_track
= codec_request_next_track_callback
;
2583 ci
.seek_buffer
= codec_seek_buffer_callback
;
2584 ci
.seek_complete
= codec_seek_complete_callback
;
2585 ci
.set_elapsed
= codec_set_elapsed_callback
;
2586 ci
.set_offset
= codec_set_offset_callback
;
2587 ci
.configure
= codec_configure_callback
;
2588 ci
.discard_codec
= codec_discard_codec_callback
;
2589 ci
.dsp
= (struct dsp_config
*)dsp_configure(NULL
, DSP_MYDSP
,
2592 /* initialize the buffer */
2595 /* audio_reset_buffer must to know the size of voice buffer so init
2599 codec_thread_id
= create_thread(
2600 codec_thread
, codec_stack
, sizeof(codec_stack
),
2601 CREATE_THREAD_FROZEN
,
2602 codec_thread_name
IF_PRIO(, PRIORITY_PLAYBACK
)
2605 queue_enable_queue_send(&codec_queue
, &codec_queue_sender_list
,
2608 audio_thread_id
= create_thread(audio_thread
, audio_stack
,
2609 sizeof(audio_stack
), CREATE_THREAD_FROZEN
,
2610 audio_thread_name
IF_PRIO(, PRIORITY_USER_INTERFACE
)
2613 queue_enable_queue_send(&audio_queue
, &audio_queue_sender_list
,
2616 #ifdef PLAYBACK_VOICE
2617 voice_thread_init();
2620 /* Set crossfade setting for next buffer init which should be about... */
2621 pcmbuf_crossfade_enable(global_settings
.crossfade
);
2623 /* initialize the buffering system */
2626 /* ...now! Set up the buffers */
2627 audio_reset_buffer();
2630 for(i
= 0; i
< MAX_TRACK
; i
++)
2632 tracks
[i
].audio_hid
= -1;
2633 tracks
[i
].id3_hid
= -1;
2634 tracks
[i
].codec_hid
= -1;
2635 #ifdef HAVE_ALBUMART
2636 tracks
[i
].aa_hid
= -1;
2640 add_event(BUFFER_EVENT_REBUFFER
, false, buffering_handle_rebuffer_callback
);
2641 add_event(BUFFER_EVENT_FINISHED
, false, buffering_handle_finished_callback
);
2643 /* Probably safe to say */
2644 audio_is_initialized
= true;
2646 sound_settings_apply();
2647 #ifdef HAVE_DISK_STORAGE
2648 audio_set_buffer_margin(global_settings
.buffer_margin
);
2651 /* it's safe to let the threads run now */
2652 #ifdef PLAYBACK_VOICE
2653 voice_thread_resume();
2655 thread_thaw(codec_thread_id
);
2656 thread_thaw(audio_thread_id
);
2660 bool audio_is_thread_ready(void)
2662 return audio_thread_ready
;