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 #define PLAYBACK_VOICE
87 /* default point to start buffer refill */
88 #define AUDIO_DEFAULT_WATERMARK (1024*512)
89 /* amount of guess-space to allow for codecs that must hunt and peck
90 * for their correct seeek target, 32k seems a good size */
91 #define AUDIO_REBUFFER_GUESS_SIZE (1024*32)
93 /* Define LOGF_ENABLE to enable logf output in this file */
94 /*#define LOGF_ENABLE*/
97 /* macros to enable logf for queues
98 logging on SYS_TIMEOUT can be disabled */
100 /* Define this for logf output of all queuing except SYS_TIMEOUT */
101 #define PLAYBACK_LOGQUEUES
102 /* Define this to logf SYS_TIMEOUT messages */
103 /*#define PLAYBACK_LOGQUEUES_SYS_TIMEOUT*/
106 #ifdef PLAYBACK_LOGQUEUES
107 #define LOGFQUEUE logf
109 #define LOGFQUEUE(...)
112 #ifdef PLAYBACK_LOGQUEUES_SYS_TIMEOUT
113 #define LOGFQUEUE_SYS_TIMEOUT logf
115 #define LOGFQUEUE_SYS_TIMEOUT(...)
119 /* Define one constant that includes recording related functionality */
120 #if defined(HAVE_RECORDING) && !defined(SIMULATOR)
121 #define AUDIO_HAVE_RECORDING
130 Q_AUDIO_PRE_FF_REWIND
,
132 Q_AUDIO_CHECK_NEW_TRACK
,
134 Q_AUDIO_TRACK_CHANGED
,
139 Q_CODEC_REQUEST_COMPLETE
,
140 Q_CODEC_REQUEST_FAILED
,
145 #ifdef AUDIO_HAVE_RECORDING
152 STATE_IDLE
, /* audio is stopped: nothing to do */
153 STATE_FILLING
, /* adding tracks to the buffer */
154 STATE_FULL
, /* can't add any more tracks */
155 STATE_END_OF_PLAYLIST
, /* all remaining tracks have been added */
156 STATE_FINISHED
, /* all remaining tracks are fully buffered */
160 #define MAX_TRACK 128
165 #define MAX_TRACK_MASK (MAX_TRACK-1)
167 /* As defined in plugins/lib/xxx2wav.h */
169 #define GUARD_BUFSIZE (32*1024)
171 #define GUARD_BUFSIZE (8*1024)
174 /* As defined in plugin.lds */
176 #define CODEC_IRAM_ORIGIN ((unsigned char *)0x4000c000)
177 #define CODEC_IRAM_SIZE ((size_t)0xc000)
178 #elif defined(IAUDIO_X5) || defined(IAUDIO_M5)
179 #define CODEC_IRAM_ORIGIN ((unsigned char *)0x10010000)
180 #define CODEC_IRAM_SIZE ((size_t)0x10000)
182 #define CODEC_IRAM_ORIGIN ((unsigned char *)0x1000c000)
183 #define CODEC_IRAM_SIZE ((size_t)0xc000)
186 bool audio_is_initialized
= false;
187 static bool audio_thread_ready SHAREDBSS_ATTR
= false;
189 /* Variables are commented with the threads that use them: *
190 * A=audio, C=codec, V=voice. A suffix of - indicates that *
191 * the variable is read but not updated on that thread. */
192 /* TBD: Split out "audio" and "playback" (ie. calling) threads */
194 /* Main state control */
195 static volatile bool audio_codec_loaded SHAREDBSS_ATTR
= false; /* Codec loaded? (C/A-) */
196 static volatile bool playing SHAREDBSS_ATTR
= false; /* Is audio playing? (A) */
197 static volatile bool paused SHAREDBSS_ATTR
= false; /* Is audio paused? (A/C-) */
199 /* Ring buffer where compressed audio and codecs are loaded */
200 static unsigned char *filebuf
= NULL
; /* Start of buffer (A/C-) */
201 static unsigned char *malloc_buf
= NULL
; /* Start of malloc buffer (A/C-) */
202 /* FIXME: make filebuflen static */
203 size_t filebuflen
= 0; /* Size of buffer (A/C-) */
204 /* FIXME: make buf_ridx (C/A-) */
206 /* Possible arrangements of the buffer */
207 static int buffer_state
= AUDIOBUF_STATE_TRASHED
; /* Buffer state */
209 /* Used to keep the WPS up-to-date during track transtition */
210 static struct mp3entry prevtrack_id3
;
212 /* Used to provide the codec with a pointer */
213 static struct mp3entry curtrack_id3
;
215 /* Used to make next track info available while playing last track on buffer */
216 static struct mp3entry lasttrack_id3
;
218 /* Track info structure about songs in the file buffer (A/C-) */
220 int audio_hid
; /* The ID for the track's buffer handle */
221 int id3_hid
; /* The ID for the track's metadata handle */
222 int codec_hid
; /* The ID for the track's codec handle */
224 int aa_hid
; /* The ID for the track's album art handle */
227 size_t filesize
; /* File total length */
229 bool taginfo_ready
; /* Is metadata read */
232 static struct track_info tracks
[MAX_TRACK
];
233 static volatile int track_ridx
= 0; /* Track being decoded (A/C-) */
234 static int track_widx
= 0; /* Track being buffered (A) */
236 #define CUR_TI (&tracks[track_ridx]) /* Playing track info pointer (A/C-) */
237 static struct track_info
*prev_ti
= NULL
; /* Pointer to the previously played
240 /* Set by the audio thread when the current track information has updated
241 * and the WPS may need to update its cached information */
242 static bool track_changed
= false;
244 /* Information used only for filling the buffer */
245 /* Playlist steps from playing track to next track to be buffered (A) */
246 static int last_peek_offset
= 0;
248 /* Scrobbler support */
249 static unsigned long prev_track_elapsed
= 0; /* Previous track elapsed time (C/A-)*/
251 static enum filling_state filling
;
253 /* Track change controls */
254 static bool automatic_skip
= false; /* Who initiated in-progress skip? (C/A-) */
255 static bool dir_skip
= false; /* Is a directory skip pending? (A) */
256 static bool new_playlist
= false; /* Are we starting a new playlist? (A) */
257 static int wps_offset
= 0; /* Pending track change offset, to keep WPS responsive (A) */
258 static bool skipped_during_pause
= false; /* Do we need to clear the PCM buffer when playback resumes (A) */
260 static bool start_play_g
= false; /* Used by audio_load_track to notify
261 audio_finish_load_track about start_play */
263 /* True when a track load is in progress, i.e. audio_load_track() has returned
264 * but audio_finish_load_track() hasn't been called yet. Used to avoid allowing
265 * audio_load_track() to get called twice in a row, which would cause problems.
267 static bool track_load_started
= false;
269 /* Set to true if the codec thread should send an audio stop request
270 * (typically because the end of the playlist has been reached).
272 static bool codec_requested_stop
= false;
274 static size_t buffer_margin
= 0; /* Buffer margin aka anti-skip buffer (A/C-) */
276 /* Multiple threads */
277 /* Set the watermark to trigger buffer fill (A/C) FIXME */
278 static void set_filebuf_watermark(int seconds
, size_t max
);
281 static struct event_queue audio_queue SHAREDBSS_ATTR
;
282 static struct queue_sender_list audio_queue_sender_list SHAREDBSS_ATTR
;
283 static long audio_stack
[(DEFAULT_STACK_SIZE
+ 0x1000)/sizeof(long)];
284 static const char audio_thread_name
[] = "audio";
286 static void audio_thread(void);
287 static void audio_initiate_track_change(long direction
);
288 static bool audio_have_tracks(void);
289 static void audio_reset_buffer(void);
290 static void audio_stop_playback(void);
293 extern struct codec_api ci
;
294 static struct event_queue codec_queue SHAREDBSS_ATTR
;
295 static struct queue_sender_list codec_queue_sender_list
;
296 static long codec_stack
[(DEFAULT_STACK_SIZE
+ 0x2000)/sizeof(long)]
298 static const char codec_thread_name
[] = "codec";
299 unsigned int codec_thread_id
; /* For modifying thread priority later. */
301 /* PCM buffer messaging */
302 static struct event_queue pcmbuf_queue SHAREDBSS_ATTR
;
304 /* Function to be called by pcm buffer callbacks.
305 * Permissible Context(s): Audio interrupt
307 static void pcmbuf_callback_queue_post(long id
, intptr_t data
)
309 /* No lock since we're already in audio interrupt context */
310 queue_post(&pcmbuf_queue
, id
, data
);
313 /* Scan the pcmbuf queue and return true if a message pulled.
314 * Permissible Context(s): Thread
316 static bool pcmbuf_queue_scan(struct queue_event
*ev
)
318 if (!queue_empty(&pcmbuf_queue
))
320 /* Transfer message to audio queue */
322 /* Pull message - never, ever any blocking call! */
323 queue_wait_w_tmo(&pcmbuf_queue
, ev
, 0);
331 /* Clear the pcmbuf queue of messages
332 * Permissible Context(s): Thread
334 static void pcmbuf_queue_clear(void)
337 queue_clear(&pcmbuf_queue
);
341 /* --- Helper functions --- */
343 static struct mp3entry
*bufgetid3(int handle_id
)
348 struct mp3entry
*id3
;
349 ssize_t ret
= bufgetdata(handle_id
, 0, (void *)&id3
);
351 if (ret
< 0 || ret
!= sizeof(struct mp3entry
))
357 static bool clear_track_info(struct track_info
*track
)
359 /* bufclose returns true if the handle is not found, or if it is closed
360 * successfully, so these checks are safe on non-existant handles */
364 if (track
->codec_hid
>= 0) {
365 if (bufclose(track
->codec_hid
))
366 track
->codec_hid
= -1;
371 if (track
->id3_hid
>= 0) {
372 if (bufclose(track
->id3_hid
))
378 if (track
->audio_hid
>= 0) {
379 if (bufclose(track
->audio_hid
))
380 track
->audio_hid
= -1;
386 if (track
->aa_hid
>= 0) {
387 if (bufclose(track
->aa_hid
))
395 track
->taginfo_ready
= false;
400 /* --- External interfaces --- */
402 /* This sends a stop message and the audio thread will dump all it's
403 subsequenct messages */
404 void audio_hard_stop(void)
407 LOGFQUEUE("audio >| audio Q_AUDIO_STOP: 1");
408 queue_send(&audio_queue
, Q_AUDIO_STOP
, 1);
409 #ifdef PLAYBACK_VOICE
414 bool audio_restore_playback(int type
)
418 case AUDIO_WANT_PLAYBACK
:
419 if (buffer_state
!= AUDIOBUF_STATE_INITIALIZED
)
420 audio_reset_buffer();
422 case AUDIO_WANT_VOICE
:
423 if (buffer_state
== AUDIOBUF_STATE_TRASHED
)
424 audio_reset_buffer();
431 unsigned char *audio_get_buffer(bool talk_buf
, size_t *buffer_size
)
433 unsigned char *buf
, *end
;
435 if (audio_is_initialized
)
439 /* else buffer_state will be AUDIOBUF_STATE_TRASHED at this point */
441 if (buffer_size
== NULL
)
443 /* Special case for talk_init to use since it already knows it's
445 buffer_state
= AUDIOBUF_STATE_TRASHED
;
449 if (talk_buf
|| buffer_state
== AUDIOBUF_STATE_TRASHED
450 || !talk_voice_required())
452 logf("get buffer: talk, audio");
453 /* Ok to use everything from audiobuf to audiobufend - voice is loaded,
454 the talk buffer is not needed because voice isn't being used, or
455 could be AUDIOBUF_STATE_TRASHED already. If state is
456 AUDIOBUF_STATE_VOICED_ONLY, no problem as long as memory isn't written
457 without the caller knowing what's going on. Changing certain settings
458 may move it to a worse condition but the memory in use by something
459 else will remain undisturbed.
461 if (buffer_state
!= AUDIOBUF_STATE_TRASHED
)
464 buffer_state
= AUDIOBUF_STATE_TRASHED
;
472 /* Safe to just return this if already AUDIOBUF_STATE_VOICED_ONLY or
473 still AUDIOBUF_STATE_INITIALIZED */
474 /* Skip talk buffer and move pcm buffer to end to maximize available
475 contiguous memory - no audio running means voice will not need the
477 logf("get buffer: audio");
478 buf
= audiobuf
+ talk_get_bufsize();
479 end
= audiobufend
- pcmbuf_init(audiobufend
);
480 buffer_state
= AUDIOBUF_STATE_VOICED_ONLY
;
483 *buffer_size
= end
- buf
;
488 int audio_buffer_state(void)
493 #ifdef HAVE_RECORDING
494 unsigned char *audio_get_recording_buffer(size_t *buffer_size
)
496 /* Stop audio, voice and obtain all available buffer space */
500 unsigned char *end
= audiobufend
;
501 buffer_state
= AUDIOBUF_STATE_TRASHED
;
502 *buffer_size
= end
- audiobuf
;
504 return (unsigned char *)audiobuf
;
507 bool audio_load_encoder(int afmt
)
510 const char *enc_fn
= get_codec_filename(afmt
| CODEC_TYPE_ENCODER
);
514 audio_remove_encoder();
515 ci
.enc_codec_loaded
= 0; /* clear any previous error condition */
517 LOGFQUEUE("codec > Q_ENCODER_LOAD_DISK");
518 queue_post(&codec_queue
, Q_ENCODER_LOAD_DISK
, (intptr_t)enc_fn
);
520 while (ci
.enc_codec_loaded
== 0)
523 logf("codec loaded: %d", ci
.enc_codec_loaded
);
525 return ci
.enc_codec_loaded
> 0;
530 } /* audio_load_encoder */
532 void audio_remove_encoder(void)
535 /* force encoder codec unload (if currently loaded) */
536 if (ci
.enc_codec_loaded
<= 0)
539 ci
.stop_encoder
= true;
540 while (ci
.enc_codec_loaded
> 0)
543 } /* audio_remove_encoder */
545 #endif /* HAVE_RECORDING */
548 int audio_current_aa_hid(void)
551 int offset
= ci
.new_track
+ wps_offset
;
553 cur_idx
= track_ridx
+ offset
;
554 cur_idx
&= MAX_TRACK_MASK
;
556 return tracks
[cur_idx
].aa_hid
;
560 struct mp3entry
* audio_current_track(void)
562 const char *filename
;
563 static struct mp3entry temp_id3
;
564 struct playlist_track_info trackinfo
;
566 int offset
= ci
.new_track
+ wps_offset
;
568 cur_idx
= (track_ridx
+ offset
) & MAX_TRACK_MASK
;
570 if (cur_idx
== track_ridx
&& *curtrack_id3
.path
)
573 return &curtrack_id3
;
575 else if (automatic_skip
&& offset
== -1 && *prevtrack_id3
.path
)
577 /* We're in a track transition. The codec has moved on to the nex track,
578 but the audio being played is still the same (now previous) track.
579 prevtrack_id3.elapsed is being updated in an ISR by
580 codec_pcmbuf_position_callback */
581 return &prevtrack_id3
;
583 else if (tracks
[cur_idx
].id3_hid
>= 0)
585 /* Get the ID3 metadata from the main buffer */
586 struct mp3entry
*ret
= bufgetid3(tracks
[cur_idx
].id3_hid
);
590 /* We didn't find the ID3 metadata, so we fill temp_id3 with the little info
591 we have and return that. */
593 memset(&temp_id3
, 0, sizeof(struct mp3entry
));
595 playlist_get_track_info(NULL
, playlist_next(0)+wps_offset
, &trackinfo
);
596 filename
= trackinfo
.filename
;
598 filename
= "No file!";
600 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
601 if (tagcache_fill_tags(&temp_id3
, filename
))
605 strncpy(temp_id3
.path
, filename
, sizeof(temp_id3
.path
)-1);
606 temp_id3
.title
= strrchr(temp_id3
.path
, '/');
608 temp_id3
.title
= &temp_id3
.path
[0];
615 struct mp3entry
* audio_next_track(void)
618 int offset
= ci
.new_track
+ wps_offset
;
620 if (!audio_have_tracks())
623 if (wps_offset
== -1 && *prevtrack_id3
.path
)
625 /* We're in a track transition. The next track for the WPS is the one
626 currently being decoded. */
627 return &curtrack_id3
;
630 next_idx
= (track_ridx
+ offset
+ 1) & MAX_TRACK_MASK
;
632 if (tracks
[next_idx
].id3_hid
>= 0)
633 return bufgetid3(tracks
[next_idx
].id3_hid
);
635 if (next_idx
== track_widx
)
637 /* The next track hasn't been buffered yet, so we return the static
638 version of its metadata. */
639 return &lasttrack_id3
;
645 bool audio_has_changed_track(void)
649 track_changed
= false;
656 void audio_play(long offset
)
660 #ifdef PLAYBACK_VOICE
661 /* Truncate any existing voice output so we don't have spelling
662 * etc. over the first part of the played track */
667 LOGFQUEUE("audio >| audio Q_AUDIO_PLAY: %ld", offset
);
668 /* Don't return until playback has actually started */
669 queue_send(&audio_queue
, Q_AUDIO_PLAY
, offset
);
672 void audio_stop(void)
675 LOGFQUEUE("audio >| audio Q_AUDIO_STOP");
676 /* Don't return until playback has actually stopped */
677 queue_send(&audio_queue
, Q_AUDIO_STOP
, 0);
680 void audio_pause(void)
682 LOGFQUEUE("audio >| audio Q_AUDIO_PAUSE");
683 /* Don't return until playback has actually paused */
684 queue_send(&audio_queue
, Q_AUDIO_PAUSE
, true);
687 void audio_resume(void)
689 LOGFQUEUE("audio >| audio Q_AUDIO_PAUSE resume");
690 /* Don't return until playback has actually resumed */
691 queue_send(&audio_queue
, Q_AUDIO_PAUSE
, false);
694 static void audio_skip(int direction
)
696 if (playlist_check(ci
.new_track
+ wps_offset
+ direction
))
698 if (global_settings
.beep
)
699 pcmbuf_beep(2000, 100, 2500*global_settings
.beep
);
701 LOGFQUEUE("audio > audio Q_AUDIO_SKIP %d", direction
);
702 queue_post(&audio_queue
, Q_AUDIO_SKIP
, direction
);
703 /* Update wps while our message travels inside deep playback queues. */
704 wps_offset
+= direction
;
705 track_changed
= true;
709 /* No more tracks. */
710 if (global_settings
.beep
)
711 pcmbuf_beep(1000, 100, 1500*global_settings
.beep
);
715 void audio_next(void)
720 void audio_prev(void)
725 void audio_next_dir(void)
727 LOGFQUEUE("audio > audio Q_AUDIO_DIR_SKIP 1");
728 queue_post(&audio_queue
, Q_AUDIO_DIR_SKIP
, 1);
731 void audio_prev_dir(void)
733 LOGFQUEUE("audio > audio Q_AUDIO_DIR_SKIP -1");
734 queue_post(&audio_queue
, Q_AUDIO_DIR_SKIP
, -1);
737 void audio_pre_ff_rewind(void)
739 LOGFQUEUE("audio > audio Q_AUDIO_PRE_FF_REWIND");
740 queue_post(&audio_queue
, Q_AUDIO_PRE_FF_REWIND
, 0);
743 void audio_ff_rewind(long newpos
)
745 LOGFQUEUE("audio > audio Q_AUDIO_FF_REWIND");
746 queue_post(&audio_queue
, Q_AUDIO_FF_REWIND
, newpos
);
749 void audio_flush_and_reload_tracks(void)
751 LOGFQUEUE("audio > audio Q_AUDIO_FLUSH");
752 queue_post(&audio_queue
, Q_AUDIO_FLUSH
, 0);
755 void audio_error_clear(void)
757 #ifdef AUDIO_HAVE_RECORDING
758 pcm_rec_error_clear();
762 int audio_status(void)
767 ret
|= AUDIO_STATUS_PLAY
;
770 ret
|= AUDIO_STATUS_PAUSE
;
772 #ifdef HAVE_RECORDING
773 /* Do this here for constitency with mpeg.c version */
774 ret
|= pcm_rec_status();
780 int audio_get_file_pos(void)
785 #ifdef HAVE_DISK_STORAGE
786 void audio_set_buffer_margin(int setting
)
788 static const int lookup
[] = {5, 15, 30, 60, 120, 180, 300, 600};
789 buffer_margin
= lookup
[setting
];
790 logf("buffer margin: %ld", (long)buffer_margin
);
791 set_filebuf_watermark(buffer_margin
, 0);
795 /* Take necessary steps to enable or disable the crossfade setting */
796 void audio_set_crossfade(int enable
)
802 /* Tell it the next setting to use */
803 pcmbuf_crossfade_enable(enable
);
805 /* Return if size hasn't changed or this is too early to determine
806 which in the second case there's no way we could be playing
808 if (pcmbuf_is_same_size())
810 /* This function is a copout and just syncs some variables -
811 to be removed at a later date */
812 pcmbuf_crossfade_enable_finished();
817 was_playing
= playing
;
819 /* Playback has to be stopped before changing the buffer size */
822 /* Store the track resume position */
823 offset
= curtrack_id3
.offset
;
826 /* Blast it - audio buffer will have to be setup again next time
828 audio_get_buffer(true, &size
);
830 /* Restart playback if audio was running previously */
835 /* --- Routines called from multiple threads --- */
837 static void set_filebuf_watermark(int seconds
, size_t max
)
842 return; /* Audio buffers not yet set up */
844 bytes
= seconds
?MAX(curtrack_id3
.bitrate
* seconds
* (1000/8), max
):max
;
845 bytes
= MIN(bytes
, filebuflen
/ 2);
846 buf_set_watermark(bytes
);
849 const char *get_codec_filename(int cod_spec
)
853 #ifdef HAVE_RECORDING
854 /* Can choose decoder or encoder if one available */
855 int type
= cod_spec
& CODEC_TYPE_MASK
;
856 int afmt
= cod_spec
& CODEC_AFMT_MASK
;
858 if ((unsigned)afmt
>= AFMT_NUM_CODECS
)
859 type
= AFMT_UNKNOWN
| (type
& CODEC_TYPE_MASK
);
861 fname
= (type
== CODEC_TYPE_ENCODER
) ?
862 audio_formats
[afmt
].codec_enc_root_fn
:
863 audio_formats
[afmt
].codec_root_fn
;
866 (type
== CODEC_TYPE_ENCODER
) ? "Encoder" : "Decoder",
867 afmt
, fname
? fname
: "<unknown>");
868 #else /* !HAVE_RECORDING */
870 if ((unsigned)cod_spec
>= AFMT_NUM_CODECS
)
871 cod_spec
= AFMT_UNKNOWN
;
872 fname
= audio_formats
[cod_spec
].codec_root_fn
;
873 logf("Codec: %d - %s", cod_spec
, fname
? fname
: "<unknown>");
874 #endif /* HAVE_RECORDING */
877 } /* get_codec_filename */
879 /* --- Codec thread --- */
880 static bool codec_pcmbuf_insert_callback(
881 const void *ch1
, const void *ch2
, int count
)
883 const char *src
[2] = { ch1
, ch2
};
887 int out_count
= dsp_output_count(ci
.dsp
, count
);
891 /* Prevent audio from a previous track from playing */
892 if (ci
.new_track
|| ci
.stop_codec
)
895 while ((dest
= pcmbuf_request_buffer(&out_count
)) == NULL
)
899 if (ci
.seek_time
|| ci
.new_track
|| ci
.stop_codec
)
903 /* Get the real input_size for output_size bytes, guarding
904 * against resampling buffer overflows. */
905 inp_count
= dsp_input_count(ci
.dsp
, out_count
);
910 /* Input size has grown, no error, just don't write more than length */
911 if (inp_count
> count
)
914 out_count
= dsp_process(ci
.dsp
, dest
, src
, inp_count
);
919 pcmbuf_write_complete(out_count
);
925 } /* codec_pcmbuf_insert_callback */
927 static void* codec_get_buffer(size_t *size
)
929 if (codec_size
>= CODEC_SIZE
)
931 *size
= CODEC_SIZE
- codec_size
;
932 return &codecbuf
[codec_size
];
935 /* Between the codec and PCM track change, we need to keep updating the
936 "elapsed" value of the previous (to the codec, but current to the
937 user/PCM/WPS) track, so that the progressbar reaches the end.
938 During that transition, the WPS will display prevtrack_id3. */
939 static void codec_pcmbuf_position_callback(size_t size
) ICODE_ATTR
;
940 static void codec_pcmbuf_position_callback(size_t size
)
942 /* This is called from an ISR, so be quick */
943 unsigned int time
= size
* 1000 / 4 / NATIVE_FREQUENCY
+
944 prevtrack_id3
.elapsed
;
946 if (time
>= prevtrack_id3
.length
)
948 pcmbuf_set_position_callback(NULL
);
949 prevtrack_id3
.elapsed
= prevtrack_id3
.length
;
952 prevtrack_id3
.elapsed
= time
;
955 static void codec_set_elapsed_callback(unsigned int value
)
957 unsigned int latency
;
961 #ifdef AB_REPEAT_ENABLE
962 ab_position_report(value
);
965 latency
= pcmbuf_get_latency();
967 curtrack_id3
.elapsed
= 0;
968 else if (value
- latency
> curtrack_id3
.elapsed
||
969 value
- latency
< curtrack_id3
.elapsed
- 2)
971 curtrack_id3
.elapsed
= value
- latency
;
975 static void codec_set_offset_callback(size_t value
)
977 unsigned int latency
;
982 latency
= pcmbuf_get_latency() * curtrack_id3
.bitrate
/ 8;
984 curtrack_id3
.offset
= 0;
986 curtrack_id3
.offset
= value
- latency
;
989 static void codec_advance_buffer_counters(size_t amount
)
991 bufadvance(CUR_TI
->audio_hid
, amount
);
995 /* copy up-to size bytes into ptr and return the actual size copied */
996 static size_t codec_filebuf_callback(void *ptr
, size_t size
)
1000 if (ci
.stop_codec
|| !playing
)
1003 copy_n
= bufread(CUR_TI
->audio_hid
, size
, ptr
);
1005 /* Nothing requested OR nothing left */
1009 /* Update read and other position pointers */
1010 codec_advance_buffer_counters(copy_n
);
1012 /* Return the actual amount of data copied to the buffer */
1014 } /* codec_filebuf_callback */
1016 static void* codec_request_buffer_callback(size_t *realsize
, size_t reqsize
)
1018 size_t copy_n
= reqsize
;
1028 ret
= bufgetdata(CUR_TI
->audio_hid
, reqsize
, &ptr
);
1030 copy_n
= MIN((size_t)ret
, reqsize
);
1041 } /* codec_request_buffer_callback */
1043 static int get_codec_base_type(int type
)
1055 static void codec_advance_buffer_callback(size_t amount
)
1057 codec_advance_buffer_counters(amount
);
1058 codec_set_offset_callback(ci
.curpos
);
1061 static void codec_advance_buffer_loc_callback(void *ptr
)
1063 size_t amount
= buf_get_offset(CUR_TI
->audio_hid
, ptr
);
1064 codec_advance_buffer_callback(amount
);
1067 static void codec_seek_complete_callback(void)
1069 logf("seek_complete");
1070 if (pcm_is_paused())
1072 /* If this is not a seamless seek, clear the buffer */
1074 dsp_configure(ci
.dsp
, DSP_FLUSH
, 0);
1076 /* If playback was not 'deliberately' paused, unpause now */
1078 pcmbuf_pause(false);
1083 static bool codec_seek_buffer_callback(size_t newpos
)
1085 logf("codec_seek_buffer_callback");
1087 int ret
= bufseek(CUR_TI
->audio_hid
, newpos
);
1097 static void codec_configure_callback(int setting
, intptr_t value
)
1100 case CODEC_SET_FILEBUF_WATERMARK
:
1101 set_filebuf_watermark(buffer_margin
, value
);
1105 if (!dsp_configure(ci
.dsp
, setting
, value
))
1106 { logf("Illegal key:%d", setting
); }
1110 static void codec_track_changed(void)
1112 LOGFQUEUE("codec > audio Q_AUDIO_TRACK_CHANGED");
1113 queue_post(&audio_queue
, Q_AUDIO_TRACK_CHANGED
, 0);
1116 static void codec_pcmbuf_track_changed_callback(void)
1118 pcmbuf_set_position_callback(NULL
);
1119 pcmbuf_callback_queue_post(Q_AUDIO_TRACK_CHANGED
, 0);
1122 static void codec_discard_codec_callback(void)
1124 if (CUR_TI
->codec_hid
>= 0)
1126 bufclose(CUR_TI
->codec_hid
);
1127 CUR_TI
->codec_hid
= -1;
1131 static inline void codec_gapless_track_change(void)
1133 /* callback keeps the progress bar moving while the pcmbuf empties */
1134 pcmbuf_set_position_callback(codec_pcmbuf_position_callback
);
1135 /* set the pcmbuf callback for when the track really changes */
1136 pcmbuf_set_event_handler(codec_pcmbuf_track_changed_callback
);
1139 static inline void codec_crossfade_track_change(void)
1141 /* Initiate automatic crossfade mode */
1142 pcmbuf_crossfade_init(false);
1143 /* Notify the wps that the track change starts now */
1144 codec_track_changed();
1147 static void codec_track_skip_done(bool was_manual
)
1149 /* Manual track change (always crossfade or flush audio). */
1152 pcmbuf_crossfade_init(true);
1153 LOGFQUEUE("codec > audio Q_AUDIO_TRACK_CHANGED");
1154 queue_post(&audio_queue
, Q_AUDIO_TRACK_CHANGED
, 0);
1156 /* Automatic track change w/crossfade, if not in "Track Skip Only" mode. */
1157 else if (pcmbuf_is_crossfade_enabled() && !pcmbuf_is_crossfade_active()
1158 && global_settings
.crossfade
!= CROSSFADE_ENABLE_TRACKSKIP
)
1160 if (global_settings
.crossfade
== CROSSFADE_ENABLE_SHUFFLE_AND_TRACKSKIP
)
1162 if (global_settings
.playlist_shuffle
)
1163 /* shuffle mode is on, so crossfade: */
1164 codec_crossfade_track_change();
1166 /* shuffle mode is off, so do a gapless track change */
1167 codec_gapless_track_change();
1170 /* normal crossfade: */
1171 codec_crossfade_track_change();
1174 /* normal gapless playback. */
1175 codec_gapless_track_change();
1178 static bool codec_load_next_track(void)
1180 intptr_t result
= Q_CODEC_REQUEST_FAILED
;
1182 prev_track_elapsed
= curtrack_id3
.elapsed
;
1184 #ifdef AB_REPEAT_ENABLE
1185 ab_end_of_track_report();
1188 logf("Request new track");
1190 if (ci
.new_track
== 0)
1193 automatic_skip
= true;
1198 trigger_cpu_boost();
1199 LOGFQUEUE("codec >| audio Q_AUDIO_CHECK_NEW_TRACK");
1200 result
= queue_send(&audio_queue
, Q_AUDIO_CHECK_NEW_TRACK
, 0);
1205 case Q_CODEC_REQUEST_COMPLETE
:
1206 LOGFQUEUE("codec |< Q_CODEC_REQUEST_COMPLETE");
1207 codec_track_skip_done(!automatic_skip
);
1210 case Q_CODEC_REQUEST_FAILED
:
1211 LOGFQUEUE("codec |< Q_CODEC_REQUEST_FAILED");
1213 ci
.stop_codec
= true;
1214 codec_requested_stop
= true;
1218 LOGFQUEUE("codec |< default");
1219 ci
.stop_codec
= true;
1220 codec_requested_stop
= true;
1225 static bool codec_request_next_track_callback(void)
1229 if (ci
.stop_codec
|| !playing
)
1232 prev_codectype
= get_codec_base_type(curtrack_id3
.codectype
);
1234 if (!codec_load_next_track())
1237 /* Seek to the beginning of the new track because if the struct
1238 mp3entry was buffered, "elapsed" might not be zero (if the track has
1239 been played already but not unbuffered) */
1240 codec_seek_buffer_callback(curtrack_id3
.first_frame_offset
);
1242 /* Check if the next codec is the same file. */
1243 if (prev_codectype
== get_codec_base_type(curtrack_id3
.codectype
))
1245 logf("New track loaded");
1246 codec_discard_codec_callback();
1251 logf("New codec:%d/%d", curtrack_id3
.codectype
, prev_codectype
);
1256 static void codec_thread(void)
1258 struct queue_event ev
;
1264 if (!pcmbuf_is_crossfade_active()) {
1268 queue_wait(&codec_queue
, &ev
);
1269 codec_requested_stop
= false;
1272 case Q_CODEC_LOAD_DISK
:
1273 LOGFQUEUE("codec < Q_CODEC_LOAD_DISK");
1274 queue_reply(&codec_queue
, 1);
1275 audio_codec_loaded
= true;
1276 ci
.stop_codec
= false;
1277 status
= codec_load_file((const char *)ev
.data
, &ci
);
1281 LOGFQUEUE("codec < Q_CODEC_LOAD");
1282 if (CUR_TI
->codec_hid
< 0) {
1283 logf("Codec slot is empty!");
1284 /* Wait for the pcm buffer to go empty */
1285 while (pcm_is_playing())
1287 /* This must be set to prevent an infinite loop */
1288 ci
.stop_codec
= true;
1289 LOGFQUEUE("codec > codec Q_AUDIO_PLAY");
1290 queue_post(&codec_queue
, Q_AUDIO_PLAY
, 0);
1294 audio_codec_loaded
= true;
1295 ci
.stop_codec
= false;
1296 status
= codec_load_buf(CUR_TI
->codec_hid
, &ci
);
1299 #ifdef AUDIO_HAVE_RECORDING
1300 case Q_ENCODER_LOAD_DISK
:
1301 LOGFQUEUE("codec < Q_ENCODER_LOAD_DISK");
1302 audio_codec_loaded
= false; /* Not audio codec! */
1303 logf("loading encoder");
1304 ci
.stop_encoder
= false;
1305 status
= codec_load_file((const char *)ev
.data
, &ci
);
1306 logf("encoder stopped");
1308 #endif /* AUDIO_HAVE_RECORDING */
1311 LOGFQUEUE("codec < default");
1314 if (audio_codec_loaded
)
1323 audio_codec_loaded
= false;
1327 case Q_CODEC_LOAD_DISK
:
1329 LOGFQUEUE("codec < Q_CODEC_LOAD");
1332 if (ci
.new_track
|| status
!= CODEC_OK
)
1336 logf("Codec failure");
1337 splash(HZ
*2, "Codec failure");
1340 if (!codec_load_next_track())
1342 LOGFQUEUE("codec > audio Q_AUDIO_STOP");
1343 /* End of playlist */
1344 queue_post(&audio_queue
, Q_AUDIO_STOP
, 0);
1350 logf("Codec finished");
1353 /* Wait for the audio to stop playing before
1354 * triggering the WPS exit */
1355 while(pcm_is_playing())
1357 curtrack_id3
.elapsed
=
1358 curtrack_id3
.length
- pcmbuf_get_latency();
1362 if (codec_requested_stop
)
1364 LOGFQUEUE("codec > audio Q_AUDIO_STOP");
1365 queue_post(&audio_queue
, Q_AUDIO_STOP
, 0);
1371 if (CUR_TI
->codec_hid
>= 0)
1373 LOGFQUEUE("codec > codec Q_CODEC_LOAD");
1374 queue_post(&codec_queue
, Q_CODEC_LOAD
, 0);
1378 const char *codec_fn
=
1379 get_codec_filename(curtrack_id3
.codectype
);
1382 LOGFQUEUE("codec > codec Q_CODEC_LOAD_DISK");
1383 queue_post(&codec_queue
, Q_CODEC_LOAD_DISK
,
1384 (intptr_t)codec_fn
);
1390 #ifdef AUDIO_HAVE_RECORDING
1391 case Q_ENCODER_LOAD_DISK
:
1392 LOGFQUEUE("codec < Q_ENCODER_LOAD_DISK");
1394 if (status
== CODEC_OK
)
1397 logf("Encoder failure");
1398 splash(HZ
*2, "Encoder failure");
1400 if (ci
.enc_codec_loaded
< 0)
1403 logf("Encoder failed to load");
1404 ci
.enc_codec_loaded
= -1;
1406 #endif /* AUDIO_HAVE_RECORDING */
1409 LOGFQUEUE("codec < default");
1416 /* --- Buffering callbacks --- */
1418 static void buffering_low_buffer_callback(void *data
)
1421 logf("low buffer callback");
1423 if (filling
== STATE_FULL
|| filling
== STATE_END_OF_PLAYLIST
) {
1424 /* force a refill */
1425 LOGFQUEUE("buffering > audio Q_AUDIO_FILL_BUFFER");
1426 queue_post(&audio_queue
, Q_AUDIO_FILL_BUFFER
, 0);
1430 static void buffering_handle_rebuffer_callback(void *data
)
1433 LOGFQUEUE("audio >| audio Q_AUDIO_FLUSH");
1434 queue_post(&audio_queue
, Q_AUDIO_FLUSH
, 0);
1437 static void buffering_handle_finished_callback(int *data
)
1439 logf("handle %d finished buffering", *data
);
1441 if (*data
== tracks
[track_widx
].id3_hid
)
1443 /* The metadata handle for the last loaded track has been buffered.
1444 We can ask the audio thread to load the rest of the track's data. */
1445 LOGFQUEUE("audio >| audio Q_AUDIO_FINISH_LOAD");
1446 queue_post(&audio_queue
, Q_AUDIO_FINISH_LOAD
, 0);
1450 /* This is most likely an audio handle, so we strip the useless
1451 trailing tags that are left. */
1454 if (*data
== tracks
[track_widx
-1].audio_hid
1455 && filling
== STATE_END_OF_PLAYLIST
)
1457 /* This was the last track in the playlist.
1458 We now have all the data we need. */
1459 logf("last track finished buffering");
1460 filling
= STATE_FINISHED
;
1466 /* --- Audio thread --- */
1468 static bool audio_have_tracks(void)
1470 return (audio_track_count() != 0);
1473 static int audio_free_track_count(void)
1475 /* Used tracks + free tracks adds up to MAX_TRACK - 1 */
1476 return MAX_TRACK
- 1 - audio_track_count();
1479 int audio_track_count(void)
1481 /* Calculate difference from track_ridx to track_widx
1482 * taking into account a possible wrap-around. */
1483 return (MAX_TRACK
+ track_widx
- track_ridx
) & MAX_TRACK_MASK
;
1486 long audio_filebufused(void)
1488 return (long) buf_used();
1491 /* Update track info after successful a codec track change */
1492 static void audio_update_trackinfo(void)
1494 /* Load the curent track's metadata into curtrack_id3 */
1495 if (CUR_TI
->id3_hid
>= 0)
1496 copy_mp3entry(&curtrack_id3
, bufgetid3(CUR_TI
->id3_hid
));
1498 /* Reset current position */
1499 curtrack_id3
.elapsed
= 0;
1500 curtrack_id3
.offset
= 0;
1502 /* Update the codec API */
1503 ci
.filesize
= CUR_TI
->filesize
;
1504 ci
.id3
= &curtrack_id3
;
1506 ci
.taginfo_ready
= &CUR_TI
->taginfo_ready
;
1509 /* Clear tracks between write and read, non inclusive */
1510 static void audio_clear_track_entries(void)
1512 int cur_idx
= track_widx
;
1514 logf("Clearing tracks:%d/%d", track_ridx
, track_widx
);
1516 /* Loop over all tracks from write-to-read */
1519 cur_idx
= (cur_idx
+ 1) & MAX_TRACK_MASK
;
1521 if (cur_idx
== track_ridx
)
1524 clear_track_info(&tracks
[cur_idx
]);
1528 /* Clear all tracks */
1529 static bool audio_release_tracks(void)
1533 logf("releasing all tracks");
1535 for(i
= 0; i
< MAX_TRACK
; i
++)
1537 cur_idx
= (track_ridx
+ i
) & MAX_TRACK_MASK
;
1538 if (!clear_track_info(&tracks
[cur_idx
]))
1545 static bool audio_loadcodec(bool start_play
)
1548 char codec_path
[MAX_PATH
]; /* Full path to codec */
1549 const struct mp3entry
*id3
, *prev_id3
;
1551 if (tracks
[track_widx
].id3_hid
< 0) {
1555 id3
= bufgetid3(tracks
[track_widx
].id3_hid
);
1559 const char *codec_fn
= get_codec_filename(id3
->codectype
);
1560 if (codec_fn
== NULL
)
1563 tracks
[track_widx
].codec_hid
= -1;
1567 /* Load the codec directly from disk and save some memory. */
1568 track_ridx
= track_widx
;
1569 ci
.filesize
= CUR_TI
->filesize
;
1570 ci
.id3
= &curtrack_id3
;
1571 ci
.taginfo_ready
= &CUR_TI
->taginfo_ready
;
1573 LOGFQUEUE("codec > codec Q_CODEC_LOAD_DISK");
1574 queue_post(&codec_queue
, Q_CODEC_LOAD_DISK
, (intptr_t)codec_fn
);
1579 /* If we already have another track than this one buffered */
1580 if (track_widx
!= track_ridx
)
1582 prev_track
= (track_widx
- 1) & MAX_TRACK_MASK
;
1584 id3
= bufgetid3(tracks
[track_widx
].id3_hid
);
1585 prev_id3
= bufgetid3(tracks
[prev_track
].id3_hid
);
1587 /* If the previous codec is the same as this one, there is no need
1588 * to put another copy of it on the file buffer */
1589 if (id3
&& prev_id3
&&
1590 get_codec_base_type(id3
->codectype
) ==
1591 get_codec_base_type(prev_id3
->codectype
)
1592 && audio_codec_loaded
)
1594 logf("Reusing prev. codec");
1600 codec_get_full_path(codec_path
, codec_fn
);
1602 tracks
[track_widx
].codec_hid
= bufopen(codec_path
, 0, TYPE_CODEC
);
1603 if (tracks
[track_widx
].codec_hid
< 0)
1606 logf("Loaded codec");
1611 /* Load metadata for the next track (with bufopen). The rest of the track
1612 loading will be handled by audio_finish_load_track once the metadata has been
1613 actually loaded by the buffering thread. */
1614 static bool audio_load_track(size_t offset
, bool start_play
)
1616 const char *trackname
;
1619 if (track_load_started
) {
1620 /* There is already a track load in progress, so track_widx hasn't been
1621 incremented yet. Loading another track would overwrite the one that
1622 hasn't finished loading. */
1623 logf("audio_load_track(): a track load is already in progress");
1627 start_play_g
= start_play
; /* will be read by audio_finish_load_track */
1629 /* Stop buffer filling if there is no free track entries.
1630 Don't fill up the last track entry (we wan't to store next track
1632 if (!audio_free_track_count())
1634 logf("No free tracks");
1639 tracks
[track_widx
].taginfo_ready
= false;
1641 logf("Buffering track:%d/%d", track_widx
, track_ridx
);
1642 /* Get track name from current playlist read position. */
1643 while ((trackname
= playlist_peek(last_peek_offset
)) != NULL
)
1645 /* Handle broken playlists. */
1646 fd
= open(trackname
, O_RDONLY
);
1649 logf("Open failed");
1650 /* Skip invalid entry from playlist. */
1651 playlist_skip_entry(NULL
, last_peek_offset
);
1659 logf("End-of-playlist");
1660 memset(&lasttrack_id3
, 0, sizeof(struct mp3entry
));
1661 filling
= STATE_END_OF_PLAYLIST
;
1663 if (curtrack_id3
.length
== 0 && curtrack_id3
.filesize
== 0)
1665 /* Stop playback if no valid track was found. */
1666 audio_stop_playback();
1672 tracks
[track_widx
].filesize
= filesize(fd
);
1674 if (offset
> tracks
[track_widx
].filesize
)
1677 /* Set default values */
1680 buf_set_watermark(AUDIO_DEFAULT_WATERMARK
);
1681 dsp_configure(ci
.dsp
, DSP_RESET
, 0);
1682 track_changed
= true;
1683 playlist_update_resume_info(audio_current_track());
1686 /* Get track metadata if we don't already have it. */
1687 if (tracks
[track_widx
].id3_hid
< 0)
1689 tracks
[track_widx
].id3_hid
= bufopen(trackname
, 0, TYPE_ID3
);
1691 if (tracks
[track_widx
].id3_hid
< 0)
1693 /* Buffer is full. */
1694 get_metadata(&lasttrack_id3
, fd
, trackname
);
1697 logf("buffer is full for now");
1698 filling
= STATE_FULL
;
1702 if (track_widx
== track_ridx
)
1704 /* TODO: Superfluos buffering call? */
1705 buf_request_buffer_handle(tracks
[track_widx
].id3_hid
);
1706 copy_mp3entry(&curtrack_id3
, bufgetid3(tracks
[track_widx
].id3_hid
));
1707 curtrack_id3
.offset
= offset
;
1712 track_changed
= true;
1713 playlist_update_resume_info(audio_current_track());
1718 track_load_started
= true; /* Remember that we've started loading a track */
1722 /* Second part of the track loading: We now have the metadata available, so we
1723 can load the codec, the album art and finally the audio data.
1724 This is called on the audio thread after the buffering thread calls the
1725 buffering_handle_finished_callback callback. */
1726 static void audio_finish_load_track(void)
1728 size_t file_offset
= 0;
1730 bool start_play
= start_play_g
;
1733 if (cuesheet_is_enabled() && tracks
[track_widx
].id3
.cuesheet_type
== 1)
1735 char cuepath
[MAX_PATH
];
1737 struct cuesheet
*cue
= start_play
? curr_cue
: temp_cue
;
1739 if (look_for_cuesheet_file(trackname
, cuepath
) &&
1740 parse_cuesheet(cuepath
, cue
))
1742 strcpy((cue
)->audio_filename
, trackname
);
1744 cue_spoof_id3(curr_cue
, &tracks
[track_widx
].id3
);
1749 track_load_started
= false;
1751 if (tracks
[track_widx
].id3_hid
< 0) {
1752 logf("no metatdata");
1756 struct mp3entry
*track_id3
;
1758 if (track_widx
== track_ridx
)
1759 track_id3
= &curtrack_id3
;
1761 track_id3
= bufgetid3(tracks
[track_widx
].id3_hid
);
1763 if (track_id3
->length
== 0 && track_id3
->filesize
== 0)
1765 logf("audio_finish_load_track: invalid metadata");
1767 /* Invalid metadata */
1768 bufclose(tracks
[track_widx
].id3_hid
);
1769 tracks
[track_widx
].id3_hid
= -1;
1771 /* Skip invalid entry from playlist. */
1772 playlist_skip_entry(NULL
, last_peek_offset
--);
1774 /* load next track */
1775 LOGFQUEUE("audio > audio Q_AUDIO_FILL_BUFFER %d", (int)start_play
);
1776 queue_post(&audio_queue
, Q_AUDIO_FILL_BUFFER
, start_play
);
1781 #ifdef HAVE_ALBUMART
1782 if (tracks
[track_widx
].aa_hid
< 0 && gui_sync_wps_uses_albumart())
1784 char aa_path
[MAX_PATH
];
1785 if (find_albumart(track_id3
, aa_path
, sizeof(aa_path
)))
1786 tracks
[track_widx
].aa_hid
= bufopen(aa_path
, 0, TYPE_BITMAP
);
1790 /* Load the codec. */
1791 if (!audio_loadcodec(start_play
))
1793 if (tracks
[track_widx
].codec_hid
== ERR_BUFFER_FULL
)
1795 /* No space for codec on buffer, not an error */
1799 /* This is an error condition, either no codec was found, or reading
1800 * the codec file failed part way through, either way, skip the track */
1801 /* FIXME: We should not use splashf from audio thread! */
1802 splashf(HZ
*2, "No codec for: %s", track_id3
->path
);
1803 /* Skip invalid entry from playlist. */
1804 playlist_skip_entry(NULL
, last_peek_offset
);
1808 track_id3
->elapsed
= 0;
1809 offset
= track_id3
->offset
;
1811 enum data_type type
= TYPE_PACKET_AUDIO
;
1813 switch (track_id3
->codectype
) {
1818 file_offset
= offset
;
1819 track_id3
->offset
= offset
;
1825 file_offset
= offset
;
1826 track_id3
->offset
= offset
;
1827 track_id3
->elapsed
= track_id3
->length
/ 2;
1831 case AFMT_OGG_VORBIS
:
1841 track_id3
->offset
= offset
;
1847 logf("Loading atomic %d",track_id3
->codectype
);
1848 type
= TYPE_ATOMIC_AUDIO
;
1852 logf("alt:%s", track_id3
->path
);
1854 if (file_offset
> AUDIO_REBUFFER_GUESS_SIZE
)
1855 file_offset
-= AUDIO_REBUFFER_GUESS_SIZE
;
1856 else if (track_id3
->first_frame_offset
)
1857 file_offset
= track_id3
->first_frame_offset
;
1861 tracks
[track_widx
].audio_hid
= bufopen(track_id3
->path
, file_offset
, type
);
1863 if (tracks
[track_widx
].audio_hid
< 0)
1866 /* All required data is now available for the codec. */
1867 tracks
[track_widx
].taginfo_ready
= true;
1871 ci
.curpos
=file_offset
;
1872 buf_request_buffer_handle(tracks
[track_widx
].audio_hid
);
1875 track_widx
= (track_widx
+ 1) & MAX_TRACK_MASK
;
1877 send_event(PLAYBACK_EVENT_TRACK_BUFFER
, track_id3
);
1879 /* load next track */
1880 LOGFQUEUE("audio > audio Q_AUDIO_FILL_BUFFER");
1881 queue_post(&audio_queue
, Q_AUDIO_FILL_BUFFER
, 0);
1886 static void audio_fill_file_buffer(bool start_play
, size_t offset
)
1888 bool had_next_track
= audio_next_track() != NULL
;
1890 filling
= STATE_FILLING
;
1891 trigger_cpu_boost();
1893 /* No need to rebuffer if there are track skips pending. */
1894 if (ci
.new_track
!= 0)
1897 /* Must reset the buffer before use if trashed or voice only - voice
1898 file size shouldn't have changed so we can go straight from
1899 AUDIOBUF_STATE_VOICED_ONLY to AUDIOBUF_STATE_INITIALIZED */
1900 if (buffer_state
!= AUDIOBUF_STATE_INITIALIZED
)
1901 audio_reset_buffer();
1903 logf("Starting buffer fill");
1906 audio_clear_track_entries();
1908 /* Save the current resume position once. */
1909 playlist_update_resume_info(audio_current_track());
1911 audio_load_track(offset
, start_play
);
1913 if (!had_next_track
&& audio_next_track())
1914 track_changed
= true;
1917 static void audio_rebuffer(void)
1919 logf("Forcing rebuffer");
1921 clear_track_info(CUR_TI
);
1923 /* Reset track pointers */
1924 track_widx
= track_ridx
;
1925 audio_clear_track_entries();
1927 /* Reset a possibly interrupted track load */
1928 track_load_started
= false;
1930 /* Fill the buffer */
1931 last_peek_offset
= -1;
1934 if (!CUR_TI
->taginfo_ready
)
1935 memset(&curtrack_id3
, 0, sizeof(struct mp3entry
));
1937 audio_fill_file_buffer(false, 0);
1940 /* Called on request from the codec to get a new track. This is the codec part
1941 of the track transition. */
1942 static int audio_check_new_track(void)
1944 int track_count
= audio_track_count();
1945 int old_track_ridx
= track_ridx
;
1949 /* Now it's good time to send track finish events. */
1950 send_event(PLAYBACK_EVENT_TRACK_FINISH
, &curtrack_id3
);
1954 /* regardless of the return value we need to rebuffer.
1955 if it fails the old playlist will resume, else the
1956 next dir will start playing */
1957 playlist_next_dir(ci
.new_track
);
1966 /* If the playlist isn't that big */
1969 while (!playlist_check(ci
.new_track
))
1971 if (ci
.new_track
>= 0)
1973 LOGFQUEUE("audio >|= codec Q_CODEC_REQUEST_FAILED");
1974 return Q_CODEC_REQUEST_FAILED
;
1980 /* Update the playlist */
1981 last_peek_offset
-= ci
.new_track
;
1983 if (playlist_next(ci
.new_track
) < 0)
1985 LOGFQUEUE("audio >|= codec Q_CODEC_REQUEST_FAILED");
1986 return Q_CODEC_REQUEST_FAILED
;
1992 new_playlist
= false;
1995 /* Save the track metadata to allow the WPS to display it
1996 while PCM finishes playing that track */
1997 copy_mp3entry(&prevtrack_id3
, &curtrack_id3
);
1999 /* Update the main buffer copy of the track metadata with the one
2000 the codec has been using (for the unbuffer callbacks) */
2001 if (CUR_TI
->id3_hid
>= 0)
2002 copy_mp3entry(bufgetid3(CUR_TI
->id3_hid
), &curtrack_id3
);
2004 /* Save a pointer to the old track to allow later clearing */
2007 for (i
= 0; i
< ci
.new_track
; i
++)
2009 idx
= (track_ridx
+ i
) & MAX_TRACK_MASK
;
2010 struct mp3entry
*id3
= bufgetid3(tracks
[idx
].id3_hid
);
2011 ssize_t offset
= buf_handle_offset(tracks
[idx
].audio_hid
);
2012 if (!id3
|| offset
< 0 || (unsigned)offset
> id3
->first_frame_offset
)
2014 /* We don't have all the audio data for that track, so clear it,
2015 but keep the metadata. */
2016 if (tracks
[idx
].audio_hid
>= 0 && bufclose(tracks
[idx
].audio_hid
))
2018 tracks
[idx
].audio_hid
= -1;
2019 tracks
[idx
].filesize
= 0;
2024 /* Move to the new track */
2025 track_ridx
= (track_ridx
+ ci
.new_track
) & MAX_TRACK_MASK
;
2027 buf_set_base_handle(CUR_TI
->audio_hid
);
2031 wps_offset
= -ci
.new_track
;
2032 track_changed
= true;
2035 /* If it is not safe to even skip this many track entries */
2036 if (ci
.new_track
>= track_count
|| ci
.new_track
<= track_count
- MAX_TRACK
)
2043 forward
= ci
.new_track
> 0;
2046 /* If the target track is clearly not in memory */
2047 if (CUR_TI
->filesize
== 0 || !CUR_TI
->taginfo_ready
)
2053 /* When skipping backwards, it is possible that we've found a track that's
2054 * buffered, but which is around the track-wrap and therefore not the track
2055 * we are looking for */
2058 int cur_idx
= track_ridx
;
2059 bool taginfo_ready
= true;
2060 /* We've wrapped the buffer backwards if new > old */
2061 bool wrap
= track_ridx
> old_track_ridx
;
2065 cur_idx
= (cur_idx
+ 1) & MAX_TRACK_MASK
;
2067 /* if we've advanced past the wrap when cur_idx is zeroed */
2071 /* if we aren't still on the wrap and we've caught the old track */
2072 if (!(wrap
|| cur_idx
< old_track_ridx
))
2075 /* If we hit a track in between without valid tag info, bail */
2076 if (!tracks
[cur_idx
].taginfo_ready
)
2078 taginfo_ready
= false;
2089 audio_update_trackinfo();
2090 LOGFQUEUE("audio >|= codec Q_CODEC_REQUEST_COMPLETE");
2091 return Q_CODEC_REQUEST_COMPLETE
;
2094 unsigned long audio_prev_elapsed(void)
2096 return prev_track_elapsed
;
2099 static void audio_stop_codec_flush(void)
2101 ci
.stop_codec
= true;
2104 while (audio_codec_loaded
)
2107 /* If the audio codec is not loaded any more, and the audio is still
2108 * playing, it is now and _only_ now safe to call this function from the
2110 if (pcm_is_playing())
2113 pcmbuf_queue_clear();
2115 pcmbuf_pause(paused
);
2118 static void audio_stop_playback(void)
2120 /* If we were playing, save resume information */
2123 struct mp3entry
*id3
= NULL
;
2127 /* Set this early, the outside code yields and may allow the codec
2128 to try to wait for a reply on a buffer wait */
2129 ci
.stop_codec
= true;
2130 id3
= audio_current_track();
2133 /* Save the current playing spot, or NULL if the playlist has ended */
2134 playlist_update_resume_info(id3
);
2136 /* TODO: Create auto bookmark too? */
2138 prev_track_elapsed
= curtrack_id3
.elapsed
;
2140 remove_event(BUFFER_EVENT_BUFFER_LOW
, buffering_low_buffer_callback
);
2143 audio_stop_codec_flush();
2146 track_load_started
= false;
2148 filling
= STATE_IDLE
;
2150 /* Mark all entries null. */
2151 audio_clear_track_entries();
2153 /* Close all tracks */
2154 audio_release_tracks();
2156 memset(&curtrack_id3
, 0, sizeof(struct mp3entry
));
2159 static void audio_play_start(size_t offset
)
2163 #if INPUT_SRC_CAPS != 0
2164 audio_set_input_source(AUDIO_SRC_PLAYBACK
, SRCF_PLAYBACK
);
2165 audio_set_output_source(AUDIO_SRC_PLAYBACK
);
2168 /* Wait for any previously playing audio to flush - TODO: Not necessary? */
2170 audio_stop_codec_flush();
2172 track_changed
= true;
2175 track_load_started
= false;
2181 sound_set_volume(global_settings
.volume
);
2182 track_widx
= track_ridx
= 0;
2184 /* Clear all track entries. */
2185 for (i
= 0; i
< MAX_TRACK
; i
++) {
2186 clear_track_info(&tracks
[i
]);
2189 last_peek_offset
= -1;
2191 /* Officially playing */
2192 queue_reply(&audio_queue
, 1);
2194 #ifdef HAVE_DISK_STORAGE
2195 set_filebuf_watermark(buffer_margin
, 0);
2198 audio_fill_file_buffer(true, offset
);
2200 add_event(BUFFER_EVENT_BUFFER_LOW
, false, buffering_low_buffer_callback
);
2202 LOGFQUEUE("audio > audio Q_AUDIO_TRACK_CHANGED");
2203 queue_post(&audio_queue
, Q_AUDIO_TRACK_CHANGED
, 0);
2207 /* Invalidates all but currently playing track. */
2208 static void audio_invalidate_tracks(void)
2210 if (audio_have_tracks())
2212 last_peek_offset
= 0;
2213 track_widx
= track_ridx
;
2215 /* Mark all other entries null (also buffered wrong metadata). */
2216 audio_clear_track_entries();
2218 track_widx
= (track_widx
+ 1) & MAX_TRACK_MASK
;
2220 audio_fill_file_buffer(false, 0);
2224 static void audio_new_playlist(void)
2226 /* Prepare to start a new fill from the beginning of the playlist */
2227 last_peek_offset
= -1;
2228 if (audio_have_tracks())
2231 skipped_during_pause
= true;
2232 track_widx
= track_ridx
;
2233 audio_clear_track_entries();
2235 track_widx
= (track_widx
+ 1) & MAX_TRACK_MASK
;
2237 /* Mark the current track as invalid to prevent skipping back to it */
2238 CUR_TI
->taginfo_ready
= false;
2241 /* Signal the codec to initiate a track change forward */
2242 new_playlist
= true;
2245 /* Officially playing */
2246 queue_reply(&audio_queue
, 1);
2248 audio_fill_file_buffer(false, 0);
2251 /* Called on manual track skip */
2252 static void audio_initiate_track_change(long direction
)
2254 logf("audio_initiate_track_change(%ld)", direction
);
2256 ci
.new_track
+= direction
;
2257 wps_offset
-= direction
;
2259 skipped_during_pause
= true;
2262 /* Called on manual dir skip */
2263 static void audio_initiate_dir_change(long direction
)
2266 ci
.new_track
= direction
;
2268 skipped_during_pause
= true;
2271 /* Called when PCM track change is complete */
2272 static void audio_finalise_track_change(void)
2274 logf("audio_finalise_track_change");
2279 automatic_skip
= false;
2281 /* Invalidate prevtrack_id3 */
2282 prevtrack_id3
.path
[0] = 0;
2284 if (prev_ti
&& prev_ti
->audio_hid
< 0)
2286 /* No audio left so we clear all the track info. */
2287 clear_track_info(prev_ti
);
2290 if (prev_ti
&& prev_ti
->id3_hid
>= 0)
2292 /* Reset the elapsed time to force the progressbar to be empty if
2293 the user skips back to this track */
2294 bufgetid3(prev_ti
->id3_hid
)->elapsed
= 0;
2298 send_event(PLAYBACK_EVENT_TRACK_CHANGE
, &curtrack_id3
);
2300 track_changed
= true;
2301 playlist_update_resume_info(audio_current_track());
2305 * Layout audio buffer as follows - iram buffer depends on target:
2306 * [|SWAP:iram][|TALK]|FILE|GUARD|PCM|[SWAP:dram[|iram]|]
2308 static void audio_reset_buffer(void)
2310 /* see audio_get_recording_buffer if this is modified */
2311 logf("audio_reset_buffer");
2313 /* If the setup of anything allocated before the file buffer is
2314 changed, do check the adjustments after the buffer_alloc call
2315 as it will likely be affected and need sliding over */
2317 /* Initially set up file buffer as all space available */
2318 malloc_buf
= audiobuf
+ talk_get_bufsize();
2319 /* Align the malloc buf to line size. Especially important to cf
2320 targets that do line reads/writes. */
2321 malloc_buf
= (unsigned char *)(((uintptr_t)malloc_buf
+ 15) & ~15);
2322 filebuf
= malloc_buf
; /* filebuf line align implied */
2323 filebuflen
= audiobufend
- filebuf
;
2327 /* Subtract whatever the pcm buffer says it used plus the guard buffer */
2328 const size_t pcmbuf_size
= pcmbuf_init(filebuf
+ filebuflen
) +GUARD_BUFSIZE
;
2330 if(pcmbuf_size
> filebuflen
)
2331 panicf("Not enough memory for pcmbuf_init() : %d > %d",
2332 (int)pcmbuf_size
, (int)filebuflen
);
2334 filebuflen
-= pcmbuf_size
;
2336 /* Make sure filebuflen is a longword multiple after adjustment - filebuf
2337 will already be line aligned */
2340 buffering_reset(filebuf
, filebuflen
);
2342 /* Clear any references to the file buffer */
2343 buffer_state
= AUDIOBUF_STATE_INITIALIZED
;
2345 #if defined(ROCKBOX_HAS_LOGF) && defined(LOGF_ENABLE)
2346 /* Make sure everything adds up - yes, some info is a bit redundant but
2347 aids viewing and the sumation of certain variables should add up to
2348 the location of others. */
2351 const unsigned char *pcmbuf
= pcmbuf_get_meminfo(&pcmbufsize
);
2352 logf("mabuf: %08X", (unsigned)malloc_buf
);
2353 logf("fbuf: %08X", (unsigned)filebuf
);
2354 logf("fbufe: %08X", (unsigned)(filebuf
+ filebuflen
));
2355 logf("gbuf: %08X", (unsigned)(filebuf
+ filebuflen
));
2356 logf("gbufe: %08X", (unsigned)(filebuf
+ filebuflen
+ GUARD_BUFSIZE
));
2357 logf("pcmb: %08X", (unsigned)pcmbuf
);
2358 logf("pcmbe: %08X", (unsigned)(pcmbuf
+ pcmbufsize
));
2363 static void audio_thread(void)
2365 struct queue_event ev
;
2369 audio_thread_ready
= true;
2373 if (filling
!= STATE_FILLING
) {
2377 if (!pcmbuf_queue_scan(&ev
))
2378 queue_wait_w_tmo(&audio_queue
, &ev
, HZ
/2);
2382 case Q_AUDIO_FILL_BUFFER
:
2383 LOGFQUEUE("audio < Q_AUDIO_FILL_BUFFER %d", (int)ev
.data
);
2384 audio_fill_file_buffer((bool)ev
.data
, 0);
2387 case Q_AUDIO_FINISH_LOAD
:
2388 LOGFQUEUE("audio < Q_AUDIO_FINISH_LOAD");
2389 audio_finish_load_track();
2393 LOGFQUEUE("audio < Q_AUDIO_PLAY");
2394 if (playing
&& ev
.data
<= 0)
2395 audio_new_playlist();
2398 audio_stop_playback();
2399 audio_play_start((size_t)ev
.data
);
2404 LOGFQUEUE("audio < Q_AUDIO_STOP");
2406 audio_stop_playback();
2408 queue_clear(&audio_queue
);
2412 LOGFQUEUE("audio < Q_AUDIO_PAUSE");
2413 if (!(bool) ev
.data
&& skipped_during_pause
&& !pcmbuf_is_crossfade_active())
2414 pcmbuf_play_stop(); /* Flush old track on resume after skip */
2415 skipped_during_pause
= false;
2418 pcmbuf_pause((bool)ev
.data
);
2419 paused
= (bool)ev
.data
;
2423 LOGFQUEUE("audio < Q_AUDIO_SKIP");
2424 audio_initiate_track_change((long)ev
.data
);
2427 case Q_AUDIO_PRE_FF_REWIND
:
2428 LOGFQUEUE("audio < Q_AUDIO_PRE_FF_REWIND");
2434 case Q_AUDIO_FF_REWIND
:
2435 LOGFQUEUE("audio < Q_AUDIO_FF_REWIND");
2440 /* An automatic track skip is in progress. Finalize it,
2441 then go back to the previous track */
2442 audio_finalise_track_change();
2445 ci
.seek_time
= (long)ev
.data
+1;
2448 case Q_AUDIO_CHECK_NEW_TRACK
:
2449 LOGFQUEUE("audio < Q_AUDIO_CHECK_NEW_TRACK");
2450 queue_reply(&audio_queue
, audio_check_new_track());
2453 case Q_AUDIO_DIR_SKIP
:
2454 LOGFQUEUE("audio < Q_AUDIO_DIR_SKIP");
2455 audio_initiate_dir_change(ev
.data
);
2459 LOGFQUEUE("audio < Q_AUDIO_FLUSH");
2460 audio_invalidate_tracks();
2463 case Q_AUDIO_TRACK_CHANGED
:
2464 /* PCM track change done */
2465 LOGFQUEUE("audio < Q_AUDIO_TRACK_CHANGED");
2466 audio_finalise_track_change();
2470 case SYS_USB_CONNECTED
:
2471 LOGFQUEUE("audio < SYS_USB_CONNECTED");
2473 audio_stop_playback();
2474 #ifdef PLAYBACK_VOICE
2477 usb_acknowledge(SYS_USB_CONNECTED_ACK
);
2478 usb_wait_for_disconnect(&audio_queue
);
2480 /* Mark all entries null. */
2481 audio_clear_track_entries();
2483 /* release tracks to make sure all handles are closed */
2484 audio_release_tracks();
2489 LOGFQUEUE_SYS_TIMEOUT("audio < SYS_TIMEOUT");
2493 LOGFQUEUE("audio < default");
2499 /* Initialize the audio system - called from init() in main.c.
2500 * Last function because of all the references to internal symbols
2502 void audio_init(void)
2504 unsigned int audio_thread_id
;
2506 /* Can never do this twice */
2507 if (audio_is_initialized
)
2509 logf("audio: already initialized");
2513 logf("audio: initializing");
2515 /* Initialize queues before giving control elsewhere in case it likes
2516 to send messages. Thread creation will be delayed however so nothing
2517 starts running until ready if something yields such as talk_init. */
2518 queue_init(&audio_queue
, true);
2519 queue_init(&codec_queue
, false);
2520 queue_init(&pcmbuf_queue
, false);
2524 /* Initialize codec api. */
2525 ci
.read_filebuf
= codec_filebuf_callback
;
2526 ci
.pcmbuf_insert
= codec_pcmbuf_insert_callback
;
2527 ci
.codec_get_buffer
= codec_get_buffer
;
2528 ci
.request_buffer
= codec_request_buffer_callback
;
2529 ci
.advance_buffer
= codec_advance_buffer_callback
;
2530 ci
.advance_buffer_loc
= codec_advance_buffer_loc_callback
;
2531 ci
.request_next_track
= codec_request_next_track_callback
;
2532 ci
.seek_buffer
= codec_seek_buffer_callback
;
2533 ci
.seek_complete
= codec_seek_complete_callback
;
2534 ci
.set_elapsed
= codec_set_elapsed_callback
;
2535 ci
.set_offset
= codec_set_offset_callback
;
2536 ci
.configure
= codec_configure_callback
;
2537 ci
.discard_codec
= codec_discard_codec_callback
;
2538 ci
.dsp
= (struct dsp_config
*)dsp_configure(NULL
, DSP_MYDSP
,
2541 /* initialize the buffer */
2544 /* audio_reset_buffer must to know the size of voice buffer so init
2548 codec_thread_id
= create_thread(
2549 codec_thread
, codec_stack
, sizeof(codec_stack
),
2550 CREATE_THREAD_FROZEN
,
2551 codec_thread_name
IF_PRIO(, PRIORITY_PLAYBACK
)
2554 queue_enable_queue_send(&codec_queue
, &codec_queue_sender_list
,
2557 audio_thread_id
= create_thread(audio_thread
, audio_stack
,
2558 sizeof(audio_stack
), CREATE_THREAD_FROZEN
,
2559 audio_thread_name
IF_PRIO(, PRIORITY_USER_INTERFACE
)
2562 queue_enable_queue_send(&audio_queue
, &audio_queue_sender_list
,
2565 #ifdef PLAYBACK_VOICE
2566 voice_thread_init();
2569 /* Set crossfade setting for next buffer init which should be about... */
2570 pcmbuf_crossfade_enable(global_settings
.crossfade
);
2572 /* initialize the buffering system */
2575 /* ...now! Set up the buffers */
2576 audio_reset_buffer();
2579 for(i
= 0; i
< MAX_TRACK
; i
++)
2581 tracks
[i
].audio_hid
= -1;
2582 tracks
[i
].id3_hid
= -1;
2583 tracks
[i
].codec_hid
= -1;
2584 #ifdef HAVE_ALBUMART
2585 tracks
[i
].aa_hid
= -1;
2589 add_event(BUFFER_EVENT_REBUFFER
, false, buffering_handle_rebuffer_callback
);
2590 add_event(BUFFER_EVENT_FINISHED
, false, buffering_handle_finished_callback
);
2592 /* Probably safe to say */
2593 audio_is_initialized
= true;
2595 sound_settings_apply();
2596 #ifdef HAVE_DISK_STORAGE
2597 audio_set_buffer_margin(global_settings
.buffer_margin
);
2600 /* it's safe to let the threads run now */
2601 #ifdef PLAYBACK_VOICE
2602 voice_thread_resume();
2604 thread_thaw(codec_thread_id
);
2605 thread_thaw(audio_thread_id
);
2609 bool audio_is_thread_ready(void)
2611 return audio_thread_ready
;