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"
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"
84 #define PLAYBACK_VOICE
86 /* default point to start buffer refill */
87 #define AUDIO_DEFAULT_WATERMARK (1024*512)
88 /* amount of guess-space to allow for codecs that must hunt and peck
89 * for their correct seeek target, 32k seems a good size */
90 #define AUDIO_REBUFFER_GUESS_SIZE (1024*32)
92 /* Define LOGF_ENABLE to enable logf output in this file */
93 /*#define LOGF_ENABLE*/
96 /* macros to enable logf for queues
97 logging on SYS_TIMEOUT can be disabled */
99 /* Define this for logf output of all queuing except SYS_TIMEOUT */
100 #define PLAYBACK_LOGQUEUES
101 /* Define this to logf SYS_TIMEOUT messages */
102 /*#define PLAYBACK_LOGQUEUES_SYS_TIMEOUT*/
105 #ifdef PLAYBACK_LOGQUEUES
106 #define LOGFQUEUE logf
108 #define LOGFQUEUE(...)
111 #ifdef PLAYBACK_LOGQUEUES_SYS_TIMEOUT
112 #define LOGFQUEUE_SYS_TIMEOUT logf
114 #define LOGFQUEUE_SYS_TIMEOUT(...)
118 /* Define one constant that includes recording related functionality */
119 #if defined(HAVE_RECORDING) && !defined(SIMULATOR)
120 #define AUDIO_HAVE_RECORDING
129 Q_AUDIO_PRE_FF_REWIND
,
131 Q_AUDIO_CHECK_NEW_TRACK
,
133 Q_AUDIO_TRACK_CHANGED
,
138 Q_CODEC_REQUEST_COMPLETE
,
139 Q_CODEC_REQUEST_FAILED
,
144 #ifdef AUDIO_HAVE_RECORDING
151 STATE_IDLE
, /* audio is stopped: nothing to do */
152 STATE_FILLING
, /* adding tracks to the buffer */
153 STATE_FULL
, /* can't add any more tracks */
154 STATE_END_OF_PLAYLIST
, /* all remaining tracks have been added */
155 STATE_FINISHED
, /* all remaining tracks are fully buffered */
159 #define MAX_TRACK 128
164 #define MAX_TRACK_MASK (MAX_TRACK-1)
166 /* As defined in plugins/lib/xxx2wav.h */
168 #define MALLOC_BUFSIZE (512*1024)
169 #define GUARD_BUFSIZE (32*1024)
171 #define MALLOC_BUFSIZE (100*1024)
172 #define GUARD_BUFSIZE (8*1024)
175 /* As defined in plugin.lds */
177 #define CODEC_IRAM_ORIGIN ((unsigned char *)0x4000c000)
178 #define CODEC_IRAM_SIZE ((size_t)0xc000)
179 #elif defined(IAUDIO_X5) || defined(IAUDIO_M5)
180 #define CODEC_IRAM_ORIGIN ((unsigned char *)0x10010000)
181 #define CODEC_IRAM_SIZE ((size_t)0x10000)
183 #define CODEC_IRAM_ORIGIN ((unsigned char *)0x1000c000)
184 #define CODEC_IRAM_SIZE ((size_t)0xc000)
187 bool audio_is_initialized
= false;
188 static bool audio_thread_ready SHAREDBSS_ATTR
= false;
190 /* Variables are commented with the threads that use them: *
191 * A=audio, C=codec, V=voice. A suffix of - indicates that *
192 * the variable is read but not updated on that thread. */
193 /* TBD: Split out "audio" and "playback" (ie. calling) threads */
195 /* Main state control */
196 static volatile bool audio_codec_loaded SHAREDBSS_ATTR
= false; /* Codec loaded? (C/A-) */
197 static volatile bool playing SHAREDBSS_ATTR
= false; /* Is audio playing? (A) */
198 static volatile bool paused SHAREDBSS_ATTR
= false; /* Is audio paused? (A/C-) */
200 /* Ring buffer where compressed audio and codecs are loaded */
201 static unsigned char *filebuf
= NULL
; /* Start of buffer (A/C-) */
202 static unsigned char *malloc_buf
= NULL
; /* Start of malloc buffer (A/C-) */
203 /* FIXME: make filebuflen static */
204 size_t filebuflen
= 0; /* Size of buffer (A/C-) */
205 /* FIXME: make buf_ridx (C/A-) */
207 /* Possible arrangements of the buffer */
208 #define BUFFER_STATE_TRASHED -1 /* trashed; must be reset */
209 #define BUFFER_STATE_INITIALIZED 0 /* voice+audio OR audio-only */
210 #define BUFFER_STATE_VOICED_ONLY 1 /* voice-only */
211 static int buffer_state
= BUFFER_STATE_TRASHED
; /* Buffer state */
213 /* Used to keep the WPS up-to-date during track transtition */
214 static struct mp3entry prevtrack_id3
;
216 /* Used to provide the codec with a pointer */
217 static struct mp3entry curtrack_id3
;
219 /* Used to make next track info available while playing last track on buffer */
220 static struct mp3entry lasttrack_id3
;
222 /* Track info structure about songs in the file buffer (A/C-) */
224 int audio_hid
; /* The ID for the track's buffer handle */
225 int id3_hid
; /* The ID for the track's metadata handle */
226 int codec_hid
; /* The ID for the track's codec handle */
228 int aa_hid
; /* The ID for the track's album art handle */
231 size_t filesize
; /* File total length */
233 bool taginfo_ready
; /* Is metadata read */
236 static struct track_info tracks
[MAX_TRACK
];
237 static volatile int track_ridx
= 0; /* Track being decoded (A/C-) */
238 static int track_widx
= 0; /* Track being buffered (A) */
240 #define CUR_TI (&tracks[track_ridx]) /* Playing track info pointer (A/C-) */
241 static struct track_info
*prev_ti
= NULL
; /* Pointer to the previously played
244 /* Set by the audio thread when the current track information has updated
245 * and the WPS may need to update its cached information */
246 static bool track_changed
= false;
248 /* Information used only for filling the buffer */
249 /* Playlist steps from playing track to next track to be buffered (A) */
250 static int last_peek_offset
= 0;
252 /* Scrobbler support */
253 static unsigned long prev_track_elapsed
= 0; /* Previous track elapsed time (C/A-)*/
255 static enum filling_state filling
;
257 /* Track change controls */
258 static bool automatic_skip
= false; /* Who initiated in-progress skip? (C/A-) */
259 static bool dir_skip
= false; /* Is a directory skip pending? (A) */
260 static bool new_playlist
= false; /* Are we starting a new playlist? (A) */
261 static int wps_offset
= 0; /* Pending track change offset, to keep WPS responsive (A) */
262 static bool skipped_during_pause
= false; /* Do we need to clear the PCM buffer when playback resumes (A) */
264 static bool start_play_g
= false; /* Used by audio_load_track to notify
265 audio_finish_load_track about start_play */
267 /* Set to true if the codec thread should send an audio stop request
268 * (typically because the end of the playlist has been reached).
270 static bool codec_requested_stop
= false;
272 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) FIXME */
276 static void set_filebuf_watermark(int seconds
, size_t max
);
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);
290 extern struct codec_api ci
;
291 static struct event_queue codec_queue SHAREDBSS_ATTR
;
292 static struct queue_sender_list codec_queue_sender_list
;
293 static long codec_stack
[(DEFAULT_STACK_SIZE
+ 0x2000)/sizeof(long)]
295 static const char codec_thread_name
[] = "codec";
296 struct thread_entry
*codec_thread_p
; /* For modifying thread priority later. */
298 /* PCM buffer messaging */
299 static struct event_queue pcmbuf_queue SHAREDBSS_ATTR
;
301 /* Function to be called by pcm buffer callbacks.
302 * Permissible Context(s): Audio interrupt
304 static void pcmbuf_callback_queue_post(long id
, intptr_t data
)
306 /* No lock since we're already in audio interrupt context */
307 queue_post(&pcmbuf_queue
, id
, data
);
310 /* Scan the pcmbuf queue and return true if a message pulled.
311 * Permissible Context(s): Thread
313 static bool pcmbuf_queue_scan(struct queue_event
*ev
)
315 if (!queue_empty(&pcmbuf_queue
))
317 /* Transfer message to audio queue */
319 /* Pull message - never, ever any blocking call! */
320 queue_wait_w_tmo(&pcmbuf_queue
, ev
, 0);
328 /* Clear the pcmbuf queue of messages
329 * Permissible Context(s): Thread
331 static void pcmbuf_queue_clear(void)
334 queue_clear(&pcmbuf_queue
);
338 /* --- Helper functions --- */
340 static struct mp3entry
*bufgetid3(int handle_id
)
345 struct mp3entry
*id3
;
346 ssize_t ret
= bufgetdata(handle_id
, 0, (void *)&id3
);
348 if (ret
< 0 || ret
!= sizeof(struct mp3entry
))
354 static bool clear_track_info(struct track_info
*track
)
356 /* bufclose returns true if the handle is not found, or if it is closed
357 * successfully, so these checks are safe on non-existant handles */
361 if (track
->codec_hid
>= 0) {
362 if (bufclose(track
->codec_hid
))
363 track
->codec_hid
= -1;
368 if (track
->id3_hid
>= 0) {
369 if (bufclose(track
->id3_hid
))
375 if (track
->audio_hid
>= 0) {
376 if (bufclose(track
->audio_hid
))
377 track
->audio_hid
= -1;
383 if (track
->aa_hid
>= 0) {
384 if (bufclose(track
->aa_hid
))
392 track
->taginfo_ready
= false;
397 /* --- External interfaces --- */
399 /* This sends a stop message and the audio thread will dump all it's
400 subsequenct messages */
401 void audio_hard_stop(void)
404 LOGFQUEUE("audio >| audio Q_AUDIO_STOP: 1");
405 queue_send(&audio_queue
, Q_AUDIO_STOP
, 1);
406 #ifdef PLAYBACK_VOICE
411 bool audio_restore_playback(int type
)
415 case AUDIO_WANT_PLAYBACK
:
416 if (buffer_state
!= BUFFER_STATE_INITIALIZED
)
417 audio_reset_buffer();
419 case AUDIO_WANT_VOICE
:
420 if (buffer_state
== BUFFER_STATE_TRASHED
)
421 audio_reset_buffer();
428 unsigned char *audio_get_buffer(bool talk_buf
, size_t *buffer_size
)
430 unsigned char *buf
, *end
;
432 if (audio_is_initialized
)
436 /* else buffer_state will be BUFFER_STATE_TRASHED at this point */
438 if (buffer_size
== NULL
)
440 /* Special case for talk_init to use since it already knows it's
442 buffer_state
= BUFFER_STATE_TRASHED
;
446 if (talk_buf
|| buffer_state
== BUFFER_STATE_TRASHED
447 || !talk_voice_required())
449 logf("get buffer: talk, audio");
450 /* Ok to use everything from audiobuf to audiobufend - voice is loaded,
451 the talk buffer is not needed because voice isn't being used, or
452 could be BUFFER_STATE_TRASHED already. If state is
453 BUFFER_STATE_VOICED_ONLY, no problem as long as memory isn't written
454 without the caller knowing what's going on. Changing certain settings
455 may move it to a worse condition but the memory in use by something
456 else will remain undisturbed.
458 if (buffer_state
!= BUFFER_STATE_TRASHED
)
461 buffer_state
= BUFFER_STATE_TRASHED
;
469 /* Safe to just return this if already BUFFER_STATE_VOICED_ONLY or
470 still BUFFER_STATE_INITIALIZED */
471 /* Skip talk buffer and move pcm buffer to end to maximize available
472 contiguous memory - no audio running means voice will not need the
474 logf("get buffer: audio");
475 buf
= audiobuf
+ talk_get_bufsize();
476 end
= audiobufend
- pcmbuf_init(audiobufend
);
477 buffer_state
= BUFFER_STATE_VOICED_ONLY
;
480 *buffer_size
= end
- buf
;
485 #ifdef HAVE_RECORDING
486 unsigned char *audio_get_recording_buffer(size_t *buffer_size
)
488 /* Stop audio, voice and obtain all available buffer space */
492 unsigned char *end
= audiobufend
;
493 buffer_state
= BUFFER_STATE_TRASHED
;
494 *buffer_size
= end
- audiobuf
;
496 return (unsigned char *)audiobuf
;
499 bool audio_load_encoder(int afmt
)
502 const char *enc_fn
= get_codec_filename(afmt
| CODEC_TYPE_ENCODER
);
506 audio_remove_encoder();
507 ci
.enc_codec_loaded
= 0; /* clear any previous error condition */
509 LOGFQUEUE("codec > Q_ENCODER_LOAD_DISK");
510 queue_post(&codec_queue
, Q_ENCODER_LOAD_DISK
, (intptr_t)enc_fn
);
512 while (ci
.enc_codec_loaded
== 0)
515 logf("codec loaded: %d", ci
.enc_codec_loaded
);
517 return ci
.enc_codec_loaded
> 0;
522 } /* audio_load_encoder */
524 void audio_remove_encoder(void)
527 /* force encoder codec unload (if currently loaded) */
528 if (ci
.enc_codec_loaded
<= 0)
531 ci
.stop_encoder
= true;
532 while (ci
.enc_codec_loaded
> 0)
535 } /* audio_remove_encoder */
537 #endif /* HAVE_RECORDING */
540 int audio_current_aa_hid(void)
543 int offset
= ci
.new_track
+ wps_offset
;
545 cur_idx
= track_ridx
+ offset
;
546 cur_idx
&= MAX_TRACK_MASK
;
548 return tracks
[cur_idx
].aa_hid
;
552 struct mp3entry
* audio_current_track(void)
554 const char *filename
;
556 static struct mp3entry temp_id3
;
557 struct playlist_track_info trackinfo
;
559 int offset
= ci
.new_track
+ wps_offset
;
561 cur_idx
= (track_ridx
+ offset
) & MAX_TRACK_MASK
;
563 if (cur_idx
== track_ridx
&& *curtrack_id3
.path
)
566 return &curtrack_id3
;
568 else if (automatic_skip
&& offset
== -1 && *prevtrack_id3
.path
)
570 /* We're in a track transition. The codec has moved on to the nex track,
571 but the audio being played is still the same (now previous) track.
572 prevtrack_id3.elapsed is being updated in an ISR by
573 codec_pcmbuf_position_callback */
574 return &prevtrack_id3
;
576 else if (tracks
[cur_idx
].id3_hid
>= 0)
578 /* Get the ID3 metadata from the main buffer */
579 struct mp3entry
*ret
= bufgetid3(tracks
[cur_idx
].id3_hid
);
583 /* We didn't find the ID3 metadata, so we fill temp_id3 with the little info
584 we have and return that. */
586 memset(&temp_id3
, 0, sizeof(struct mp3entry
));
588 playlist_get_track_info(NULL
, playlist_next(0)+wps_offset
, &trackinfo
);
589 filename
= trackinfo
.filename
;
591 filename
= "No file!";
593 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
594 if (tagcache_fill_tags(&temp_id3
, filename
))
598 p
= strrchr(filename
, '/');
604 strncpy(temp_id3
.path
, p
, sizeof(temp_id3
.path
)-1);
605 temp_id3
.title
= &temp_id3
.path
[0];
610 struct mp3entry
* audio_next_track(void)
613 int offset
= ci
.new_track
+ wps_offset
;
615 if (!audio_have_tracks())
618 if (wps_offset
== -1 && *prevtrack_id3
.path
)
620 /* We're in a track transition. The next track for the WPS is the one
621 currently being decoded. */
622 return &curtrack_id3
;
625 next_idx
= (track_ridx
+ offset
+ 1) & MAX_TRACK_MASK
;
627 if (tracks
[next_idx
].id3_hid
>= 0)
628 return bufgetid3(tracks
[next_idx
].id3_hid
);
630 if (next_idx
== track_widx
)
632 /* The next track hasn't been buffered yet, so we return the static
633 version of its metadata. */
634 return &lasttrack_id3
;
640 bool audio_has_changed_track(void)
644 track_changed
= false;
651 void audio_play(long offset
)
655 #ifdef PLAYBACK_VOICE
656 /* Truncate any existing voice output so we don't have spelling
657 * etc. over the first part of the played track */
662 LOGFQUEUE("audio >| audio Q_AUDIO_PLAY: %ld", offset
);
663 /* Don't return until playback has actually started */
664 queue_send(&audio_queue
, Q_AUDIO_PLAY
, offset
);
667 void audio_stop(void)
670 LOGFQUEUE("audio >| audio Q_AUDIO_STOP");
671 /* Don't return until playback has actually stopped */
672 queue_send(&audio_queue
, Q_AUDIO_STOP
, 0);
675 void audio_pause(void)
677 LOGFQUEUE("audio >| audio Q_AUDIO_PAUSE");
678 /* Don't return until playback has actually paused */
679 queue_send(&audio_queue
, Q_AUDIO_PAUSE
, true);
682 void audio_resume(void)
684 LOGFQUEUE("audio >| audio Q_AUDIO_PAUSE resume");
685 /* Don't return until playback has actually resumed */
686 queue_send(&audio_queue
, Q_AUDIO_PAUSE
, false);
689 static void audio_skip(int direction
)
691 if (playlist_check(ci
.new_track
+ wps_offset
+ direction
))
693 if (global_settings
.beep
)
694 pcmbuf_beep(5000, 100, 2500*global_settings
.beep
);
696 LOGFQUEUE("audio > audio Q_AUDIO_SKIP %d", direction
);
697 queue_post(&audio_queue
, Q_AUDIO_SKIP
, direction
);
698 /* Update wps while our message travels inside deep playback queues. */
699 wps_offset
+= direction
;
700 track_changed
= true;
704 /* No more tracks. */
705 if (global_settings
.beep
)
706 pcmbuf_beep(1000, 100, 1000*global_settings
.beep
);
710 void audio_next(void)
715 void audio_prev(void)
720 void audio_next_dir(void)
722 LOGFQUEUE("audio > audio Q_AUDIO_DIR_SKIP 1");
723 queue_post(&audio_queue
, Q_AUDIO_DIR_SKIP
, 1);
726 void audio_prev_dir(void)
728 LOGFQUEUE("audio > audio Q_AUDIO_DIR_SKIP -1");
729 queue_post(&audio_queue
, Q_AUDIO_DIR_SKIP
, -1);
732 void audio_pre_ff_rewind(void)
734 LOGFQUEUE("audio > audio Q_AUDIO_PRE_FF_REWIND");
735 queue_post(&audio_queue
, Q_AUDIO_PRE_FF_REWIND
, 0);
738 void audio_ff_rewind(long newpos
)
740 LOGFQUEUE("audio > audio Q_AUDIO_FF_REWIND");
741 queue_post(&audio_queue
, Q_AUDIO_FF_REWIND
, newpos
);
744 void audio_flush_and_reload_tracks(void)
746 LOGFQUEUE("audio > audio Q_AUDIO_FLUSH");
747 queue_post(&audio_queue
, Q_AUDIO_FLUSH
, 0);
750 void audio_error_clear(void)
752 #ifdef AUDIO_HAVE_RECORDING
753 pcm_rec_error_clear();
757 int audio_status(void)
762 ret
|= AUDIO_STATUS_PLAY
;
765 ret
|= AUDIO_STATUS_PAUSE
;
767 #ifdef HAVE_RECORDING
768 /* Do this here for constitency with mpeg.c version */
769 ret
|= pcm_rec_status();
775 int audio_get_file_pos(void)
780 #ifndef HAVE_FLASH_STORAGE
781 void audio_set_buffer_margin(int setting
)
783 static const int lookup
[] = {5, 15, 30, 60, 120, 180, 300, 600};
784 buffer_margin
= lookup
[setting
];
785 logf("buffer margin: %ld", (long)buffer_margin
);
786 set_filebuf_watermark(buffer_margin
, 0);
790 /* Take necessary steps to enable or disable the crossfade setting */
791 void audio_set_crossfade(int enable
)
797 /* Tell it the next setting to use */
798 pcmbuf_crossfade_enable(enable
);
800 /* Return if size hasn't changed or this is too early to determine
801 which in the second case there's no way we could be playing
803 if (pcmbuf_is_same_size())
805 /* This function is a copout and just syncs some variables -
806 to be removed at a later date */
807 pcmbuf_crossfade_enable_finished();
812 was_playing
= playing
;
814 /* Playback has to be stopped before changing the buffer size */
817 /* Store the track resume position */
818 offset
= curtrack_id3
.offset
;
819 gui_syncsplash(0, str(LANG_RESTARTING_PLAYBACK
));
822 /* Blast it - audio buffer will have to be setup again next time
824 audio_get_buffer(true, &size
);
826 /* Restart playback if audio was running previously */
831 /* --- Routines called from multiple threads --- */
833 static void set_filebuf_watermark(int seconds
, size_t max
)
838 return; /* Audio buffers not yet set up */
840 bytes
= seconds
?MAX(curtrack_id3
.bitrate
* seconds
* (1000/8), max
):max
;
841 bytes
= MIN(bytes
, filebuflen
/ 2);
842 buf_set_watermark(bytes
);
845 const char *get_codec_filename(int cod_spec
)
849 #ifdef HAVE_RECORDING
850 /* Can choose decoder or encoder if one available */
851 int type
= cod_spec
& CODEC_TYPE_MASK
;
852 int afmt
= cod_spec
& CODEC_AFMT_MASK
;
854 if ((unsigned)afmt
>= AFMT_NUM_CODECS
)
855 type
= AFMT_UNKNOWN
| (type
& CODEC_TYPE_MASK
);
857 fname
= (type
== CODEC_TYPE_ENCODER
) ?
858 audio_formats
[afmt
].codec_enc_root_fn
:
859 audio_formats
[afmt
].codec_root_fn
;
862 (type
== CODEC_TYPE_ENCODER
) ? "Encoder" : "Decoder",
863 afmt
, fname
? fname
: "<unknown>");
864 #else /* !HAVE_RECORDING */
866 if ((unsigned)cod_spec
>= AFMT_NUM_CODECS
)
867 cod_spec
= AFMT_UNKNOWN
;
868 fname
= audio_formats
[cod_spec
].codec_root_fn
;
869 logf("Codec: %d - %s", cod_spec
, fname
? fname
: "<unknown>");
870 #endif /* HAVE_RECORDING */
873 } /* get_codec_filename */
875 /* --- Codec thread --- */
876 static bool codec_pcmbuf_insert_callback(
877 const void *ch1
, const void *ch2
, int count
)
879 const char *src
[2] = { ch1
, ch2
};
883 int out_count
= dsp_output_count(ci
.dsp
, count
);
887 /* Prevent audio from a previous track from playing */
888 if (ci
.new_track
|| ci
.stop_codec
)
891 while ((dest
= pcmbuf_request_buffer(&out_count
)) == NULL
)
895 if (ci
.seek_time
|| ci
.new_track
|| ci
.stop_codec
)
899 /* Get the real input_size for output_size bytes, guarding
900 * against resampling buffer overflows. */
901 inp_count
= dsp_input_count(ci
.dsp
, out_count
);
906 /* Input size has grown, no error, just don't write more than length */
907 if (inp_count
> count
)
910 out_count
= dsp_process(ci
.dsp
, dest
, src
, inp_count
);
915 pcmbuf_write_complete(out_count
);
921 } /* codec_pcmbuf_insert_callback */
923 static void* codec_get_memory_callback(size_t *size
)
925 *size
= MALLOC_BUFSIZE
;
929 /* Between the codec and PCM track change, we need to keep updating the
930 "elapsed" value of the previous (to the codec, but current to the
931 user/PCM/WPS) track, so that the progressbar reaches the end.
932 During that transition, the WPS will display prevtrack_id3. */
933 static void codec_pcmbuf_position_callback(size_t size
) ICODE_ATTR
;
934 static void codec_pcmbuf_position_callback(size_t size
)
936 /* This is called from an ISR, so be quick */
937 unsigned int time
= size
* 1000 / 4 / NATIVE_FREQUENCY
+
938 prevtrack_id3
.elapsed
;
940 if (time
>= prevtrack_id3
.length
)
942 pcmbuf_set_position_callback(NULL
);
943 prevtrack_id3
.elapsed
= prevtrack_id3
.length
;
946 prevtrack_id3
.elapsed
= time
;
949 static void codec_set_elapsed_callback(unsigned int value
)
951 unsigned int latency
;
955 #ifdef AB_REPEAT_ENABLE
956 ab_position_report(value
);
959 latency
= pcmbuf_get_latency();
961 curtrack_id3
.elapsed
= 0;
962 else if (value
- latency
> curtrack_id3
.elapsed
||
963 value
- latency
< curtrack_id3
.elapsed
- 2)
965 curtrack_id3
.elapsed
= value
- latency
;
969 static void codec_set_offset_callback(size_t value
)
971 unsigned int latency
;
976 latency
= pcmbuf_get_latency() * curtrack_id3
.bitrate
/ 8;
978 curtrack_id3
.offset
= 0;
980 curtrack_id3
.offset
= value
- latency
;
983 static void codec_advance_buffer_counters(size_t amount
)
985 bufadvance(CUR_TI
->audio_hid
, amount
);
989 /* copy up-to size bytes into ptr and return the actual size copied */
990 static size_t codec_filebuf_callback(void *ptr
, size_t size
)
994 if (ci
.stop_codec
|| !playing
)
997 copy_n
= bufread(CUR_TI
->audio_hid
, size
, ptr
);
999 /* Nothing requested OR nothing left */
1003 /* Update read and other position pointers */
1004 codec_advance_buffer_counters(copy_n
);
1006 /* Return the actual amount of data copied to the buffer */
1008 } /* codec_filebuf_callback */
1010 static void* codec_request_buffer_callback(size_t *realsize
, size_t reqsize
)
1012 size_t copy_n
= reqsize
;
1022 ret
= bufgetdata(CUR_TI
->audio_hid
, reqsize
, &ptr
);
1024 copy_n
= MIN((size_t)ret
, reqsize
);
1035 } /* codec_request_buffer_callback */
1037 static int get_codec_base_type(int type
)
1049 static void codec_advance_buffer_callback(size_t amount
)
1051 codec_advance_buffer_counters(amount
);
1052 codec_set_offset_callback(ci
.curpos
);
1055 static void codec_advance_buffer_loc_callback(void *ptr
)
1057 size_t amount
= buf_get_offset(CUR_TI
->audio_hid
, ptr
);
1058 codec_advance_buffer_callback(amount
);
1061 static void codec_seek_complete_callback(void)
1063 logf("seek_complete");
1064 if (pcm_is_paused())
1066 /* If this is not a seamless seek, clear the buffer */
1068 dsp_configure(ci
.dsp
, DSP_FLUSH
, 0);
1070 /* If playback was not 'deliberately' paused, unpause now */
1072 pcmbuf_pause(false);
1077 static bool codec_seek_buffer_callback(size_t newpos
)
1079 logf("codec_seek_buffer_callback");
1081 int ret
= bufseek(CUR_TI
->audio_hid
, newpos
);
1091 static void codec_configure_callback(int setting
, intptr_t value
)
1094 case CODEC_SET_FILEBUF_WATERMARK
:
1095 set_filebuf_watermark(buffer_margin
, value
);
1099 if (!dsp_configure(ci
.dsp
, setting
, value
))
1100 { logf("Illegal key:%d", setting
); }
1104 static void codec_track_changed(void)
1106 LOGFQUEUE("codec > audio Q_AUDIO_TRACK_CHANGED");
1107 queue_post(&audio_queue
, Q_AUDIO_TRACK_CHANGED
, 0);
1110 static void codec_pcmbuf_track_changed_callback(void)
1112 pcmbuf_set_position_callback(NULL
);
1113 pcmbuf_callback_queue_post(Q_AUDIO_TRACK_CHANGED
, 0);
1116 static void codec_discard_codec_callback(void)
1118 if (CUR_TI
->codec_hid
>= 0)
1120 bufclose(CUR_TI
->codec_hid
);
1121 CUR_TI
->codec_hid
= -1;
1125 static inline void codec_gapless_track_change(void)
1127 /* callback keeps the progress bar moving while the pcmbuf empties */
1128 pcmbuf_set_position_callback(codec_pcmbuf_position_callback
);
1129 /* set the pcmbuf callback for when the track really changes */
1130 pcmbuf_set_event_handler(codec_pcmbuf_track_changed_callback
);
1133 static inline void codec_crossfade_track_change(void)
1135 /* Initiate automatic crossfade mode */
1136 pcmbuf_crossfade_init(false);
1137 /* Notify the wps that the track change starts now */
1138 codec_track_changed();
1141 static void codec_track_skip_done(bool was_manual
)
1143 /* Manual track change (always crossfade or flush audio). */
1146 pcmbuf_crossfade_init(true);
1147 LOGFQUEUE("codec > audio Q_AUDIO_TRACK_CHANGED");
1148 queue_post(&audio_queue
, Q_AUDIO_TRACK_CHANGED
, 0);
1150 /* Automatic track change w/crossfade, if not in "Track Skip Only" mode. */
1151 else if (pcmbuf_is_crossfade_enabled() && !pcmbuf_is_crossfade_active()
1152 && global_settings
.crossfade
!= CROSSFADE_ENABLE_TRACKSKIP
)
1154 if (global_settings
.crossfade
== CROSSFADE_ENABLE_SHUFFLE_AND_TRACKSKIP
)
1156 if (global_settings
.playlist_shuffle
)
1157 /* shuffle mode is on, so crossfade: */
1158 codec_crossfade_track_change();
1160 /* shuffle mode is off, so do a gapless track change */
1161 codec_gapless_track_change();
1164 /* normal crossfade: */
1165 codec_crossfade_track_change();
1168 /* normal gapless playback. */
1169 codec_gapless_track_change();
1172 static bool codec_load_next_track(void)
1174 intptr_t result
= Q_CODEC_REQUEST_FAILED
;
1176 prev_track_elapsed
= curtrack_id3
.elapsed
;
1178 #ifdef AB_REPEAT_ENABLE
1179 ab_end_of_track_report();
1182 logf("Request new track");
1184 if (ci
.new_track
== 0)
1187 automatic_skip
= true;
1192 trigger_cpu_boost();
1193 LOGFQUEUE("codec >| audio Q_AUDIO_CHECK_NEW_TRACK");
1194 result
= queue_send(&audio_queue
, Q_AUDIO_CHECK_NEW_TRACK
, 0);
1199 case Q_CODEC_REQUEST_COMPLETE
:
1200 LOGFQUEUE("codec |< Q_CODEC_REQUEST_COMPLETE");
1201 codec_track_skip_done(!automatic_skip
);
1204 case Q_CODEC_REQUEST_FAILED
:
1205 LOGFQUEUE("codec |< Q_CODEC_REQUEST_FAILED");
1207 ci
.stop_codec
= true;
1208 codec_requested_stop
= true;
1212 LOGFQUEUE("codec |< default");
1213 ci
.stop_codec
= true;
1214 codec_requested_stop
= true;
1219 static bool codec_request_next_track_callback(void)
1223 if (ci
.stop_codec
|| !playing
)
1226 prev_codectype
= get_codec_base_type(curtrack_id3
.codectype
);
1228 if (!codec_load_next_track())
1231 /* Seek to the beginning of the new track because if the struct
1232 mp3entry was buffered, "elapsed" might not be zero (if the track has
1233 been played already but not unbuffered) */
1234 codec_seek_buffer_callback(curtrack_id3
.first_frame_offset
);
1236 /* Check if the next codec is the same file. */
1237 if (prev_codectype
== get_codec_base_type(curtrack_id3
.codectype
))
1239 logf("New track loaded");
1240 codec_discard_codec_callback();
1245 logf("New codec:%d/%d", curtrack_id3
.codectype
, prev_codectype
);
1250 static void codec_thread(void)
1252 struct queue_event ev
;
1258 if (!pcmbuf_is_crossfade_active()) {
1262 queue_wait(&codec_queue
, &ev
);
1263 codec_requested_stop
= false;
1266 case Q_CODEC_LOAD_DISK
:
1267 LOGFQUEUE("codec < Q_CODEC_LOAD_DISK");
1268 queue_reply(&codec_queue
, 1);
1269 audio_codec_loaded
= true;
1270 ci
.stop_codec
= false;
1271 status
= codec_load_file((const char *)ev
.data
, &ci
);
1275 LOGFQUEUE("codec < Q_CODEC_LOAD");
1276 if (CUR_TI
->codec_hid
< 0) {
1277 logf("Codec slot is empty!");
1278 /* Wait for the pcm buffer to go empty */
1279 while (pcm_is_playing())
1281 /* This must be set to prevent an infinite loop */
1282 ci
.stop_codec
= true;
1283 LOGFQUEUE("codec > codec Q_AUDIO_PLAY");
1284 queue_post(&codec_queue
, Q_AUDIO_PLAY
, 0);
1288 audio_codec_loaded
= true;
1289 ci
.stop_codec
= false;
1290 status
= codec_load_buf(CUR_TI
->codec_hid
, &ci
);
1293 #ifdef AUDIO_HAVE_RECORDING
1294 case Q_ENCODER_LOAD_DISK
:
1295 LOGFQUEUE("codec < Q_ENCODER_LOAD_DISK");
1296 audio_codec_loaded
= false; /* Not audio codec! */
1297 logf("loading encoder");
1298 ci
.stop_encoder
= false;
1299 status
= codec_load_file((const char *)ev
.data
, &ci
);
1300 logf("encoder stopped");
1302 #endif /* AUDIO_HAVE_RECORDING */
1305 LOGFQUEUE("codec < default");
1308 if (audio_codec_loaded
)
1317 audio_codec_loaded
= false;
1321 case Q_CODEC_LOAD_DISK
:
1323 LOGFQUEUE("codec < Q_CODEC_LOAD");
1326 if (ci
.new_track
|| status
!= CODEC_OK
)
1330 logf("Codec failure");
1331 gui_syncsplash(HZ
*2, "Codec failure");
1334 if (!codec_load_next_track())
1336 LOGFQUEUE("codec > audio Q_AUDIO_STOP");
1337 /* End of playlist */
1338 queue_post(&audio_queue
, Q_AUDIO_STOP
, 0);
1344 logf("Codec finished");
1347 /* Wait for the audio to stop playing before
1348 * triggering the WPS exit */
1349 while(pcm_is_playing())
1351 curtrack_id3
.elapsed
=
1352 curtrack_id3
.length
- pcmbuf_get_latency();
1356 if (codec_requested_stop
)
1358 LOGFQUEUE("codec > audio Q_AUDIO_STOP");
1359 queue_post(&audio_queue
, Q_AUDIO_STOP
, 0);
1365 if (CUR_TI
->codec_hid
>= 0)
1367 LOGFQUEUE("codec > codec Q_CODEC_LOAD");
1368 queue_post(&codec_queue
, Q_CODEC_LOAD
, 0);
1372 const char *codec_fn
=
1373 get_codec_filename(curtrack_id3
.codectype
);
1376 LOGFQUEUE("codec > codec Q_CODEC_LOAD_DISK");
1377 queue_post(&codec_queue
, Q_CODEC_LOAD_DISK
,
1378 (intptr_t)codec_fn
);
1384 #ifdef AUDIO_HAVE_RECORDING
1385 case Q_ENCODER_LOAD_DISK
:
1386 LOGFQUEUE("codec < Q_ENCODER_LOAD_DISK");
1388 if (status
== CODEC_OK
)
1391 logf("Encoder failure");
1392 gui_syncsplash(HZ
*2, "Encoder failure");
1394 if (ci
.enc_codec_loaded
< 0)
1397 logf("Encoder failed to load");
1398 ci
.enc_codec_loaded
= -1;
1400 #endif /* AUDIO_HAVE_RECORDING */
1403 LOGFQUEUE("codec < default");
1410 /* --- Buffering callbacks --- */
1412 static void buffering_low_buffer_callback(void *data
)
1415 logf("low buffer callback");
1417 if (filling
== STATE_FULL
|| filling
== STATE_END_OF_PLAYLIST
) {
1418 /* force a refill */
1419 LOGFQUEUE("buffering > audio Q_AUDIO_FILL_BUFFER");
1420 queue_post(&audio_queue
, Q_AUDIO_FILL_BUFFER
, 0);
1424 static void buffering_handle_rebuffer_callback(void *data
)
1427 LOGFQUEUE("audio >| audio Q_AUDIO_FLUSH");
1428 queue_post(&audio_queue
, Q_AUDIO_FLUSH
, 0);
1431 static void buffering_handle_finished_callback(int *data
)
1433 logf("handle %d finished buffering", *data
);
1435 if (*data
== tracks
[track_widx
].id3_hid
)
1437 /* The metadata handle for the last loaded track has been buffered.
1438 We can ask the audio thread to load the rest of the track's data. */
1439 LOGFQUEUE("audio >| audio Q_AUDIO_FINISH_LOAD");
1440 queue_post(&audio_queue
, Q_AUDIO_FINISH_LOAD
, 0);
1444 /* This is most likely an audio handle, so we strip the useless
1445 trailing tags that are left. */
1448 if (*data
== tracks
[track_widx
-1].audio_hid
1449 && filling
== STATE_END_OF_PLAYLIST
)
1451 /* This was the last track in the playlist.
1452 We now have all the data we need. */
1453 logf("last track finished buffering");
1454 filling
= STATE_FINISHED
;
1460 /* --- Audio thread --- */
1462 static bool audio_have_tracks(void)
1464 return (audio_track_count() != 0);
1467 static int audio_free_track_count(void)
1469 /* Used tracks + free tracks adds up to MAX_TRACK - 1 */
1470 return MAX_TRACK
- 1 - audio_track_count();
1473 int audio_track_count(void)
1475 /* Calculate difference from track_ridx to track_widx
1476 * taking into account a possible wrap-around. */
1477 return (MAX_TRACK
+ track_widx
- track_ridx
) & MAX_TRACK_MASK
;
1480 long audio_filebufused(void)
1482 return (long) buf_used();
1485 /* Update track info after successful a codec track change */
1486 static void audio_update_trackinfo(void)
1488 /* Load the curent track's metadata into curtrack_id3 */
1489 if (CUR_TI
->id3_hid
>= 0)
1490 copy_mp3entry(&curtrack_id3
, bufgetid3(CUR_TI
->id3_hid
));
1492 /* Reset current position */
1493 curtrack_id3
.elapsed
= 0;
1494 curtrack_id3
.offset
= 0;
1496 /* Update the codec API */
1497 ci
.filesize
= CUR_TI
->filesize
;
1498 ci
.id3
= &curtrack_id3
;
1500 ci
.taginfo_ready
= &CUR_TI
->taginfo_ready
;
1503 /* Clear tracks between write and read, non inclusive */
1504 static void audio_clear_track_entries(void)
1506 int cur_idx
= track_widx
;
1508 logf("Clearing tracks:%d/%d", track_ridx
, track_widx
);
1510 /* Loop over all tracks from write-to-read */
1513 cur_idx
= (cur_idx
+ 1) & MAX_TRACK_MASK
;
1515 if (cur_idx
== track_ridx
)
1518 clear_track_info(&tracks
[cur_idx
]);
1522 /* Clear all tracks */
1523 static bool audio_release_tracks(void)
1527 logf("releasing all tracks");
1529 for(i
= 0; i
< MAX_TRACK
; i
++)
1531 cur_idx
= (track_ridx
+ i
) & MAX_TRACK_MASK
;
1532 if (!clear_track_info(&tracks
[cur_idx
]))
1539 static bool audio_loadcodec(bool start_play
)
1542 char codec_path
[MAX_PATH
]; /* Full path to codec */
1543 const struct mp3entry
*id3
, *prev_id3
;
1545 if (tracks
[track_widx
].id3_hid
< 0) {
1549 id3
= bufgetid3(tracks
[track_widx
].id3_hid
);
1553 const char *codec_fn
= get_codec_filename(id3
->codectype
);
1554 if (codec_fn
== NULL
)
1557 tracks
[track_widx
].codec_hid
= -1;
1561 /* Load the codec directly from disk and save some memory. */
1562 track_ridx
= track_widx
;
1563 ci
.filesize
= CUR_TI
->filesize
;
1564 ci
.id3
= &curtrack_id3
;
1565 ci
.taginfo_ready
= &CUR_TI
->taginfo_ready
;
1567 LOGFQUEUE("codec > codec Q_CODEC_LOAD_DISK");
1568 queue_post(&codec_queue
, Q_CODEC_LOAD_DISK
, (intptr_t)codec_fn
);
1573 /* If we already have another track than this one buffered */
1574 if (track_widx
!= track_ridx
)
1576 prev_track
= (track_widx
- 1) & MAX_TRACK_MASK
;
1578 id3
= bufgetid3(tracks
[track_widx
].id3_hid
);
1579 prev_id3
= bufgetid3(tracks
[prev_track
].id3_hid
);
1581 /* If the previous codec is the same as this one, there is no need
1582 * to put another copy of it on the file buffer */
1583 if (id3
&& prev_id3
&&
1584 get_codec_base_type(id3
->codectype
) ==
1585 get_codec_base_type(prev_id3
->codectype
)
1586 && audio_codec_loaded
)
1588 logf("Reusing prev. codec");
1594 codec_get_full_path(codec_path
, codec_fn
);
1596 tracks
[track_widx
].codec_hid
= bufopen(codec_path
, 0, TYPE_CODEC
);
1597 if (tracks
[track_widx
].codec_hid
< 0)
1600 logf("Loaded codec");
1605 /* Load metadata for the next track (with bufopen). The rest of the track
1606 loading will be handled by audio_finish_load_track once the metadata has been
1607 actually loaded by the buffering thread. */
1608 static bool audio_load_track(size_t offset
, bool start_play
)
1610 const char *trackname
;
1613 start_play_g
= start_play
; /* will be read by audio_finish_load_track */
1615 /* Stop buffer filling if there is no free track entries.
1616 Don't fill up the last track entry (we wan't to store next track
1618 if (!audio_free_track_count())
1620 logf("No free tracks");
1625 tracks
[track_widx
].taginfo_ready
= false;
1627 logf("Buffering track:%d/%d", track_widx
, track_ridx
);
1628 /* Get track name from current playlist read position. */
1629 while ((trackname
= playlist_peek(last_peek_offset
)) != NULL
)
1631 /* Handle broken playlists. */
1632 fd
= open(trackname
, O_RDONLY
);
1635 logf("Open failed");
1636 /* Skip invalid entry from playlist. */
1637 playlist_skip_entry(NULL
, last_peek_offset
);
1645 logf("End-of-playlist");
1646 memset(&lasttrack_id3
, 0, sizeof(struct mp3entry
));
1647 filling
= STATE_END_OF_PLAYLIST
;
1651 tracks
[track_widx
].filesize
= filesize(fd
);
1653 if (offset
> tracks
[track_widx
].filesize
)
1656 /* Set default values */
1659 buf_set_watermark(AUDIO_DEFAULT_WATERMARK
);
1660 dsp_configure(ci
.dsp
, DSP_RESET
, 0);
1661 track_changed
= true;
1662 playlist_update_resume_info(audio_current_track());
1665 /* Get track metadata if we don't already have it. */
1666 if (tracks
[track_widx
].id3_hid
< 0)
1668 tracks
[track_widx
].id3_hid
= bufopen(trackname
, 0, TYPE_ID3
);
1670 if (tracks
[track_widx
].id3_hid
< 0)
1672 /* Buffer is full. */
1673 get_metadata(&lasttrack_id3
, fd
, trackname
);
1676 logf("buffer is full for now");
1677 filling
= STATE_FULL
;
1681 if (track_widx
== track_ridx
)
1683 buf_request_buffer_handle(tracks
[track_widx
].id3_hid
);
1684 copy_mp3entry(&curtrack_id3
, bufgetid3(tracks
[track_widx
].id3_hid
));
1685 curtrack_id3
.offset
= offset
;
1690 track_changed
= true;
1691 playlist_update_resume_info(audio_current_track());
1699 /* Second part of the track loading: We now have the metadata available, so we
1700 can load the codec, the album art and finally the audio data.
1701 This is called on the audio thread after the buffering thread calls the
1702 buffering_handle_finished_callback callback. */
1703 static void audio_finish_load_track(void)
1706 size_t file_offset
= 0;
1708 bool start_play
= start_play_g
;
1711 if (cuesheet_is_enabled() && tracks
[track_widx
].id3
.cuesheet_type
== 1)
1713 char cuepath
[MAX_PATH
];
1715 struct cuesheet
*cue
= start_play
? curr_cue
: temp_cue
;
1717 if (look_for_cuesheet_file(trackname
, cuepath
) &&
1718 parse_cuesheet(cuepath
, cue
))
1720 strcpy((cue
)->audio_filename
, trackname
);
1722 cue_spoof_id3(curr_cue
, &tracks
[track_widx
].id3
);
1727 if (tracks
[track_widx
].id3_hid
< 0) {
1728 logf("no metatdata");
1732 struct mp3entry
*track_id3
;
1734 if (track_widx
== track_ridx
)
1735 track_id3
= &curtrack_id3
;
1737 track_id3
= bufgetid3(tracks
[track_widx
].id3_hid
);
1739 if (track_id3
->length
== 0 && track_id3
->filesize
== 0)
1741 logf("audio_finish_load_track: invalid metadata");
1743 /* Invalid metadata */
1744 bufclose(tracks
[track_widx
].id3_hid
);
1745 tracks
[track_widx
].id3_hid
= -1;
1747 /* Skip invalid entry from playlist. */
1748 playlist_skip_entry(NULL
, last_peek_offset
--);
1750 /* load next track */
1751 LOGFQUEUE("audio > audio Q_AUDIO_FILL_BUFFER %d", (int)start_play
);
1752 queue_post(&audio_queue
, Q_AUDIO_FILL_BUFFER
, start_play
);
1757 #ifdef HAVE_ALBUMART
1758 if (tracks
[track_widx
].aa_hid
< 0 && gui_sync_wps_uses_albumart())
1760 char aa_path
[MAX_PATH
];
1761 if (find_albumart(track_id3
, aa_path
, sizeof(aa_path
)))
1762 tracks
[track_widx
].aa_hid
= bufopen(aa_path
, 0, TYPE_BITMAP
);
1766 /* Load the codec. */
1767 if (!audio_loadcodec(start_play
))
1769 if (tracks
[track_widx
].codec_hid
== ERR_BUFFER_FULL
)
1771 /* No space for codec on buffer, not an error */
1775 /* This is an error condition, either no codec was found, or reading
1776 * the codec file failed part way through, either way, skip the track */
1777 snprintf(msgbuf
, sizeof(msgbuf
)-1, "No codec for: %s", track_id3
->path
);
1778 /* We should not use gui_syncplash from audio thread! */
1779 gui_syncsplash(HZ
*2, msgbuf
);
1780 /* Skip invalid entry from playlist. */
1781 playlist_skip_entry(NULL
, last_peek_offset
);
1785 track_id3
->elapsed
= 0;
1786 offset
= track_id3
->offset
;
1788 enum data_type type
= TYPE_PACKET_AUDIO
;
1790 switch (track_id3
->codectype
) {
1795 file_offset
= offset
;
1796 track_id3
->offset
= offset
;
1802 file_offset
= offset
;
1803 track_id3
->offset
= offset
;
1804 track_id3
->elapsed
= track_id3
->length
/ 2;
1808 case AFMT_OGG_VORBIS
:
1818 track_id3
->offset
= offset
;
1824 logf("Loading atomic %d",track_id3
->codectype
);
1825 type
= TYPE_ATOMIC_AUDIO
;
1829 logf("alt:%s", track_id3
->path
);
1831 if (file_offset
> AUDIO_REBUFFER_GUESS_SIZE
)
1832 file_offset
-= AUDIO_REBUFFER_GUESS_SIZE
;
1833 else if (track_id3
->first_frame_offset
)
1834 file_offset
= track_id3
->first_frame_offset
;
1838 tracks
[track_widx
].audio_hid
= bufopen(track_id3
->path
, file_offset
, type
);
1840 if (tracks
[track_widx
].audio_hid
< 0)
1843 /* All required data is now available for the codec. */
1844 tracks
[track_widx
].taginfo_ready
= true;
1848 ci
.curpos
=file_offset
;
1849 buf_request_buffer_handle(tracks
[track_widx
].audio_hid
);
1852 track_widx
= (track_widx
+ 1) & MAX_TRACK_MASK
;
1854 send_event(PLAYBACK_EVENT_TRACK_BUFFER
, track_id3
);
1856 /* load next track */
1857 LOGFQUEUE("audio > audio Q_AUDIO_FILL_BUFFER");
1858 queue_post(&audio_queue
, Q_AUDIO_FILL_BUFFER
, 0);
1863 static void audio_fill_file_buffer(bool start_play
, size_t offset
)
1865 bool had_next_track
= audio_next_track() != NULL
;
1867 filling
= STATE_FILLING
;
1868 trigger_cpu_boost();
1870 /* No need to rebuffer if there are track skips pending. */
1871 if (ci
.new_track
!= 0)
1874 /* Must reset the buffer before use if trashed or voice only - voice
1875 file size shouldn't have changed so we can go straight from
1876 BUFFER_STATE_VOICED_ONLY to BUFFER_STATE_INITIALIZED */
1877 if (buffer_state
!= BUFFER_STATE_INITIALIZED
)
1878 audio_reset_buffer();
1880 logf("Starting buffer fill");
1883 audio_clear_track_entries();
1885 /* Save the current resume position once. */
1886 playlist_update_resume_info(audio_current_track());
1888 audio_load_track(offset
, start_play
);
1890 if (!had_next_track
&& audio_next_track())
1891 track_changed
= true;
1894 static void audio_rebuffer(void)
1896 logf("Forcing rebuffer");
1898 clear_track_info(CUR_TI
);
1900 /* Reset track pointers */
1901 track_widx
= track_ridx
;
1902 audio_clear_track_entries();
1904 /* Fill the buffer */
1905 last_peek_offset
= -1;
1908 if (!CUR_TI
->taginfo_ready
)
1909 memset(&curtrack_id3
, 0, sizeof(struct mp3entry
));
1911 audio_fill_file_buffer(false, 0);
1914 /* Called on request from the codec to get a new track. This is the codec part
1915 of the track transition. */
1916 static int audio_check_new_track(void)
1918 int track_count
= audio_track_count();
1919 int old_track_ridx
= track_ridx
;
1923 /* Now it's good time to send track finish events. */
1924 send_event(PLAYBACK_EVENT_TRACK_FINISH
, &curtrack_id3
);
1928 if (playlist_next_dir(ci
.new_track
))
1936 LOGFQUEUE("audio >|= codec Q_CODEC_REQUEST_FAILED");
1937 return Q_CODEC_REQUEST_FAILED
;
1944 /* If the playlist isn't that big */
1947 while (!playlist_check(ci
.new_track
))
1949 if (ci
.new_track
>= 0)
1951 LOGFQUEUE("audio >|= codec Q_CODEC_REQUEST_FAILED");
1952 return Q_CODEC_REQUEST_FAILED
;
1958 /* Update the playlist */
1959 last_peek_offset
-= ci
.new_track
;
1961 if (playlist_next(ci
.new_track
) < 0)
1963 LOGFQUEUE("audio >|= codec Q_CODEC_REQUEST_FAILED");
1964 return Q_CODEC_REQUEST_FAILED
;
1970 new_playlist
= false;
1973 /* Save the track metadata to allow the WPS to display it
1974 while PCM finishes playing that track */
1975 copy_mp3entry(&prevtrack_id3
, &curtrack_id3
);
1977 /* Update the main buffer copy of the track metadata with the one
1978 the codec has been using (for the unbuffer callbacks) */
1979 if (CUR_TI
->id3_hid
>= 0)
1980 copy_mp3entry(bufgetid3(CUR_TI
->id3_hid
), &curtrack_id3
);
1982 /* Save a pointer to the old track to allow later clearing */
1985 for (i
= 0; i
< ci
.new_track
; i
++)
1987 idx
= (track_ridx
+ i
) & MAX_TRACK_MASK
;
1988 struct mp3entry
*id3
= bufgetid3(tracks
[idx
].id3_hid
);
1989 ssize_t offset
= buf_handle_offset(tracks
[idx
].audio_hid
);
1990 if (!id3
|| offset
< 0 || (unsigned)offset
> id3
->first_frame_offset
)
1992 /* We don't have all the audio data for that track, so clear it,
1993 but keep the metadata. */
1994 if (tracks
[idx
].audio_hid
>= 0 && bufclose(tracks
[idx
].audio_hid
))
1996 tracks
[idx
].audio_hid
= -1;
1997 tracks
[idx
].filesize
= 0;
2002 /* Move to the new track */
2003 track_ridx
= (track_ridx
+ ci
.new_track
) & MAX_TRACK_MASK
;
2005 buf_set_base_handle(CUR_TI
->audio_hid
);
2009 wps_offset
= -ci
.new_track
;
2010 track_changed
= true;
2013 /* If it is not safe to even skip this many track entries */
2014 if (ci
.new_track
>= track_count
|| ci
.new_track
<= track_count
- MAX_TRACK
)
2021 forward
= ci
.new_track
> 0;
2024 /* If the target track is clearly not in memory */
2025 if (CUR_TI
->filesize
== 0 || !CUR_TI
->taginfo_ready
)
2031 /* When skipping backwards, it is possible that we've found a track that's
2032 * buffered, but which is around the track-wrap and therefore not the track
2033 * we are looking for */
2036 int cur_idx
= track_ridx
;
2037 bool taginfo_ready
= true;
2038 /* We've wrapped the buffer backwards if new > old */
2039 bool wrap
= track_ridx
> old_track_ridx
;
2043 cur_idx
= (cur_idx
+ 1) & MAX_TRACK_MASK
;
2045 /* if we've advanced past the wrap when cur_idx is zeroed */
2049 /* if we aren't still on the wrap and we've caught the old track */
2050 if (!(wrap
|| cur_idx
< old_track_ridx
))
2053 /* If we hit a track in between without valid tag info, bail */
2054 if (!tracks
[cur_idx
].taginfo_ready
)
2056 taginfo_ready
= false;
2067 audio_update_trackinfo();
2068 LOGFQUEUE("audio >|= codec Q_CODEC_REQUEST_COMPLETE");
2069 return Q_CODEC_REQUEST_COMPLETE
;
2072 unsigned long audio_prev_elapsed(void)
2074 return prev_track_elapsed
;
2077 static void audio_stop_codec_flush(void)
2079 ci
.stop_codec
= true;
2082 while (audio_codec_loaded
)
2085 /* If the audio codec is not loaded any more, and the audio is still
2086 * playing, it is now and _only_ now safe to call this function from the
2088 if (pcm_is_playing())
2091 pcmbuf_queue_clear();
2093 pcmbuf_pause(paused
);
2096 static void audio_stop_playback(void)
2098 /* If we were playing, save resume information */
2101 struct mp3entry
*id3
= NULL
;
2105 /* Set this early, the outside code yields and may allow the codec
2106 to try to wait for a reply on a buffer wait */
2107 ci
.stop_codec
= true;
2108 id3
= audio_current_track();
2111 /* Save the current playing spot, or NULL if the playlist has ended */
2112 playlist_update_resume_info(id3
);
2114 /* TODO: Create auto bookmark too? */
2116 prev_track_elapsed
= curtrack_id3
.elapsed
;
2118 remove_event(EVENT_BUFFER_LOW
, buffering_low_buffer_callback
);
2122 audio_stop_codec_flush();
2125 filling
= STATE_IDLE
;
2127 /* Mark all entries null. */
2128 audio_clear_track_entries();
2130 /* Close all tracks */
2131 audio_release_tracks();
2133 memset(&curtrack_id3
, 0, sizeof(struct mp3entry
));
2136 static void audio_play_start(size_t offset
)
2140 #if INPUT_SRC_CAPS != 0
2141 audio_set_input_source(AUDIO_SRC_PLAYBACK
, SRCF_PLAYBACK
);
2142 audio_set_output_source(AUDIO_SRC_PLAYBACK
);
2145 /* Wait for any previously playing audio to flush - TODO: Not necessary? */
2147 audio_stop_codec_flush();
2149 track_changed
= true;
2157 sound_set_volume(global_settings
.volume
);
2158 track_widx
= track_ridx
= 0;
2160 /* Clear all track entries. */
2161 for (i
= 0; i
< MAX_TRACK
; i
++) {
2162 clear_track_info(&tracks
[i
]);
2165 last_peek_offset
= -1;
2167 /* Officially playing */
2168 queue_reply(&audio_queue
, 1);
2170 #ifndef HAVE_FLASH_STORAGE
2171 set_filebuf_watermark(buffer_margin
, 0);
2174 audio_fill_file_buffer(true, offset
);
2176 add_event(EVENT_BUFFER_LOW
, false, buffering_low_buffer_callback
);
2178 LOGFQUEUE("audio > audio Q_AUDIO_TRACK_CHANGED");
2179 queue_post(&audio_queue
, Q_AUDIO_TRACK_CHANGED
, 0);
2183 /* Invalidates all but currently playing track. */
2184 static void audio_invalidate_tracks(void)
2186 if (audio_have_tracks())
2188 last_peek_offset
= 0;
2189 track_widx
= track_ridx
;
2191 /* Mark all other entries null (also buffered wrong metadata). */
2192 audio_clear_track_entries();
2194 track_widx
= (track_widx
+ 1) & MAX_TRACK_MASK
;
2196 audio_fill_file_buffer(false, 0);
2200 static void audio_new_playlist(void)
2202 /* Prepare to start a new fill from the beginning of the playlist */
2203 last_peek_offset
= -1;
2204 if (audio_have_tracks())
2207 skipped_during_pause
= true;
2208 track_widx
= track_ridx
;
2209 audio_clear_track_entries();
2211 track_widx
= (track_widx
+ 1) & MAX_TRACK_MASK
;
2213 /* Mark the current track as invalid to prevent skipping back to it */
2214 CUR_TI
->taginfo_ready
= false;
2217 /* Signal the codec to initiate a track change forward */
2218 new_playlist
= true;
2221 /* Officially playing */
2222 queue_reply(&audio_queue
, 1);
2224 audio_fill_file_buffer(false, 0);
2227 /* Called on manual track skip */
2228 static void audio_initiate_track_change(long direction
)
2230 logf("audio_initiate_track_change(%ld)", direction
);
2232 ci
.new_track
+= direction
;
2233 wps_offset
-= direction
;
2235 skipped_during_pause
= true;
2238 /* Called on manual dir skip */
2239 static void audio_initiate_dir_change(long direction
)
2242 ci
.new_track
= direction
;
2244 skipped_during_pause
= true;
2247 /* Called when PCM track change is complete */
2248 static void audio_finalise_track_change(void)
2250 logf("audio_finalise_track_change");
2255 automatic_skip
= false;
2257 /* Invalidate prevtrack_id3 */
2258 prevtrack_id3
.path
[0] = 0;
2260 if (prev_ti
&& prev_ti
->audio_hid
< 0)
2262 /* No audio left so we clear all the track info. */
2263 clear_track_info(prev_ti
);
2266 if (prev_ti
&& prev_ti
->id3_hid
>= 0)
2268 /* Reset the elapsed time to force the progressbar to be empty if
2269 the user skips back to this track */
2270 bufgetid3(prev_ti
->id3_hid
)->elapsed
= 0;
2274 send_event(PLAYBACK_EVENT_TRACK_CHANGE
, &curtrack_id3
);
2276 track_changed
= true;
2277 playlist_update_resume_info(audio_current_track());
2281 * Layout audio buffer as follows - iram buffer depends on target:
2282 * [|SWAP:iram][|TALK]|MALLOC|FILE|GUARD|PCM|[SWAP:dram[|iram]|]
2284 static void audio_reset_buffer(void)
2286 /* see audio_get_recording_buffer if this is modified */
2287 logf("audio_reset_buffer");
2289 /* If the setup of anything allocated before the file buffer is
2290 changed, do check the adjustments after the buffer_alloc call
2291 as it will likely be affected and need sliding over */
2293 /* Initially set up file buffer as all space available */
2294 malloc_buf
= audiobuf
+ talk_get_bufsize();
2295 /* Align the malloc buf to line size. Especially important to cf
2296 targets that do line reads/writes. */
2297 malloc_buf
= (unsigned char *)(((uintptr_t)malloc_buf
+ 15) & ~15);
2298 filebuf
= malloc_buf
+ MALLOC_BUFSIZE
; /* filebuf line align implied */
2299 filebuflen
= audiobufend
- filebuf
;
2303 /* Subtract whatever the pcm buffer says it used plus the guard buffer */
2304 filebuflen
-= pcmbuf_init(filebuf
+ filebuflen
) + GUARD_BUFSIZE
;
2306 /* Make sure filebuflen is a longword multiple after adjustment - filebuf
2307 will already be line aligned */
2310 buffering_reset(filebuf
, filebuflen
);
2312 /* Clear any references to the file buffer */
2313 buffer_state
= BUFFER_STATE_INITIALIZED
;
2315 #if defined(ROCKBOX_HAS_LOGF) && defined(LOGF_ENABLE)
2316 /* Make sure everything adds up - yes, some info is a bit redundant but
2317 aids viewing and the sumation of certain variables should add up to
2318 the location of others. */
2321 const unsigned char *pcmbuf
= pcmbuf_get_meminfo(&pcmbufsize
);
2322 logf("mabuf: %08X", (unsigned)malloc_buf
);
2323 logf("mabufe: %08X", (unsigned)(malloc_buf
+ MALLOC_BUFSIZE
));
2324 logf("fbuf: %08X", (unsigned)filebuf
);
2325 logf("fbufe: %08X", (unsigned)(filebuf
+ filebuflen
));
2326 logf("gbuf: %08X", (unsigned)(filebuf
+ filebuflen
));
2327 logf("gbufe: %08X", (unsigned)(filebuf
+ filebuflen
+ GUARD_BUFSIZE
));
2328 logf("pcmb: %08X", (unsigned)pcmbuf
);
2329 logf("pcmbe: %08X", (unsigned)(pcmbuf
+ pcmbufsize
));
2334 static void audio_thread(void)
2336 struct queue_event ev
;
2340 audio_thread_ready
= true;
2344 if (filling
!= STATE_FILLING
) {
2348 if (!pcmbuf_queue_scan(&ev
))
2349 queue_wait_w_tmo(&audio_queue
, &ev
, HZ
/2);
2353 case Q_AUDIO_FILL_BUFFER
:
2354 LOGFQUEUE("audio < Q_AUDIO_FILL_BUFFER %d", (int)ev
.data
);
2355 audio_fill_file_buffer((bool)ev
.data
, 0);
2358 case Q_AUDIO_FINISH_LOAD
:
2359 LOGFQUEUE("audio < Q_AUDIO_FINISH_LOAD");
2360 audio_finish_load_track();
2364 LOGFQUEUE("audio < Q_AUDIO_PLAY");
2365 if (playing
&& ev
.data
<= 0)
2366 audio_new_playlist();
2369 audio_stop_playback();
2370 audio_play_start((size_t)ev
.data
);
2375 LOGFQUEUE("audio < Q_AUDIO_STOP");
2377 audio_stop_playback();
2379 queue_clear(&audio_queue
);
2383 LOGFQUEUE("audio < Q_AUDIO_PAUSE");
2384 if (!(bool) ev
.data
&& skipped_during_pause
&& !pcmbuf_is_crossfade_active())
2385 pcmbuf_play_stop(); /* Flush old track on resume after skip */
2386 skipped_during_pause
= false;
2389 pcmbuf_pause((bool)ev
.data
);
2390 paused
= (bool)ev
.data
;
2394 LOGFQUEUE("audio < Q_AUDIO_SKIP");
2395 audio_initiate_track_change((long)ev
.data
);
2398 case Q_AUDIO_PRE_FF_REWIND
:
2399 LOGFQUEUE("audio < Q_AUDIO_PRE_FF_REWIND");
2405 case Q_AUDIO_FF_REWIND
:
2406 LOGFQUEUE("audio < Q_AUDIO_FF_REWIND");
2411 /* An automatic track skip is in progress. Finalize it,
2412 then go back to the previous track */
2413 audio_finalise_track_change();
2416 ci
.seek_time
= (long)ev
.data
+1;
2419 case Q_AUDIO_CHECK_NEW_TRACK
:
2420 LOGFQUEUE("audio < Q_AUDIO_CHECK_NEW_TRACK");
2421 queue_reply(&audio_queue
, audio_check_new_track());
2424 case Q_AUDIO_DIR_SKIP
:
2425 LOGFQUEUE("audio < Q_AUDIO_DIR_SKIP");
2426 audio_initiate_dir_change(ev
.data
);
2430 LOGFQUEUE("audio < Q_AUDIO_FLUSH");
2431 audio_invalidate_tracks();
2434 case Q_AUDIO_TRACK_CHANGED
:
2435 /* PCM track change done */
2436 LOGFQUEUE("audio < Q_AUDIO_TRACK_CHANGED");
2437 audio_finalise_track_change();
2441 case SYS_USB_CONNECTED
:
2442 LOGFQUEUE("audio < SYS_USB_CONNECTED");
2444 audio_stop_playback();
2445 #ifdef PLAYBACK_VOICE
2448 usb_acknowledge(SYS_USB_CONNECTED_ACK
);
2449 usb_wait_for_disconnect(&audio_queue
);
2451 /* Mark all entries null. */
2452 audio_clear_track_entries();
2454 /* release tracks to make sure all handles are closed */
2455 audio_release_tracks();
2460 LOGFQUEUE_SYS_TIMEOUT("audio < SYS_TIMEOUT");
2464 LOGFQUEUE("audio < default");
2470 /* Initialize the audio system - called from init() in main.c.
2471 * Last function because of all the references to internal symbols
2473 void audio_init(void)
2475 struct thread_entry
*audio_thread_p
;
2477 /* Can never do this twice */
2478 if (audio_is_initialized
)
2480 logf("audio: already initialized");
2484 logf("audio: initializing");
2486 /* Initialize queues before giving control elsewhere in case it likes
2487 to send messages. Thread creation will be delayed however so nothing
2488 starts running until ready if something yields such as talk_init. */
2489 queue_init(&audio_queue
, true);
2490 queue_init(&codec_queue
, false);
2491 queue_init(&pcmbuf_queue
, false);
2495 /* Initialize codec api. */
2496 ci
.read_filebuf
= codec_filebuf_callback
;
2497 ci
.pcmbuf_insert
= codec_pcmbuf_insert_callback
;
2498 ci
.get_codec_memory
= codec_get_memory_callback
;
2499 ci
.request_buffer
= codec_request_buffer_callback
;
2500 ci
.advance_buffer
= codec_advance_buffer_callback
;
2501 ci
.advance_buffer_loc
= codec_advance_buffer_loc_callback
;
2502 ci
.request_next_track
= codec_request_next_track_callback
;
2503 ci
.seek_buffer
= codec_seek_buffer_callback
;
2504 ci
.seek_complete
= codec_seek_complete_callback
;
2505 ci
.set_elapsed
= codec_set_elapsed_callback
;
2506 ci
.set_offset
= codec_set_offset_callback
;
2507 ci
.configure
= codec_configure_callback
;
2508 ci
.discard_codec
= codec_discard_codec_callback
;
2509 ci
.dsp
= (struct dsp_config
*)dsp_configure(NULL
, DSP_MYDSP
,
2512 /* initialize the buffer */
2515 /* audio_reset_buffer must to know the size of voice buffer so init
2519 codec_thread_p
= create_thread(
2520 codec_thread
, codec_stack
, sizeof(codec_stack
),
2521 CREATE_THREAD_FROZEN
,
2522 codec_thread_name
IF_PRIO(, PRIORITY_PLAYBACK
)
2525 queue_enable_queue_send(&codec_queue
, &codec_queue_sender_list
,
2528 audio_thread_p
= create_thread(audio_thread
, audio_stack
,
2529 sizeof(audio_stack
), CREATE_THREAD_FROZEN
,
2530 audio_thread_name
IF_PRIO(, PRIORITY_USER_INTERFACE
)
2533 queue_enable_queue_send(&audio_queue
, &audio_queue_sender_list
,
2536 #ifdef PLAYBACK_VOICE
2537 voice_thread_init();
2540 /* Set crossfade setting for next buffer init which should be about... */
2541 pcmbuf_crossfade_enable(global_settings
.crossfade
);
2543 /* initialize the buffering system */
2546 /* ...now! Set up the buffers */
2547 audio_reset_buffer();
2550 for(i
= 0; i
< MAX_TRACK
; i
++)
2552 tracks
[i
].audio_hid
= -1;
2553 tracks
[i
].id3_hid
= -1;
2554 tracks
[i
].codec_hid
= -1;
2555 #ifdef HAVE_ALBUMART
2556 tracks
[i
].aa_hid
= -1;
2560 add_event(EVENT_HANDLE_REBUFFER
, false, buffering_handle_rebuffer_callback
);
2561 add_event(EVENT_HANDLE_FINISHED
, false, buffering_handle_finished_callback
);
2563 /* Probably safe to say */
2564 audio_is_initialized
= true;
2566 sound_settings_apply();
2567 #ifndef HAVE_FLASH_STORAGE
2568 audio_set_buffer_margin(global_settings
.buffer_margin
);
2571 /* it's safe to let the threads run now */
2572 #ifdef PLAYBACK_VOICE
2573 voice_thread_resume();
2575 thread_thaw(codec_thread_p
);
2576 thread_thaw(audio_thread_p
);
2580 void audio_wait_for_init(void)
2582 /* audio thread will only set this once after it finished the final
2583 * audio hardware init so this little construct is safe - even
2585 while (!audio_thread_ready
)