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_FINISHED
, /* all remaining tracks have been added */
158 #define MAX_TRACK 128
163 #define MAX_TRACK_MASK (MAX_TRACK-1)
165 /* As defined in plugins/lib/xxx2wav.h */
167 #define MALLOC_BUFSIZE (512*1024)
168 #define GUARD_BUFSIZE (32*1024)
170 #define MALLOC_BUFSIZE (100*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 #define BUFFER_STATE_TRASHED -1 /* trashed; must be reset */
208 #define BUFFER_STATE_INITIALIZED 0 /* voice+audio OR audio-only */
209 #define BUFFER_STATE_VOICED_ONLY 1 /* voice-only */
210 static int buffer_state
= BUFFER_STATE_TRASHED
; /* Buffer state */
212 /* Used to keep the WPS up-to-date during track transtition */
213 static struct mp3entry prevtrack_id3
;
215 /* Used to provide the codec with a pointer */
216 static struct mp3entry curtrack_id3
;
218 /* Used to make next track info available while playing last track on buffer */
219 static struct mp3entry lasttrack_id3
;
221 /* Track info structure about songs in the file buffer (A/C-) */
223 int audio_hid
; /* The ID for the track's buffer handle */
224 int id3_hid
; /* The ID for the track's metadata handle */
225 int codec_hid
; /* The ID for the track's codec handle */
227 int aa_hid
; /* The ID for the track's album art handle */
230 size_t filesize
; /* File total length */
232 bool taginfo_ready
; /* Is metadata read */
235 static struct track_info tracks
[MAX_TRACK
];
236 static volatile int track_ridx
= 0; /* Track being decoded (A/C-) */
237 static int track_widx
= 0; /* Track being buffered (A) */
239 #define CUR_TI (&tracks[track_ridx]) /* Playing track info pointer (A/C-) */
240 static struct track_info
*prev_ti
= NULL
; /* Pointer to the previously played
243 /* Set by the audio thread when the current track information has updated
244 * and the WPS may need to update its cached information */
245 static bool track_changed
= false;
247 /* Information used only for filling the buffer */
248 /* Playlist steps from playing track to next track to be buffered (A) */
249 static int last_peek_offset
= 0;
251 /* Scrobbler support */
252 static unsigned long prev_track_elapsed
= 0; /* Previous track elapsed time (C/A-)*/
254 static enum filling_state filling
;
256 /* Track change controls */
257 static bool automatic_skip
= false; /* Who initiated in-progress skip? (C/A-) */
258 static bool dir_skip
= false; /* Is a directory skip pending? (A) */
259 static bool new_playlist
= false; /* Are we starting a new playlist? (A) */
260 static int wps_offset
= 0; /* Pending track change offset, to keep WPS responsive (A) */
261 static bool skipped_during_pause
= false; /* Do we need to clear the PCM buffer when playback resumes (A) */
263 static bool start_play_g
= false; /* Used by audio_load_track to notify
264 audio_finish_load_track about start_play */
266 /* Set to true if the codec thread should send an audio stop request
267 * (typically because the end of the playlist has been reached).
269 static bool codec_requested_stop
= false;
271 static size_t buffer_margin
= 0; /* Buffer margin aka anti-skip buffer (A/C-) */
273 /* Multiple threads */
274 /* Set the watermark to trigger buffer fill (A/C) FIXME */
275 static void set_filebuf_watermark(int seconds
, size_t max
);
278 static struct event_queue audio_queue SHAREDBSS_ATTR
;
279 static struct queue_sender_list audio_queue_sender_list SHAREDBSS_ATTR
;
280 static long audio_stack
[(DEFAULT_STACK_SIZE
+ 0x1000)/sizeof(long)];
281 static const char audio_thread_name
[] = "audio";
283 static void audio_thread(void);
284 static void audio_initiate_track_change(long direction
);
285 static bool audio_have_tracks(void);
286 static void audio_reset_buffer(void);
289 extern struct codec_api ci
;
290 static struct event_queue codec_queue SHAREDBSS_ATTR
;
291 static struct queue_sender_list codec_queue_sender_list
;
292 static long codec_stack
[(DEFAULT_STACK_SIZE
+ 0x2000)/sizeof(long)]
294 static const char codec_thread_name
[] = "codec";
295 struct thread_entry
*codec_thread_p
; /* For modifying thread priority later. */
297 /* PCM buffer messaging */
298 static struct event_queue pcmbuf_queue SHAREDBSS_ATTR
;
300 /* Function to be called by pcm buffer callbacks.
301 * Permissible Context(s): Audio interrupt
303 static void pcmbuf_callback_queue_post(long id
, intptr_t data
)
305 /* No lock since we're already in audio interrupt context */
306 queue_post(&pcmbuf_queue
, id
, data
);
309 /* Scan the pcmbuf queue and return true if a message pulled.
310 * Permissible Context(s): Thread
312 static bool pcmbuf_queue_scan(struct queue_event
*ev
)
314 if (!queue_empty(&pcmbuf_queue
))
316 /* Transfer message to audio queue */
318 /* Pull message - never, ever any blocking call! */
319 queue_wait_w_tmo(&pcmbuf_queue
, ev
, 0);
327 /* Clear the pcmbuf queue of messages
328 * Permissible Context(s): Thread
330 static void pcmbuf_queue_clear(void)
333 queue_clear(&pcmbuf_queue
);
337 /* --- Helper functions --- */
339 static struct mp3entry
*bufgetid3(int handle_id
)
344 struct mp3entry
*id3
;
345 ssize_t ret
= bufgetdata(handle_id
, 0, (void *)&id3
);
347 if (ret
< 0 || ret
!= sizeof(struct mp3entry
))
353 static bool clear_track_info(struct track_info
*track
)
355 /* bufclose returns true if the handle is not found, or if it is closed
356 * successfully, so these checks are safe on non-existant handles */
360 if (track
->codec_hid
>= 0) {
361 if (bufclose(track
->codec_hid
))
362 track
->codec_hid
= -1;
367 if (track
->id3_hid
>= 0) {
368 if (bufclose(track
->id3_hid
))
374 if (track
->audio_hid
>= 0) {
375 if (bufclose(track
->audio_hid
))
376 track
->audio_hid
= -1;
382 if (track
->aa_hid
>= 0) {
383 if (bufclose(track
->aa_hid
))
391 track
->taginfo_ready
= false;
396 /* --- External interfaces --- */
398 /* This sends a stop message and the audio thread will dump all it's
399 subsequenct messages */
400 void audio_hard_stop(void)
403 LOGFQUEUE("audio >| audio Q_AUDIO_STOP: 1");
404 queue_send(&audio_queue
, Q_AUDIO_STOP
, 1);
405 #ifdef PLAYBACK_VOICE
410 bool audio_restore_playback(int type
)
414 case AUDIO_WANT_PLAYBACK
:
415 if (buffer_state
!= BUFFER_STATE_INITIALIZED
)
416 audio_reset_buffer();
418 case AUDIO_WANT_VOICE
:
419 if (buffer_state
== BUFFER_STATE_TRASHED
)
420 audio_reset_buffer();
427 unsigned char *audio_get_buffer(bool talk_buf
, size_t *buffer_size
)
429 unsigned char *buf
, *end
;
431 if (audio_is_initialized
)
435 /* else buffer_state will be BUFFER_STATE_TRASHED at this point */
437 if (buffer_size
== NULL
)
439 /* Special case for talk_init to use since it already knows it's
441 buffer_state
= BUFFER_STATE_TRASHED
;
445 if (talk_buf
|| buffer_state
== BUFFER_STATE_TRASHED
446 || !talk_voice_required())
448 logf("get buffer: talk, audio");
449 /* Ok to use everything from audiobuf to audiobufend - voice is loaded,
450 the talk buffer is not needed because voice isn't being used, or
451 could be BUFFER_STATE_TRASHED already. If state is
452 BUFFER_STATE_VOICED_ONLY, no problem as long as memory isn't written
453 without the caller knowing what's going on. Changing certain settings
454 may move it to a worse condition but the memory in use by something
455 else will remain undisturbed.
457 if (buffer_state
!= BUFFER_STATE_TRASHED
)
460 buffer_state
= BUFFER_STATE_TRASHED
;
468 /* Safe to just return this if already BUFFER_STATE_VOICED_ONLY or
469 still BUFFER_STATE_INITIALIZED */
470 /* Skip talk buffer and move pcm buffer to end to maximize available
471 contiguous memory - no audio running means voice will not need the
473 logf("get buffer: audio");
474 buf
= audiobuf
+ talk_get_bufsize();
475 end
= audiobufend
- pcmbuf_init(audiobufend
);
476 buffer_state
= BUFFER_STATE_VOICED_ONLY
;
479 *buffer_size
= end
- buf
;
484 #ifdef HAVE_RECORDING
485 unsigned char *audio_get_recording_buffer(size_t *buffer_size
)
487 /* Stop audio, voice and obtain all available buffer space */
491 unsigned char *end
= audiobufend
;
492 buffer_state
= BUFFER_STATE_TRASHED
;
493 *buffer_size
= end
- audiobuf
;
495 return (unsigned char *)audiobuf
;
498 bool audio_load_encoder(int afmt
)
501 const char *enc_fn
= get_codec_filename(afmt
| CODEC_TYPE_ENCODER
);
505 audio_remove_encoder();
506 ci
.enc_codec_loaded
= 0; /* clear any previous error condition */
508 LOGFQUEUE("codec > Q_ENCODER_LOAD_DISK");
509 queue_post(&codec_queue
, Q_ENCODER_LOAD_DISK
, (intptr_t)enc_fn
);
511 while (ci
.enc_codec_loaded
== 0)
514 logf("codec loaded: %d", ci
.enc_codec_loaded
);
516 return ci
.enc_codec_loaded
> 0;
521 } /* audio_load_encoder */
523 void audio_remove_encoder(void)
526 /* force encoder codec unload (if currently loaded) */
527 if (ci
.enc_codec_loaded
<= 0)
530 ci
.stop_encoder
= true;
531 while (ci
.enc_codec_loaded
> 0)
534 } /* audio_remove_encoder */
536 #endif /* HAVE_RECORDING */
539 int audio_current_aa_hid(void)
542 int offset
= ci
.new_track
+ wps_offset
;
544 cur_idx
= track_ridx
+ offset
;
545 cur_idx
&= MAX_TRACK_MASK
;
547 return tracks
[cur_idx
].aa_hid
;
551 struct mp3entry
* audio_current_track(void)
553 const char *filename
;
555 static struct mp3entry temp_id3
;
556 struct playlist_track_info trackinfo
;
558 int offset
= ci
.new_track
+ wps_offset
;
560 cur_idx
= (track_ridx
+ offset
) & MAX_TRACK_MASK
;
562 if (cur_idx
== track_ridx
&& *curtrack_id3
.path
)
565 return &curtrack_id3
;
567 else if (automatic_skip
&& offset
== -1 && *prevtrack_id3
.path
)
569 /* We're in a track transition. The codec has moved on to the nex track,
570 but the audio being played is still the same (now previous) track.
571 prevtrack_id3.elapsed is being updated in an ISR by
572 codec_pcmbuf_position_callback */
573 return &prevtrack_id3
;
575 else if (tracks
[cur_idx
].id3_hid
>= 0)
577 /* Get the ID3 metadata from the main buffer */
578 struct mp3entry
*ret
= bufgetid3(tracks
[cur_idx
].id3_hid
);
582 /* We didn't find the ID3 metadata, so we fill temp_id3 with the little info
583 we have and return that. */
585 memset(&temp_id3
, 0, sizeof(struct mp3entry
));
587 playlist_get_track_info(NULL
, playlist_next(0)+wps_offset
, &trackinfo
);
588 filename
= trackinfo
.filename
;
590 filename
= "No file!";
592 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
593 if (tagcache_fill_tags(&temp_id3
, filename
))
597 p
= strrchr(filename
, '/');
603 strncpy(temp_id3
.path
, p
, sizeof(temp_id3
.path
)-1);
604 temp_id3
.title
= &temp_id3
.path
[0];
609 struct mp3entry
* audio_next_track(void)
612 int offset
= ci
.new_track
+ wps_offset
;
614 if (!audio_have_tracks())
617 if (wps_offset
== -1 && *prevtrack_id3
.path
)
619 /* We're in a track transition. The next track for the WPS is the one
620 currently being decoded. */
621 return &curtrack_id3
;
624 next_idx
= (track_ridx
+ offset
+ 1) & MAX_TRACK_MASK
;
626 if (tracks
[next_idx
].id3_hid
>= 0)
627 return bufgetid3(tracks
[next_idx
].id3_hid
);
629 if (next_idx
== track_widx
)
631 /* The next track hasn't been buffered yet, so we return the static
632 version of its metadata. */
633 return &lasttrack_id3
;
639 bool audio_has_changed_track(void)
643 track_changed
= false;
650 void audio_play(long offset
)
654 #ifdef PLAYBACK_VOICE
655 /* Truncate any existing voice output so we don't have spelling
656 * etc. over the first part of the played track */
661 LOGFQUEUE("audio >| audio Q_AUDIO_PLAY: %ld", offset
);
662 /* Don't return until playback has actually started */
663 queue_send(&audio_queue
, Q_AUDIO_PLAY
, offset
);
666 void audio_stop(void)
669 LOGFQUEUE("audio >| audio Q_AUDIO_STOP");
670 /* Don't return until playback has actually stopped */
671 queue_send(&audio_queue
, Q_AUDIO_STOP
, 0);
674 void audio_pause(void)
676 LOGFQUEUE("audio >| audio Q_AUDIO_PAUSE");
677 /* Don't return until playback has actually paused */
678 queue_send(&audio_queue
, Q_AUDIO_PAUSE
, true);
681 void audio_resume(void)
683 LOGFQUEUE("audio >| audio Q_AUDIO_PAUSE resume");
684 /* Don't return until playback has actually resumed */
685 queue_send(&audio_queue
, Q_AUDIO_PAUSE
, false);
688 static void audio_skip(int direction
)
690 if (playlist_check(ci
.new_track
+ wps_offset
+ direction
))
692 if (global_settings
.beep
)
693 pcmbuf_beep(5000, 100, 2500*global_settings
.beep
);
695 LOGFQUEUE("audio > audio Q_AUDIO_SKIP %d", direction
);
696 queue_post(&audio_queue
, Q_AUDIO_SKIP
, direction
);
697 /* Update wps while our message travels inside deep playback queues. */
698 wps_offset
+= direction
;
699 track_changed
= true;
703 /* No more tracks. */
704 if (global_settings
.beep
)
705 pcmbuf_beep(1000, 100, 1000*global_settings
.beep
);
709 void audio_next(void)
714 void audio_prev(void)
719 void audio_next_dir(void)
721 LOGFQUEUE("audio > audio Q_AUDIO_DIR_SKIP 1");
722 queue_post(&audio_queue
, Q_AUDIO_DIR_SKIP
, 1);
725 void audio_prev_dir(void)
727 LOGFQUEUE("audio > audio Q_AUDIO_DIR_SKIP -1");
728 queue_post(&audio_queue
, Q_AUDIO_DIR_SKIP
, -1);
731 void audio_pre_ff_rewind(void)
733 LOGFQUEUE("audio > audio Q_AUDIO_PRE_FF_REWIND");
734 queue_post(&audio_queue
, Q_AUDIO_PRE_FF_REWIND
, 0);
737 void audio_ff_rewind(long newpos
)
739 LOGFQUEUE("audio > audio Q_AUDIO_FF_REWIND");
740 queue_post(&audio_queue
, Q_AUDIO_FF_REWIND
, newpos
);
743 void audio_flush_and_reload_tracks(void)
745 LOGFQUEUE("audio > audio Q_AUDIO_FLUSH");
746 queue_post(&audio_queue
, Q_AUDIO_FLUSH
, 0);
749 void audio_error_clear(void)
751 #ifdef AUDIO_HAVE_RECORDING
752 pcm_rec_error_clear();
756 int audio_status(void)
761 ret
|= AUDIO_STATUS_PLAY
;
764 ret
|= AUDIO_STATUS_PAUSE
;
766 #ifdef HAVE_RECORDING
767 /* Do this here for constitency with mpeg.c version */
768 ret
|= pcm_rec_status();
774 int audio_get_file_pos(void)
779 #ifndef HAVE_FLASH_STORAGE
780 void audio_set_buffer_margin(int setting
)
782 static const int lookup
[] = {5, 15, 30, 60, 120, 180, 300, 600};
783 buffer_margin
= lookup
[setting
];
784 logf("buffer margin: %ld", (long)buffer_margin
);
785 set_filebuf_watermark(buffer_margin
, 0);
789 /* Take necessary steps to enable or disable the crossfade setting */
790 void audio_set_crossfade(int enable
)
796 /* Tell it the next setting to use */
797 pcmbuf_crossfade_enable(enable
);
799 /* Return if size hasn't changed or this is too early to determine
800 which in the second case there's no way we could be playing
802 if (pcmbuf_is_same_size())
804 /* This function is a copout and just syncs some variables -
805 to be removed at a later date */
806 pcmbuf_crossfade_enable_finished();
811 was_playing
= playing
;
813 /* Playback has to be stopped before changing the buffer size */
816 /* Store the track resume position */
817 offset
= curtrack_id3
.offset
;
818 gui_syncsplash(0, str(LANG_RESTARTING_PLAYBACK
));
821 /* Blast it - audio buffer will have to be setup again next time
823 audio_get_buffer(true, &size
);
825 /* Restart playback if audio was running previously */
830 /* --- Routines called from multiple threads --- */
832 static void set_filebuf_watermark(int seconds
, size_t max
)
837 return; /* Audio buffers not yet set up */
839 bytes
= seconds
?MAX(curtrack_id3
.bitrate
* seconds
* (1000/8), max
):max
;
840 bytes
= MIN(bytes
, filebuflen
/ 2);
841 buf_set_watermark(bytes
);
844 const char *get_codec_filename(int cod_spec
)
848 #ifdef HAVE_RECORDING
849 /* Can choose decoder or encoder if one available */
850 int type
= cod_spec
& CODEC_TYPE_MASK
;
851 int afmt
= cod_spec
& CODEC_AFMT_MASK
;
853 if ((unsigned)afmt
>= AFMT_NUM_CODECS
)
854 type
= AFMT_UNKNOWN
| (type
& CODEC_TYPE_MASK
);
856 fname
= (type
== CODEC_TYPE_ENCODER
) ?
857 audio_formats
[afmt
].codec_enc_root_fn
:
858 audio_formats
[afmt
].codec_root_fn
;
861 (type
== CODEC_TYPE_ENCODER
) ? "Encoder" : "Decoder",
862 afmt
, fname
? fname
: "<unknown>");
863 #else /* !HAVE_RECORDING */
865 if ((unsigned)cod_spec
>= AFMT_NUM_CODECS
)
866 cod_spec
= AFMT_UNKNOWN
;
867 fname
= audio_formats
[cod_spec
].codec_root_fn
;
868 logf("Codec: %d - %s", cod_spec
, fname
? fname
: "<unknown>");
869 #endif /* HAVE_RECORDING */
872 } /* get_codec_filename */
874 /* --- Codec thread --- */
875 static bool codec_pcmbuf_insert_callback(
876 const void *ch1
, const void *ch2
, int count
)
878 const char *src
[2] = { ch1
, ch2
};
882 int out_count
= dsp_output_count(ci
.dsp
, count
);
886 /* Prevent audio from a previous track from playing */
887 if (ci
.new_track
|| ci
.stop_codec
)
890 while ((dest
= pcmbuf_request_buffer(&out_count
)) == NULL
)
894 if (ci
.seek_time
|| ci
.new_track
|| ci
.stop_codec
)
898 /* Get the real input_size for output_size bytes, guarding
899 * against resampling buffer overflows. */
900 inp_count
= dsp_input_count(ci
.dsp
, out_count
);
905 /* Input size has grown, no error, just don't write more than length */
906 if (inp_count
> count
)
909 out_count
= dsp_process(ci
.dsp
, dest
, src
, inp_count
);
914 pcmbuf_write_complete(out_count
);
920 } /* codec_pcmbuf_insert_callback */
922 static void* codec_get_memory_callback(size_t *size
)
924 *size
= MALLOC_BUFSIZE
;
928 /* Between the codec and PCM track change, we need to keep updating the
929 "elapsed" value of the previous (to the codec, but current to the
930 user/PCM/WPS) track, so that the progressbar reaches the end.
931 During that transition, the WPS will display prevtrack_id3. */
932 static void codec_pcmbuf_position_callback(size_t size
) ICODE_ATTR
;
933 static void codec_pcmbuf_position_callback(size_t size
)
935 /* This is called from an ISR, so be quick */
936 unsigned int time
= size
* 1000 / 4 / NATIVE_FREQUENCY
+
937 prevtrack_id3
.elapsed
;
939 if (time
>= prevtrack_id3
.length
)
941 pcmbuf_set_position_callback(NULL
);
942 prevtrack_id3
.elapsed
= prevtrack_id3
.length
;
945 prevtrack_id3
.elapsed
= time
;
948 static void codec_set_elapsed_callback(unsigned int value
)
950 unsigned int latency
;
954 #ifdef AB_REPEAT_ENABLE
955 ab_position_report(value
);
958 latency
= pcmbuf_get_latency();
960 curtrack_id3
.elapsed
= 0;
961 else if (value
- latency
> curtrack_id3
.elapsed
||
962 value
- latency
< curtrack_id3
.elapsed
- 2)
964 curtrack_id3
.elapsed
= value
- latency
;
968 static void codec_set_offset_callback(size_t value
)
970 unsigned int latency
;
975 latency
= pcmbuf_get_latency() * curtrack_id3
.bitrate
/ 8;
977 curtrack_id3
.offset
= 0;
979 curtrack_id3
.offset
= value
- latency
;
982 static void codec_advance_buffer_counters(size_t amount
)
984 bufadvance(CUR_TI
->audio_hid
, amount
);
988 /* copy up-to size bytes into ptr and return the actual size copied */
989 static size_t codec_filebuf_callback(void *ptr
, size_t size
)
993 if (ci
.stop_codec
|| !playing
)
996 copy_n
= bufread(CUR_TI
->audio_hid
, size
, ptr
);
998 /* Nothing requested OR nothing left */
1002 /* Update read and other position pointers */
1003 codec_advance_buffer_counters(copy_n
);
1005 /* Return the actual amount of data copied to the buffer */
1007 } /* codec_filebuf_callback */
1009 static void* codec_request_buffer_callback(size_t *realsize
, size_t reqsize
)
1011 size_t copy_n
= reqsize
;
1021 ret
= bufgetdata(CUR_TI
->audio_hid
, reqsize
, &ptr
);
1023 copy_n
= MIN((size_t)ret
, reqsize
);
1034 } /* codec_request_buffer_callback */
1036 static int get_codec_base_type(int type
)
1048 static void codec_advance_buffer_callback(size_t amount
)
1050 codec_advance_buffer_counters(amount
);
1051 codec_set_offset_callback(ci
.curpos
);
1054 static void codec_advance_buffer_loc_callback(void *ptr
)
1056 size_t amount
= buf_get_offset(CUR_TI
->audio_hid
, ptr
);
1057 codec_advance_buffer_callback(amount
);
1060 static void codec_seek_complete_callback(void)
1062 logf("seek_complete");
1063 if (pcm_is_paused())
1065 /* If this is not a seamless seek, clear the buffer */
1067 dsp_configure(ci
.dsp
, DSP_FLUSH
, 0);
1069 /* If playback was not 'deliberately' paused, unpause now */
1071 pcmbuf_pause(false);
1076 static bool codec_seek_buffer_callback(size_t newpos
)
1078 logf("codec_seek_buffer_callback");
1080 int ret
= bufseek(CUR_TI
->audio_hid
, newpos
);
1090 static void codec_configure_callback(int setting
, intptr_t value
)
1093 case CODEC_SET_FILEBUF_WATERMARK
:
1094 set_filebuf_watermark(buffer_margin
, value
);
1098 if (!dsp_configure(ci
.dsp
, setting
, value
))
1099 { logf("Illegal key:%d", setting
); }
1103 static void codec_track_changed(void)
1105 LOGFQUEUE("codec > audio Q_AUDIO_TRACK_CHANGED");
1106 queue_post(&audio_queue
, Q_AUDIO_TRACK_CHANGED
, 0);
1109 static void codec_pcmbuf_track_changed_callback(void)
1111 pcmbuf_set_position_callback(NULL
);
1112 pcmbuf_callback_queue_post(Q_AUDIO_TRACK_CHANGED
, 0);
1115 static void codec_discard_codec_callback(void)
1117 if (CUR_TI
->codec_hid
>= 0)
1119 bufclose(CUR_TI
->codec_hid
);
1120 CUR_TI
->codec_hid
= -1;
1124 static inline void codec_gapless_track_change(void)
1126 /* callback keeps the progress bar moving while the pcmbuf empties */
1127 pcmbuf_set_position_callback(codec_pcmbuf_position_callback
);
1128 /* set the pcmbuf callback for when the track really changes */
1129 pcmbuf_set_event_handler(codec_pcmbuf_track_changed_callback
);
1132 static inline void codec_crossfade_track_change(void)
1134 /* Initiate automatic crossfade mode */
1135 pcmbuf_crossfade_init(false);
1136 /* Notify the wps that the track change starts now */
1137 codec_track_changed();
1140 static void codec_track_skip_done(bool was_manual
)
1142 /* Manual track change (always crossfade or flush audio). */
1145 pcmbuf_crossfade_init(true);
1146 LOGFQUEUE("codec > audio Q_AUDIO_TRACK_CHANGED");
1147 queue_post(&audio_queue
, Q_AUDIO_TRACK_CHANGED
, 0);
1149 /* Automatic track change w/crossfade, if not in "Track Skip Only" mode. */
1150 else if (pcmbuf_is_crossfade_enabled() && !pcmbuf_is_crossfade_active()
1151 && global_settings
.crossfade
!= CROSSFADE_ENABLE_TRACKSKIP
)
1153 if (global_settings
.crossfade
== CROSSFADE_ENABLE_SHUFFLE_AND_TRACKSKIP
)
1155 if (global_settings
.playlist_shuffle
)
1156 /* shuffle mode is on, so crossfade: */
1157 codec_crossfade_track_change();
1159 /* shuffle mode is off, so do a gapless track change */
1160 codec_gapless_track_change();
1163 /* normal crossfade: */
1164 codec_crossfade_track_change();
1167 /* normal gapless playback. */
1168 codec_gapless_track_change();
1171 static bool codec_load_next_track(void)
1173 intptr_t result
= Q_CODEC_REQUEST_FAILED
;
1175 prev_track_elapsed
= curtrack_id3
.elapsed
;
1177 #ifdef AB_REPEAT_ENABLE
1178 ab_end_of_track_report();
1181 logf("Request new track");
1183 if (ci
.new_track
== 0)
1186 automatic_skip
= true;
1191 trigger_cpu_boost();
1192 LOGFQUEUE("codec >| audio Q_AUDIO_CHECK_NEW_TRACK");
1193 result
= queue_send(&audio_queue
, Q_AUDIO_CHECK_NEW_TRACK
, 0);
1198 case Q_CODEC_REQUEST_COMPLETE
:
1199 LOGFQUEUE("codec |< Q_CODEC_REQUEST_COMPLETE");
1200 codec_track_skip_done(!automatic_skip
);
1203 case Q_CODEC_REQUEST_FAILED
:
1204 LOGFQUEUE("codec |< Q_CODEC_REQUEST_FAILED");
1206 ci
.stop_codec
= true;
1207 codec_requested_stop
= true;
1211 LOGFQUEUE("codec |< default");
1212 ci
.stop_codec
= true;
1213 codec_requested_stop
= true;
1218 static bool codec_request_next_track_callback(void)
1222 if (ci
.stop_codec
|| !playing
)
1225 prev_codectype
= get_codec_base_type(curtrack_id3
.codectype
);
1227 if (!codec_load_next_track())
1230 /* Seek to the beginning of the new track because if the struct
1231 mp3entry was buffered, "elapsed" might not be zero (if the track has
1232 been played already but not unbuffered) */
1233 codec_seek_buffer_callback(curtrack_id3
.first_frame_offset
);
1235 /* Check if the next codec is the same file. */
1236 if (prev_codectype
== get_codec_base_type(curtrack_id3
.codectype
))
1238 logf("New track loaded");
1239 codec_discard_codec_callback();
1244 logf("New codec:%d/%d", curtrack_id3
.codectype
, prev_codectype
);
1249 static void codec_thread(void)
1251 struct queue_event ev
;
1257 if (!pcmbuf_is_crossfade_active()) {
1261 queue_wait(&codec_queue
, &ev
);
1262 codec_requested_stop
= false;
1265 case Q_CODEC_LOAD_DISK
:
1266 LOGFQUEUE("codec < Q_CODEC_LOAD_DISK");
1267 queue_reply(&codec_queue
, 1);
1268 audio_codec_loaded
= true;
1269 ci
.stop_codec
= false;
1270 status
= codec_load_file((const char *)ev
.data
, &ci
);
1274 LOGFQUEUE("codec < Q_CODEC_LOAD");
1275 if (CUR_TI
->codec_hid
< 0) {
1276 logf("Codec slot is empty!");
1277 /* Wait for the pcm buffer to go empty */
1278 while (pcm_is_playing())
1280 /* This must be set to prevent an infinite loop */
1281 ci
.stop_codec
= true;
1282 LOGFQUEUE("codec > codec Q_AUDIO_PLAY");
1283 queue_post(&codec_queue
, Q_AUDIO_PLAY
, 0);
1287 audio_codec_loaded
= true;
1288 ci
.stop_codec
= false;
1289 status
= codec_load_buf(CUR_TI
->codec_hid
, &ci
);
1292 #ifdef AUDIO_HAVE_RECORDING
1293 case Q_ENCODER_LOAD_DISK
:
1294 LOGFQUEUE("codec < Q_ENCODER_LOAD_DISK");
1295 audio_codec_loaded
= false; /* Not audio codec! */
1296 logf("loading encoder");
1297 ci
.stop_encoder
= false;
1298 status
= codec_load_file((const char *)ev
.data
, &ci
);
1299 logf("encoder stopped");
1301 #endif /* AUDIO_HAVE_RECORDING */
1304 LOGFQUEUE("codec < default");
1307 if (audio_codec_loaded
)
1316 audio_codec_loaded
= false;
1320 case Q_CODEC_LOAD_DISK
:
1322 LOGFQUEUE("codec < Q_CODEC_LOAD");
1325 if (ci
.new_track
|| status
!= CODEC_OK
)
1329 logf("Codec failure");
1330 gui_syncsplash(HZ
*2, "Codec failure");
1333 if (!codec_load_next_track())
1335 LOGFQUEUE("codec > audio Q_AUDIO_STOP");
1336 /* End of playlist */
1337 queue_post(&audio_queue
, Q_AUDIO_STOP
, 0);
1343 logf("Codec finished");
1346 /* Wait for the audio to stop playing before
1347 * triggering the WPS exit */
1348 while(pcm_is_playing())
1350 curtrack_id3
.elapsed
=
1351 curtrack_id3
.length
- pcmbuf_get_latency();
1355 if (codec_requested_stop
)
1357 LOGFQUEUE("codec > audio Q_AUDIO_STOP");
1358 queue_post(&audio_queue
, Q_AUDIO_STOP
, 0);
1364 if (CUR_TI
->codec_hid
>= 0)
1366 LOGFQUEUE("codec > codec Q_CODEC_LOAD");
1367 queue_post(&codec_queue
, Q_CODEC_LOAD
, 0);
1371 const char *codec_fn
=
1372 get_codec_filename(curtrack_id3
.codectype
);
1375 LOGFQUEUE("codec > codec Q_CODEC_LOAD_DISK");
1376 queue_post(&codec_queue
, Q_CODEC_LOAD_DISK
,
1377 (intptr_t)codec_fn
);
1383 #ifdef AUDIO_HAVE_RECORDING
1384 case Q_ENCODER_LOAD_DISK
:
1385 LOGFQUEUE("codec < Q_ENCODER_LOAD_DISK");
1387 if (status
== CODEC_OK
)
1390 logf("Encoder failure");
1391 gui_syncsplash(HZ
*2, "Encoder failure");
1393 if (ci
.enc_codec_loaded
< 0)
1396 logf("Encoder failed to load");
1397 ci
.enc_codec_loaded
= -1;
1399 #endif /* AUDIO_HAVE_RECORDING */
1402 LOGFQUEUE("codec < default");
1409 /* --- Buffering callbacks --- */
1411 static void buffering_low_buffer_callback(void *data
)
1414 logf("low buffer callback");
1416 if (filling
== STATE_FULL
) {
1417 /* force a refill */
1418 LOGFQUEUE("buffering > audio Q_AUDIO_FILL_BUFFER");
1419 queue_post(&audio_queue
, Q_AUDIO_FILL_BUFFER
, 0);
1423 static void buffering_handle_rebuffer_callback(void *data
)
1426 LOGFQUEUE("audio >| audio Q_AUDIO_FLUSH");
1427 queue_post(&audio_queue
, Q_AUDIO_FLUSH
, 0);
1430 static void buffering_handle_finished_callback(int *data
)
1432 logf("handle %d finished buffering", *data
);
1434 if (*data
== tracks
[track_widx
].id3_hid
)
1436 /* The metadata handle for the last loaded track has been buffered.
1437 We can ask the audio thread to load the rest of the track's data. */
1438 LOGFQUEUE("audio >| audio Q_AUDIO_FINISH_LOAD");
1439 queue_post(&audio_queue
, Q_AUDIO_FINISH_LOAD
, 0);
1443 /* This is most likely an audio handle, so we strip the useless
1444 trailing tags that are left. */
1450 /* --- Audio thread --- */
1452 static bool audio_have_tracks(void)
1454 return (audio_track_count() != 0);
1457 static int audio_free_track_count(void)
1459 /* Used tracks + free tracks adds up to MAX_TRACK - 1 */
1460 return MAX_TRACK
- 1 - audio_track_count();
1463 int audio_track_count(void)
1465 /* Calculate difference from track_ridx to track_widx
1466 * taking into account a possible wrap-around. */
1467 return (MAX_TRACK
+ track_widx
- track_ridx
) & MAX_TRACK_MASK
;
1470 long audio_filebufused(void)
1472 return (long) buf_used();
1475 /* Update track info after successful a codec track change */
1476 static void audio_update_trackinfo(void)
1478 /* Load the curent track's metadata into curtrack_id3 */
1479 if (CUR_TI
->id3_hid
>= 0)
1480 copy_mp3entry(&curtrack_id3
, bufgetid3(CUR_TI
->id3_hid
));
1482 /* Reset current position */
1483 curtrack_id3
.elapsed
= 0;
1484 curtrack_id3
.offset
= 0;
1486 /* Update the codec API */
1487 ci
.filesize
= CUR_TI
->filesize
;
1488 ci
.id3
= &curtrack_id3
;
1490 ci
.taginfo_ready
= &CUR_TI
->taginfo_ready
;
1493 /* Clear tracks between write and read, non inclusive */
1494 static void audio_clear_track_entries(void)
1496 int cur_idx
= track_widx
;
1498 logf("Clearing tracks:%d/%d", track_ridx
, track_widx
);
1500 /* Loop over all tracks from write-to-read */
1503 cur_idx
= (cur_idx
+ 1) & MAX_TRACK_MASK
;
1505 if (cur_idx
== track_ridx
)
1508 clear_track_info(&tracks
[cur_idx
]);
1512 /* Clear all tracks */
1513 static bool audio_release_tracks(void)
1517 logf("releasing all tracks");
1519 for(i
= 0; i
< MAX_TRACK
; i
++)
1521 cur_idx
= (track_ridx
+ i
) & MAX_TRACK_MASK
;
1522 if (!clear_track_info(&tracks
[cur_idx
]))
1529 static bool audio_loadcodec(bool start_play
)
1532 char codec_path
[MAX_PATH
]; /* Full path to codec */
1533 const struct mp3entry
*id3
, *prev_id3
;
1535 if (tracks
[track_widx
].id3_hid
< 0) {
1539 id3
= bufgetid3(tracks
[track_widx
].id3_hid
);
1543 const char *codec_fn
= get_codec_filename(id3
->codectype
);
1544 if (codec_fn
== NULL
)
1547 tracks
[track_widx
].codec_hid
= -1;
1551 /* Load the codec directly from disk and save some memory. */
1552 track_ridx
= track_widx
;
1553 ci
.filesize
= CUR_TI
->filesize
;
1554 ci
.id3
= &curtrack_id3
;
1555 ci
.taginfo_ready
= &CUR_TI
->taginfo_ready
;
1557 LOGFQUEUE("codec > codec Q_CODEC_LOAD_DISK");
1558 queue_post(&codec_queue
, Q_CODEC_LOAD_DISK
, (intptr_t)codec_fn
);
1563 /* If we already have another track than this one buffered */
1564 if (track_widx
!= track_ridx
)
1566 prev_track
= (track_widx
- 1) & MAX_TRACK_MASK
;
1568 id3
= bufgetid3(tracks
[track_widx
].id3_hid
);
1569 prev_id3
= bufgetid3(tracks
[prev_track
].id3_hid
);
1571 /* If the previous codec is the same as this one, there is no need
1572 * to put another copy of it on the file buffer */
1573 if (id3
&& prev_id3
&&
1574 get_codec_base_type(id3
->codectype
) ==
1575 get_codec_base_type(prev_id3
->codectype
)
1576 && audio_codec_loaded
)
1578 logf("Reusing prev. codec");
1584 codec_get_full_path(codec_path
, codec_fn
);
1586 tracks
[track_widx
].codec_hid
= bufopen(codec_path
, 0, TYPE_CODEC
);
1587 if (tracks
[track_widx
].codec_hid
< 0)
1590 logf("Loaded codec");
1595 /* Load metadata for the next track (with bufopen). The rest of the track
1596 loading will be handled by audio_finish_load_track once the metadata has been
1597 actually loaded by the buffering thread. */
1598 static bool audio_load_track(size_t offset
, bool start_play
)
1600 const char *trackname
;
1603 start_play_g
= start_play
; /* will be read by audio_finish_load_track */
1605 /* Stop buffer filling if there is no free track entries.
1606 Don't fill up the last track entry (we wan't to store next track
1608 if (!audio_free_track_count())
1610 logf("No free tracks");
1615 tracks
[track_widx
].taginfo_ready
= false;
1617 logf("Buffering track:%d/%d", track_widx
, track_ridx
);
1618 /* Get track name from current playlist read position. */
1619 while ((trackname
= playlist_peek(last_peek_offset
)) != NULL
)
1621 /* Handle broken playlists. */
1622 fd
= open(trackname
, O_RDONLY
);
1625 logf("Open failed");
1626 /* Skip invalid entry from playlist. */
1627 playlist_skip_entry(NULL
, last_peek_offset
);
1635 logf("End-of-playlist");
1636 memset(&lasttrack_id3
, 0, sizeof(struct mp3entry
));
1637 filling
= STATE_FINISHED
;
1641 tracks
[track_widx
].filesize
= filesize(fd
);
1643 if (offset
> tracks
[track_widx
].filesize
)
1646 /* Set default values */
1649 buf_set_watermark(AUDIO_DEFAULT_WATERMARK
);
1650 dsp_configure(ci
.dsp
, DSP_RESET
, 0);
1651 track_changed
= true;
1652 playlist_update_resume_info(audio_current_track());
1655 /* Get track metadata if we don't already have it. */
1656 if (tracks
[track_widx
].id3_hid
< 0)
1658 tracks
[track_widx
].id3_hid
= bufopen(trackname
, 0, TYPE_ID3
);
1660 if (tracks
[track_widx
].id3_hid
< 0)
1662 /* Buffer is full. */
1663 get_metadata(&lasttrack_id3
, fd
, trackname
);
1666 logf("buffer is full for now");
1667 filling
= STATE_FULL
;
1671 if (track_widx
== track_ridx
)
1673 buf_request_buffer_handle(tracks
[track_widx
].id3_hid
);
1674 copy_mp3entry(&curtrack_id3
, bufgetid3(tracks
[track_widx
].id3_hid
));
1675 curtrack_id3
.offset
= offset
;
1680 track_changed
= true;
1681 playlist_update_resume_info(audio_current_track());
1689 /* Second part of the track loading: We now have the metadata available, so we
1690 can load the codec, the album art and finally the audio data.
1691 This is called on the audio thread after the buffering thread calls the
1692 buffering_handle_finished_callback callback. */
1693 static void audio_finish_load_track(void)
1696 size_t file_offset
= 0;
1698 bool start_play
= start_play_g
;
1701 if (cuesheet_is_enabled() && tracks
[track_widx
].id3
.cuesheet_type
== 1)
1703 char cuepath
[MAX_PATH
];
1705 struct cuesheet
*cue
= start_play
? curr_cue
: temp_cue
;
1707 if (look_for_cuesheet_file(trackname
, cuepath
) &&
1708 parse_cuesheet(cuepath
, cue
))
1710 strcpy((cue
)->audio_filename
, trackname
);
1712 cue_spoof_id3(curr_cue
, &tracks
[track_widx
].id3
);
1717 if (tracks
[track_widx
].id3_hid
< 0) {
1718 logf("no metatdata");
1722 struct mp3entry
*track_id3
;
1724 if (track_widx
== track_ridx
)
1725 track_id3
= &curtrack_id3
;
1727 track_id3
= bufgetid3(tracks
[track_widx
].id3_hid
);
1729 if (track_id3
->length
== 0 && track_id3
->filesize
== 0)
1731 logf("audio_finish_load_track: invalid metadata");
1733 /* Invalid metadata */
1734 bufclose(tracks
[track_widx
].id3_hid
);
1735 tracks
[track_widx
].id3_hid
= -1;
1737 /* Skip invalid entry from playlist. */
1738 playlist_skip_entry(NULL
, last_peek_offset
--);
1740 /* load next track */
1741 LOGFQUEUE("audio > audio Q_AUDIO_FILL_BUFFER %d", (int)start_play
);
1742 queue_post(&audio_queue
, Q_AUDIO_FILL_BUFFER
, start_play
);
1747 #ifdef HAVE_ALBUMART
1748 if (tracks
[track_widx
].aa_hid
< 0 && gui_sync_wps_uses_albumart())
1750 char aa_path
[MAX_PATH
];
1751 if (find_albumart(track_id3
, aa_path
, sizeof(aa_path
)))
1752 tracks
[track_widx
].aa_hid
= bufopen(aa_path
, 0, TYPE_BITMAP
);
1756 /* Load the codec. */
1757 if (!audio_loadcodec(start_play
))
1759 if (tracks
[track_widx
].codec_hid
== ERR_BUFFER_FULL
)
1761 /* No space for codec on buffer, not an error */
1765 /* This is an error condition, either no codec was found, or reading
1766 * the codec file failed part way through, either way, skip the track */
1767 snprintf(msgbuf
, sizeof(msgbuf
)-1, "No codec for: %s", track_id3
->path
);
1768 /* We should not use gui_syncplash from audio thread! */
1769 gui_syncsplash(HZ
*2, msgbuf
);
1770 /* Skip invalid entry from playlist. */
1771 playlist_skip_entry(NULL
, last_peek_offset
);
1775 track_id3
->elapsed
= 0;
1776 offset
= track_id3
->offset
;
1778 enum data_type type
= TYPE_PACKET_AUDIO
;
1780 switch (track_id3
->codectype
) {
1785 file_offset
= offset
;
1786 track_id3
->offset
= offset
;
1792 file_offset
= offset
;
1793 track_id3
->offset
= offset
;
1794 track_id3
->elapsed
= track_id3
->length
/ 2;
1798 case AFMT_OGG_VORBIS
:
1808 track_id3
->offset
= offset
;
1814 logf("Loading atomic %d",track_id3
->codectype
);
1815 type
= TYPE_ATOMIC_AUDIO
;
1819 logf("alt:%s", track_id3
->path
);
1821 if (file_offset
> AUDIO_REBUFFER_GUESS_SIZE
)
1822 file_offset
-= AUDIO_REBUFFER_GUESS_SIZE
;
1823 else if (track_id3
->first_frame_offset
)
1824 file_offset
= track_id3
->first_frame_offset
;
1828 tracks
[track_widx
].audio_hid
= bufopen(track_id3
->path
, file_offset
, type
);
1830 if (tracks
[track_widx
].audio_hid
< 0)
1833 /* All required data is now available for the codec. */
1834 tracks
[track_widx
].taginfo_ready
= true;
1838 ci
.curpos
=file_offset
;
1839 buf_request_buffer_handle(tracks
[track_widx
].audio_hid
);
1842 track_widx
= (track_widx
+ 1) & MAX_TRACK_MASK
;
1844 send_event(PLAYBACK_EVENT_TRACK_BUFFER
, track_id3
);
1846 /* load next track */
1847 LOGFQUEUE("audio > audio Q_AUDIO_FILL_BUFFER");
1848 queue_post(&audio_queue
, Q_AUDIO_FILL_BUFFER
, 0);
1853 static void audio_fill_file_buffer(bool start_play
, size_t offset
)
1855 bool had_next_track
= audio_next_track() != NULL
;
1857 filling
= STATE_FILLING
;
1858 trigger_cpu_boost();
1860 /* No need to rebuffer if there are track skips pending. */
1861 if (ci
.new_track
!= 0)
1864 /* Must reset the buffer before use if trashed or voice only - voice
1865 file size shouldn't have changed so we can go straight from
1866 BUFFER_STATE_VOICED_ONLY to BUFFER_STATE_INITIALIZED */
1867 if (buffer_state
!= BUFFER_STATE_INITIALIZED
)
1868 audio_reset_buffer();
1870 logf("Starting buffer fill");
1873 audio_clear_track_entries();
1875 /* Save the current resume position once. */
1876 playlist_update_resume_info(audio_current_track());
1878 audio_load_track(offset
, start_play
);
1880 if (!had_next_track
&& audio_next_track())
1881 track_changed
= true;
1884 static void audio_rebuffer(void)
1886 logf("Forcing rebuffer");
1888 clear_track_info(CUR_TI
);
1890 /* Reset track pointers */
1891 track_widx
= track_ridx
;
1892 audio_clear_track_entries();
1894 /* Fill the buffer */
1895 last_peek_offset
= -1;
1898 if (!CUR_TI
->taginfo_ready
)
1899 memset(&curtrack_id3
, 0, sizeof(struct mp3entry
));
1901 audio_fill_file_buffer(false, 0);
1904 /* Called on request from the codec to get a new track. This is the codec part
1905 of the track transition. */
1906 static int audio_check_new_track(void)
1908 int track_count
= audio_track_count();
1909 int old_track_ridx
= track_ridx
;
1913 /* Now it's good time to send track finish events. */
1914 send_event(PLAYBACK_EVENT_TRACK_FINISH
, &curtrack_id3
);
1918 if (playlist_next_dir(ci
.new_track
))
1926 LOGFQUEUE("audio >|= codec Q_CODEC_REQUEST_FAILED");
1927 return Q_CODEC_REQUEST_FAILED
;
1934 /* If the playlist isn't that big */
1937 while (!playlist_check(ci
.new_track
))
1939 if (ci
.new_track
>= 0)
1941 LOGFQUEUE("audio >|= codec Q_CODEC_REQUEST_FAILED");
1942 return Q_CODEC_REQUEST_FAILED
;
1948 /* Update the playlist */
1949 last_peek_offset
-= ci
.new_track
;
1951 if (playlist_next(ci
.new_track
) < 0)
1953 LOGFQUEUE("audio >|= codec Q_CODEC_REQUEST_FAILED");
1954 return Q_CODEC_REQUEST_FAILED
;
1960 new_playlist
= false;
1963 /* Save the track metadata to allow the WPS to display it
1964 while PCM finishes playing that track */
1965 copy_mp3entry(&prevtrack_id3
, &curtrack_id3
);
1967 /* Update the main buffer copy of the track metadata with the one
1968 the codec has been using (for the unbuffer callbacks) */
1969 if (CUR_TI
->id3_hid
>= 0)
1970 copy_mp3entry(bufgetid3(CUR_TI
->id3_hid
), &curtrack_id3
);
1972 /* Save a pointer to the old track to allow later clearing */
1975 for (i
= 0; i
< ci
.new_track
; i
++)
1977 idx
= (track_ridx
+ i
) & MAX_TRACK_MASK
;
1978 struct mp3entry
*id3
= bufgetid3(tracks
[idx
].id3_hid
);
1979 ssize_t offset
= buf_handle_offset(tracks
[idx
].audio_hid
);
1980 if (!id3
|| offset
< 0 || (unsigned)offset
> id3
->first_frame_offset
)
1982 /* We don't have all the audio data for that track, so clear it,
1983 but keep the metadata. */
1984 if (tracks
[idx
].audio_hid
>= 0 && bufclose(tracks
[idx
].audio_hid
))
1986 tracks
[idx
].audio_hid
= -1;
1987 tracks
[idx
].filesize
= 0;
1992 /* Move to the new track */
1993 track_ridx
= (track_ridx
+ ci
.new_track
) & MAX_TRACK_MASK
;
1995 buf_set_base_handle(CUR_TI
->audio_hid
);
1999 wps_offset
= -ci
.new_track
;
2000 track_changed
= true;
2003 /* If it is not safe to even skip this many track entries */
2004 if (ci
.new_track
>= track_count
|| ci
.new_track
<= track_count
- MAX_TRACK
)
2011 forward
= ci
.new_track
> 0;
2014 /* If the target track is clearly not in memory */
2015 if (CUR_TI
->filesize
== 0 || !CUR_TI
->taginfo_ready
)
2021 /* When skipping backwards, it is possible that we've found a track that's
2022 * buffered, but which is around the track-wrap and therefore not the track
2023 * we are looking for */
2026 int cur_idx
= track_ridx
;
2027 bool taginfo_ready
= true;
2028 /* We've wrapped the buffer backwards if new > old */
2029 bool wrap
= track_ridx
> old_track_ridx
;
2033 cur_idx
= (cur_idx
+ 1) & MAX_TRACK_MASK
;
2035 /* if we've advanced past the wrap when cur_idx is zeroed */
2039 /* if we aren't still on the wrap and we've caught the old track */
2040 if (!(wrap
|| cur_idx
< old_track_ridx
))
2043 /* If we hit a track in between without valid tag info, bail */
2044 if (!tracks
[cur_idx
].taginfo_ready
)
2046 taginfo_ready
= false;
2057 audio_update_trackinfo();
2058 LOGFQUEUE("audio >|= codec Q_CODEC_REQUEST_COMPLETE");
2059 return Q_CODEC_REQUEST_COMPLETE
;
2062 unsigned long audio_prev_elapsed(void)
2064 return prev_track_elapsed
;
2067 static void audio_stop_codec_flush(void)
2069 ci
.stop_codec
= true;
2072 while (audio_codec_loaded
)
2075 /* If the audio codec is not loaded any more, and the audio is still
2076 * playing, it is now and _only_ now safe to call this function from the
2078 if (pcm_is_playing())
2081 pcmbuf_queue_clear();
2083 pcmbuf_pause(paused
);
2086 static void audio_stop_playback(void)
2088 /* If we were playing, save resume information */
2091 struct mp3entry
*id3
= NULL
;
2095 /* Set this early, the outside code yields and may allow the codec
2096 to try to wait for a reply on a buffer wait */
2097 ci
.stop_codec
= true;
2098 id3
= audio_current_track();
2101 /* Save the current playing spot, or NULL if the playlist has ended */
2102 playlist_update_resume_info(id3
);
2104 /* TODO: Create auto bookmark too? */
2106 prev_track_elapsed
= curtrack_id3
.elapsed
;
2108 remove_event(EVENT_BUFFER_LOW
, buffering_low_buffer_callback
);
2112 audio_stop_codec_flush();
2115 filling
= STATE_IDLE
;
2117 /* Mark all entries null. */
2118 audio_clear_track_entries();
2120 /* Close all tracks */
2121 audio_release_tracks();
2123 memset(&curtrack_id3
, 0, sizeof(struct mp3entry
));
2126 static void audio_play_start(size_t offset
)
2130 #if INPUT_SRC_CAPS != 0
2131 audio_set_input_source(AUDIO_SRC_PLAYBACK
, SRCF_PLAYBACK
);
2132 audio_set_output_source(AUDIO_SRC_PLAYBACK
);
2135 /* Wait for any previously playing audio to flush - TODO: Not necessary? */
2137 audio_stop_codec_flush();
2139 track_changed
= true;
2147 sound_set_volume(global_settings
.volume
);
2148 track_widx
= track_ridx
= 0;
2150 /* Clear all track entries. */
2151 for (i
= 0; i
< MAX_TRACK
; i
++) {
2152 clear_track_info(&tracks
[i
]);
2155 last_peek_offset
= -1;
2157 /* Officially playing */
2158 queue_reply(&audio_queue
, 1);
2160 #ifndef HAVE_FLASH_STORAGE
2161 set_filebuf_watermark(buffer_margin
, 0);
2164 audio_fill_file_buffer(true, offset
);
2166 add_event(EVENT_BUFFER_LOW
, false, buffering_low_buffer_callback
);
2168 LOGFQUEUE("audio > audio Q_AUDIO_TRACK_CHANGED");
2169 queue_post(&audio_queue
, Q_AUDIO_TRACK_CHANGED
, 0);
2173 /* Invalidates all but currently playing track. */
2174 static void audio_invalidate_tracks(void)
2176 if (audio_have_tracks())
2178 last_peek_offset
= 0;
2179 track_widx
= track_ridx
;
2181 /* Mark all other entries null (also buffered wrong metadata). */
2182 audio_clear_track_entries();
2184 track_widx
= (track_widx
+ 1) & MAX_TRACK_MASK
;
2186 audio_fill_file_buffer(false, 0);
2190 static void audio_new_playlist(void)
2192 /* Prepare to start a new fill from the beginning of the playlist */
2193 last_peek_offset
= -1;
2194 if (audio_have_tracks())
2197 skipped_during_pause
= true;
2198 track_widx
= track_ridx
;
2199 audio_clear_track_entries();
2201 track_widx
= (track_widx
+ 1) & MAX_TRACK_MASK
;
2203 /* Mark the current track as invalid to prevent skipping back to it */
2204 CUR_TI
->taginfo_ready
= false;
2207 /* Signal the codec to initiate a track change forward */
2208 new_playlist
= true;
2211 /* Officially playing */
2212 queue_reply(&audio_queue
, 1);
2214 audio_fill_file_buffer(false, 0);
2217 /* Called on manual track skip */
2218 static void audio_initiate_track_change(long direction
)
2220 logf("audio_initiate_track_change(%ld)", direction
);
2222 ci
.new_track
+= direction
;
2223 wps_offset
-= direction
;
2225 skipped_during_pause
= true;
2228 /* Called on manual dir skip */
2229 static void audio_initiate_dir_change(long direction
)
2232 ci
.new_track
= direction
;
2234 skipped_during_pause
= true;
2237 /* Called when PCM track change is complete */
2238 static void audio_finalise_track_change(void)
2240 logf("audio_finalise_track_change");
2245 automatic_skip
= false;
2247 /* Invalidate prevtrack_id3 */
2248 prevtrack_id3
.path
[0] = 0;
2250 if (prev_ti
&& prev_ti
->audio_hid
< 0)
2252 /* No audio left so we clear all the track info. */
2253 clear_track_info(prev_ti
);
2256 if (prev_ti
&& prev_ti
->id3_hid
>= 0)
2258 /* Reset the elapsed time to force the progressbar to be empty if
2259 the user skips back to this track */
2260 bufgetid3(prev_ti
->id3_hid
)->elapsed
= 0;
2264 send_event(PLAYBACK_EVENT_TRACK_CHANGE
, &curtrack_id3
);
2266 track_changed
= true;
2267 playlist_update_resume_info(audio_current_track());
2271 * Layout audio buffer as follows - iram buffer depends on target:
2272 * [|SWAP:iram][|TALK]|MALLOC|FILE|GUARD|PCM|[SWAP:dram[|iram]|]
2274 static void audio_reset_buffer(void)
2276 /* see audio_get_recording_buffer if this is modified */
2277 logf("audio_reset_buffer");
2279 /* If the setup of anything allocated before the file buffer is
2280 changed, do check the adjustments after the buffer_alloc call
2281 as it will likely be affected and need sliding over */
2283 /* Initially set up file buffer as all space available */
2284 malloc_buf
= audiobuf
+ talk_get_bufsize();
2285 /* Align the malloc buf to line size. Especially important to cf
2286 targets that do line reads/writes. */
2287 malloc_buf
= (unsigned char *)(((uintptr_t)malloc_buf
+ 15) & ~15);
2288 filebuf
= malloc_buf
+ MALLOC_BUFSIZE
; /* filebuf line align implied */
2289 filebuflen
= audiobufend
- filebuf
;
2293 /* Subtract whatever the pcm buffer says it used plus the guard buffer */
2294 filebuflen
-= pcmbuf_init(filebuf
+ filebuflen
) + GUARD_BUFSIZE
;
2296 /* Make sure filebuflen is a longword multiple after adjustment - filebuf
2297 will already be line aligned */
2300 buffering_reset(filebuf
, filebuflen
);
2302 /* Clear any references to the file buffer */
2303 buffer_state
= BUFFER_STATE_INITIALIZED
;
2305 #if defined(ROCKBOX_HAS_LOGF) && defined(LOGF_ENABLE)
2306 /* Make sure everything adds up - yes, some info is a bit redundant but
2307 aids viewing and the sumation of certain variables should add up to
2308 the location of others. */
2311 const unsigned char *pcmbuf
= pcmbuf_get_meminfo(&pcmbufsize
);
2312 logf("mabuf: %08X", (unsigned)malloc_buf
);
2313 logf("mabufe: %08X", (unsigned)(malloc_buf
+ MALLOC_BUFSIZE
));
2314 logf("fbuf: %08X", (unsigned)filebuf
);
2315 logf("fbufe: %08X", (unsigned)(filebuf
+ filebuflen
));
2316 logf("gbuf: %08X", (unsigned)(filebuf
+ filebuflen
));
2317 logf("gbufe: %08X", (unsigned)(filebuf
+ filebuflen
+ GUARD_BUFSIZE
));
2318 logf("pcmb: %08X", (unsigned)pcmbuf
);
2319 logf("pcmbe: %08X", (unsigned)(pcmbuf
+ pcmbufsize
));
2324 static void audio_thread(void)
2326 struct queue_event ev
;
2330 audio_thread_ready
= true;
2334 if (filling
!= STATE_FILLING
) {
2338 if (!pcmbuf_queue_scan(&ev
))
2339 queue_wait_w_tmo(&audio_queue
, &ev
, HZ
/2);
2343 case Q_AUDIO_FILL_BUFFER
:
2344 LOGFQUEUE("audio < Q_AUDIO_FILL_BUFFER %d", (int)ev
.data
);
2345 audio_fill_file_buffer((bool)ev
.data
, 0);
2348 case Q_AUDIO_FINISH_LOAD
:
2349 LOGFQUEUE("audio < Q_AUDIO_FINISH_LOAD");
2350 audio_finish_load_track();
2354 LOGFQUEUE("audio < Q_AUDIO_PLAY");
2355 if (playing
&& ev
.data
<= 0)
2356 audio_new_playlist();
2359 audio_stop_playback();
2360 audio_play_start((size_t)ev
.data
);
2365 LOGFQUEUE("audio < Q_AUDIO_STOP");
2367 audio_stop_playback();
2369 queue_clear(&audio_queue
);
2373 LOGFQUEUE("audio < Q_AUDIO_PAUSE");
2374 if (!(bool) ev
.data
&& skipped_during_pause
&& !pcmbuf_is_crossfade_active())
2375 pcmbuf_play_stop(); /* Flush old track on resume after skip */
2376 skipped_during_pause
= false;
2379 pcmbuf_pause((bool)ev
.data
);
2380 paused
= (bool)ev
.data
;
2384 LOGFQUEUE("audio < Q_AUDIO_SKIP");
2385 audio_initiate_track_change((long)ev
.data
);
2388 case Q_AUDIO_PRE_FF_REWIND
:
2389 LOGFQUEUE("audio < Q_AUDIO_PRE_FF_REWIND");
2395 case Q_AUDIO_FF_REWIND
:
2396 LOGFQUEUE("audio < Q_AUDIO_FF_REWIND");
2401 /* An automatic track skip is in progress. Finalize it,
2402 then go back to the previous track */
2403 audio_finalise_track_change();
2406 ci
.seek_time
= (long)ev
.data
+1;
2409 case Q_AUDIO_CHECK_NEW_TRACK
:
2410 LOGFQUEUE("audio < Q_AUDIO_CHECK_NEW_TRACK");
2411 queue_reply(&audio_queue
, audio_check_new_track());
2414 case Q_AUDIO_DIR_SKIP
:
2415 LOGFQUEUE("audio < Q_AUDIO_DIR_SKIP");
2416 audio_initiate_dir_change(ev
.data
);
2420 LOGFQUEUE("audio < Q_AUDIO_FLUSH");
2421 audio_invalidate_tracks();
2424 case Q_AUDIO_TRACK_CHANGED
:
2425 /* PCM track change done */
2426 LOGFQUEUE("audio < Q_AUDIO_TRACK_CHANGED");
2427 audio_finalise_track_change();
2431 case SYS_USB_CONNECTED
:
2432 LOGFQUEUE("audio < SYS_USB_CONNECTED");
2434 audio_stop_playback();
2435 #ifdef PLAYBACK_VOICE
2438 usb_acknowledge(SYS_USB_CONNECTED_ACK
);
2439 usb_wait_for_disconnect(&audio_queue
);
2441 /* Mark all entries null. */
2442 audio_clear_track_entries();
2444 /* release tracks to make sure all handles are closed */
2445 audio_release_tracks();
2450 LOGFQUEUE_SYS_TIMEOUT("audio < SYS_TIMEOUT");
2454 LOGFQUEUE("audio < default");
2460 /* Initialize the audio system - called from init() in main.c.
2461 * Last function because of all the references to internal symbols
2463 void audio_init(void)
2465 struct thread_entry
*audio_thread_p
;
2467 /* Can never do this twice */
2468 if (audio_is_initialized
)
2470 logf("audio: already initialized");
2474 logf("audio: initializing");
2476 /* Initialize queues before giving control elsewhere in case it likes
2477 to send messages. Thread creation will be delayed however so nothing
2478 starts running until ready if something yields such as talk_init. */
2479 queue_init(&audio_queue
, true);
2480 queue_init(&codec_queue
, false);
2481 queue_init(&pcmbuf_queue
, false);
2485 /* Initialize codec api. */
2486 ci
.read_filebuf
= codec_filebuf_callback
;
2487 ci
.pcmbuf_insert
= codec_pcmbuf_insert_callback
;
2488 ci
.get_codec_memory
= codec_get_memory_callback
;
2489 ci
.request_buffer
= codec_request_buffer_callback
;
2490 ci
.advance_buffer
= codec_advance_buffer_callback
;
2491 ci
.advance_buffer_loc
= codec_advance_buffer_loc_callback
;
2492 ci
.request_next_track
= codec_request_next_track_callback
;
2493 ci
.seek_buffer
= codec_seek_buffer_callback
;
2494 ci
.seek_complete
= codec_seek_complete_callback
;
2495 ci
.set_elapsed
= codec_set_elapsed_callback
;
2496 ci
.set_offset
= codec_set_offset_callback
;
2497 ci
.configure
= codec_configure_callback
;
2498 ci
.discard_codec
= codec_discard_codec_callback
;
2499 ci
.dsp
= (struct dsp_config
*)dsp_configure(NULL
, DSP_MYDSP
,
2502 /* initialize the buffer */
2505 /* audio_reset_buffer must to know the size of voice buffer so init
2509 codec_thread_p
= create_thread(
2510 codec_thread
, codec_stack
, sizeof(codec_stack
),
2511 CREATE_THREAD_FROZEN
,
2512 codec_thread_name
IF_PRIO(, PRIORITY_PLAYBACK
)
2515 queue_enable_queue_send(&codec_queue
, &codec_queue_sender_list
,
2518 audio_thread_p
= create_thread(audio_thread
, audio_stack
,
2519 sizeof(audio_stack
), CREATE_THREAD_FROZEN
,
2520 audio_thread_name
IF_PRIO(, PRIORITY_USER_INTERFACE
)
2523 queue_enable_queue_send(&audio_queue
, &audio_queue_sender_list
,
2526 #ifdef PLAYBACK_VOICE
2527 voice_thread_init();
2530 /* Set crossfade setting for next buffer init which should be about... */
2531 pcmbuf_crossfade_enable(global_settings
.crossfade
);
2533 /* initialize the buffering system */
2536 /* ...now! Set up the buffers */
2537 audio_reset_buffer();
2540 for(i
= 0; i
< MAX_TRACK
; i
++)
2542 tracks
[i
].audio_hid
= -1;
2543 tracks
[i
].id3_hid
= -1;
2544 tracks
[i
].codec_hid
= -1;
2545 #ifdef HAVE_ALBUMART
2546 tracks
[i
].aa_hid
= -1;
2550 add_event(EVENT_HANDLE_REBUFFER
, false, buffering_handle_rebuffer_callback
);
2551 add_event(EVENT_HANDLE_FINISHED
, false, buffering_handle_finished_callback
);
2553 /* Probably safe to say */
2554 audio_is_initialized
= true;
2556 sound_settings_apply();
2557 #ifndef HAVE_FLASH_STORAGE
2558 audio_set_buffer_margin(global_settings
.buffer_margin
);
2561 /* it's safe to let the threads run now */
2562 #ifdef PLAYBACK_VOICE
2563 voice_thread_resume();
2565 thread_thaw(codec_thread_p
);
2566 thread_thaw(audio_thread_p
);
2570 void audio_wait_for_init(void)
2572 /* audio thread will only set this once after it finished the final
2573 * audio hardware init so this little construct is safe - even
2575 while (!audio_thread_ready
)