1 /***************************************************************************
3 * Open \______ \ ____ ____ | | _\_ |__ _______ ___
4 * Source | _// _ \_/ ___\| |/ /| __ \ / _ \ \/ /
5 * Jukebox | | ( <_> ) \___| < | \_\ ( <_> > < <
6 * Firmware |____|_ /\____/ \___ >__|_ \|___ /\____/__/\_ \
10 * Copyright (C) 2005 Miika Pekkarinen
12 * All files in this archive are subject to the GNU General Public License.
13 * See the file COPYING in the source tree root for full license agreement.
15 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
16 * KIND, either express or implied.
18 ****************************************************************************/
20 /* TODO: Pause should be handled in here, rather than PCMBUF so that voice can
21 * play whilst audio is paused */
43 #include "buffering.h"
45 #include "voice_thread.h"
46 #include "mp3_playback.h"
61 #ifdef HAVE_LCD_BITMAP
63 #include "peakmeter.h"
74 #include "ata_idle_notify.h"
77 #include "recording.h"
81 #define PLAYBACK_VOICE
83 /* default point to start buffer refill */
84 #define AUDIO_DEFAULT_WATERMARK (1024*512)
85 /* amount of guess-space to allow for codecs that must hunt and peck
86 * for their correct seeek target, 32k seems a good size */
87 #define AUDIO_REBUFFER_GUESS_SIZE (1024*32)
89 /* Define LOGF_ENABLE to enable logf output in this file */
90 /*#define LOGF_ENABLE*/
93 /* macros to enable logf for queues
94 logging on SYS_TIMEOUT can be disabled */
96 /* Define this for logf output of all queuing except SYS_TIMEOUT */
97 #define PLAYBACK_LOGQUEUES
98 /* Define this to logf SYS_TIMEOUT messages */
99 /*#define PLAYBACK_LOGQUEUES_SYS_TIMEOUT*/
102 #ifdef PLAYBACK_LOGQUEUES
103 #define LOGFQUEUE logf
105 #define LOGFQUEUE(...)
108 #ifdef PLAYBACK_LOGQUEUES_SYS_TIMEOUT
109 #define LOGFQUEUE_SYS_TIMEOUT logf
111 #define LOGFQUEUE_SYS_TIMEOUT(...)
115 /* Define one constant that includes recording related functionality */
116 #if defined(HAVE_RECORDING) && !defined(SIMULATOR)
117 #define AUDIO_HAVE_RECORDING
126 Q_AUDIO_PRE_FF_REWIND
,
128 Q_AUDIO_CHECK_NEW_TRACK
,
130 Q_AUDIO_TRACK_CHANGED
,
135 Q_CODEC_REQUEST_COMPLETE
,
136 Q_CODEC_REQUEST_FAILED
,
141 #ifdef AUDIO_HAVE_RECORDING
148 STATE_IDLE
, /* audio is stopped: nothing to do */
149 STATE_FILLING
, /* adding tracks to the buffer */
150 STATE_FULL
, /* can't add any more tracks */
151 STATE_FINISHED
, /* all remaining tracks have been added */
154 /* As defined in plugins/lib/xxx2wav.h */
156 #define MALLOC_BUFSIZE (512*1024)
157 #define GUARD_BUFSIZE (32*1024)
159 #define MALLOC_BUFSIZE (100*1024)
160 #define GUARD_BUFSIZE (8*1024)
163 /* As defined in plugin.lds */
165 #define CODEC_IRAM_ORIGIN ((unsigned char *)0x4000c000)
166 #define CODEC_IRAM_SIZE ((size_t)0xc000)
167 #elif defined(IAUDIO_X5) || defined(IAUDIO_M5)
168 #define CODEC_IRAM_ORIGIN ((unsigned char *)0x10010000)
169 #define CODEC_IRAM_SIZE ((size_t)0x10000)
171 #define CODEC_IRAM_ORIGIN ((unsigned char *)0x1000c000)
172 #define CODEC_IRAM_SIZE ((size_t)0xc000)
175 bool audio_is_initialized
= false;
176 static bool audio_thread_ready SHAREDBSS_ATTR
= false;
178 /* Variables are commented with the threads that use them: *
179 * A=audio, C=codec, V=voice. A suffix of - indicates that *
180 * the variable is read but not updated on that thread. */
181 /* TBD: Split out "audio" and "playback" (ie. calling) threads */
183 /* Main state control */
184 static volatile bool audio_codec_loaded SHAREDBSS_ATTR
= false; /* Codec loaded? (C/A-) */
185 static volatile bool playing SHAREDBSS_ATTR
= false; /* Is audio playing? (A) */
186 static volatile bool paused SHAREDBSS_ATTR
= false; /* Is audio paused? (A/C-) */
188 /* Ring buffer where compressed audio and codecs are loaded */
189 static unsigned char *filebuf
= NULL
; /* Start of buffer (A/C-) */
190 static unsigned char *malloc_buf
= NULL
; /* Start of malloc buffer (A/C-) */
191 /* FIXME: make filebuflen static */
192 size_t filebuflen
= 0; /* Size of buffer (A/C-) */
193 /* FIXME: make buf_ridx (C/A-) */
195 /* Possible arrangements of the buffer */
196 #define BUFFER_STATE_TRASHED -1 /* trashed; must be reset */
197 #define BUFFER_STATE_INITIALIZED 0 /* voice+audio OR audio-only */
198 #define BUFFER_STATE_VOICED_ONLY 1 /* voice-only */
199 static int buffer_state
= BUFFER_STATE_TRASHED
; /* Buffer state */
201 /* Used to keep the WPS up-to-date during track transtition */
202 static struct mp3entry prevtrack_id3
;
204 /* Used to provide the codec with a pointer */
205 static struct mp3entry curtrack_id3
;
207 /* Used to make next track info available while playing last track on buffer */
208 static struct mp3entry lasttrack_id3
;
210 /* Track info structure about songs in the file buffer (A/C-) */
212 int audio_hid
; /* The ID for the track's buffer handle */
213 int id3_hid
; /* The ID for the track's metadata handle */
214 int codec_hid
; /* The ID for the track's codec handle */
216 int aa_hid
; /* The ID for the track's album art handle */
219 size_t filesize
; /* File total length */
221 bool taginfo_ready
; /* Is metadata read */
224 static struct track_info tracks
[MAX_TRACK
];
225 static volatile int track_ridx
= 0; /* Track being decoded (A/C-) */
226 static int track_widx
= 0; /* Track being buffered (A) */
228 #define CUR_TI (&tracks[track_ridx]) /* Playing track info pointer (A/C-) */
229 static struct track_info
*prev_ti
= NULL
; /* Pointer to the previously played
232 /* Set by the audio thread when the current track information has updated
233 * and the WPS may need to update its cached information */
234 static bool track_changed
= false;
236 /* Information used only for filling the buffer */
237 /* Playlist steps from playing track to next track to be buffered (A) */
238 static int last_peek_offset
= 0;
240 /* Scrobbler support */
241 static unsigned long prev_track_elapsed
= 0; /* Previous track elapsed time (C/A-)*/
243 static enum filling_state filling
;
245 /* Track change controls */
246 static bool automatic_skip
= false; /* Who initiated in-progress skip? (C/A-) */
247 static bool dir_skip
= false; /* Is a directory skip pending? (A) */
248 static bool new_playlist
= false; /* Are we starting a new playlist? (A) */
249 static int wps_offset
= 0; /* Pending track change offset, to keep WPS responsive (A) */
250 static bool skipped_during_pause
= false; /* Do we need to clear the PCM buffer when playback resumes (A) */
252 static bool start_play_g
= false; /* Used by audio_load_track to notify
253 audio_finish_load_track about start_play */
255 /* Set to true if the codec thread should send an audio stop request
256 * (typically because the end of the playlist has been reached).
258 static bool codec_requested_stop
= false;
260 static size_t buffer_margin
= 0; /* Buffer margin aka anti-skip buffer (A/C-) */
262 /* Multiple threads */
263 /* Set the watermark to trigger buffer fill (A/C) FIXME */
264 static void set_filebuf_watermark(int seconds
, size_t max
);
267 static struct event_queue audio_queue SHAREDBSS_ATTR
;
268 static struct queue_sender_list audio_queue_sender_list SHAREDBSS_ATTR
;
269 static long audio_stack
[(DEFAULT_STACK_SIZE
+ 0x1000)/sizeof(long)];
270 static const char audio_thread_name
[] = "audio";
272 static void audio_thread(void);
273 static void audio_initiate_track_change(long direction
);
274 static bool audio_have_tracks(void);
275 static void audio_reset_buffer(void);
278 extern struct codec_api ci
;
279 static struct event_queue codec_queue SHAREDBSS_ATTR
;
280 static struct queue_sender_list codec_queue_sender_list
;
281 static long codec_stack
[(DEFAULT_STACK_SIZE
+ 0x2000)/sizeof(long)]
283 static const char codec_thread_name
[] = "codec";
284 struct thread_entry
*codec_thread_p
; /* For modifying thread priority later. */
286 /* PCM buffer messaging */
287 static struct event_queue pcmbuf_queue SHAREDBSS_ATTR
;
289 /* Function to be called by pcm buffer callbacks.
290 * Permissible Context(s): Audio interrupt
292 static void pcmbuf_callback_queue_post(long id
, intptr_t data
)
294 /* No lock since we're already in audio interrupt context */
295 queue_post(&pcmbuf_queue
, id
, data
);
298 /* Scan the pcmbuf queue and return true if a message pulled.
299 * Permissible Context(s): Thread
301 static bool pcmbuf_queue_scan(struct queue_event
*ev
)
303 if (!queue_empty(&pcmbuf_queue
))
305 /* Transfer message to audio queue */
307 /* Pull message - never, ever any blocking call! */
308 queue_wait_w_tmo(&pcmbuf_queue
, ev
, 0);
316 /* Clear the pcmbuf queue of messages
317 * Permissible Context(s): Thread
319 static void pcmbuf_queue_clear(void)
322 queue_clear(&pcmbuf_queue
);
326 /* --- Helper functions --- */
328 static struct mp3entry
*bufgetid3(int handle_id
)
333 struct mp3entry
*id3
;
334 ssize_t ret
= bufgetdata(handle_id
, 0, (void *)&id3
);
336 if (ret
< 0 || ret
!= sizeof(struct mp3entry
))
342 static bool clear_track_info(struct track_info
*track
)
344 /* bufclose returns true if the handle is not found, or if it is closed
345 * successfully, so these checks are safe on non-existant handles */
349 if (track
->codec_hid
>= 0) {
350 if (bufclose(track
->codec_hid
))
351 track
->codec_hid
= -1;
356 if (track
->id3_hid
>= 0) {
357 if (bufclose(track
->id3_hid
))
363 if (track
->audio_hid
>= 0) {
364 if (bufclose(track
->audio_hid
))
365 track
->audio_hid
= -1;
371 if (track
->aa_hid
>= 0) {
372 if (bufclose(track
->aa_hid
))
380 track
->taginfo_ready
= false;
385 /* --- External interfaces --- */
387 /* This sends a stop message and the audio thread will dump all it's
388 subsequenct messages */
389 void audio_hard_stop(void)
392 LOGFQUEUE("audio >| audio Q_AUDIO_STOP: 1");
393 queue_send(&audio_queue
, Q_AUDIO_STOP
, 1);
394 #ifdef PLAYBACK_VOICE
399 bool audio_restore_playback(int type
)
403 case AUDIO_WANT_PLAYBACK
:
404 if (buffer_state
!= BUFFER_STATE_INITIALIZED
)
405 audio_reset_buffer();
407 case AUDIO_WANT_VOICE
:
408 if (buffer_state
== BUFFER_STATE_TRASHED
)
409 audio_reset_buffer();
416 unsigned char *audio_get_buffer(bool talk_buf
, size_t *buffer_size
)
418 unsigned char *buf
, *end
;
420 if (audio_is_initialized
)
424 /* else buffer_state will be BUFFER_STATE_TRASHED at this point */
426 if (buffer_size
== NULL
)
428 /* Special case for talk_init to use since it already knows it's
430 buffer_state
= BUFFER_STATE_TRASHED
;
434 if (talk_buf
|| buffer_state
== BUFFER_STATE_TRASHED
435 || !talk_voice_required())
437 logf("get buffer: talk, audio");
438 /* Ok to use everything from audiobuf to audiobufend - voice is loaded,
439 the talk buffer is not needed because voice isn't being used, or
440 could be BUFFER_STATE_TRASHED already. If state is
441 BUFFER_STATE_VOICED_ONLY, no problem as long as memory isn't written
442 without the caller knowing what's going on. Changing certain settings
443 may move it to a worse condition but the memory in use by something
444 else will remain undisturbed.
446 if (buffer_state
!= BUFFER_STATE_TRASHED
)
449 buffer_state
= BUFFER_STATE_TRASHED
;
457 /* Safe to just return this if already BUFFER_STATE_VOICED_ONLY or
458 still BUFFER_STATE_INITIALIZED */
459 /* Skip talk buffer and move pcm buffer to end to maximize available
460 contiguous memory - no audio running means voice will not need the
462 logf("get buffer: audio");
463 buf
= audiobuf
+ talk_get_bufsize();
464 end
= audiobufend
- pcmbuf_init(audiobufend
);
465 buffer_state
= BUFFER_STATE_VOICED_ONLY
;
468 *buffer_size
= end
- buf
;
473 #ifdef HAVE_RECORDING
474 unsigned char *audio_get_recording_buffer(size_t *buffer_size
)
476 /* Stop audio, voice and obtain all available buffer space */
480 unsigned char *end
= audiobufend
;
481 buffer_state
= BUFFER_STATE_TRASHED
;
482 *buffer_size
= end
- audiobuf
;
484 return (unsigned char *)audiobuf
;
487 bool audio_load_encoder(int afmt
)
490 const char *enc_fn
= get_codec_filename(afmt
| CODEC_TYPE_ENCODER
);
494 audio_remove_encoder();
495 ci
.enc_codec_loaded
= 0; /* clear any previous error condition */
497 LOGFQUEUE("codec > Q_ENCODER_LOAD_DISK");
498 queue_post(&codec_queue
, Q_ENCODER_LOAD_DISK
, (intptr_t)enc_fn
);
500 while (ci
.enc_codec_loaded
== 0)
503 logf("codec loaded: %d", ci
.enc_codec_loaded
);
505 return ci
.enc_codec_loaded
> 0;
510 } /* audio_load_encoder */
512 void audio_remove_encoder(void)
515 /* force encoder codec unload (if currently loaded) */
516 if (ci
.enc_codec_loaded
<= 0)
519 ci
.stop_encoder
= true;
520 while (ci
.enc_codec_loaded
> 0)
523 } /* audio_remove_encoder */
525 #endif /* HAVE_RECORDING */
528 int audio_current_aa_hid(void)
531 int offset
= ci
.new_track
+ wps_offset
;
533 cur_idx
= track_ridx
+ offset
;
534 cur_idx
&= MAX_TRACK_MASK
;
536 return tracks
[cur_idx
].aa_hid
;
540 struct mp3entry
* audio_current_track(void)
542 const char *filename
;
544 static struct mp3entry temp_id3
;
546 int offset
= ci
.new_track
+ wps_offset
;
548 cur_idx
= (track_ridx
+ offset
) & MAX_TRACK_MASK
;
550 if (cur_idx
== track_ridx
&& *curtrack_id3
.path
)
553 return &curtrack_id3
;
555 else if (offset
== -1 && *prevtrack_id3
.path
)
557 /* We're in a track transition. The codec has moved on to the nex track,
558 but the audio being played is still the same (now previous) track.
559 prevtrack_id3.elapsed is being updated in an ISR by
560 codec_pcmbuf_position_callback */
561 return &prevtrack_id3
;
563 else if (tracks
[cur_idx
].id3_hid
>= 0)
565 /* Get the ID3 metadata from the main buffer */
566 return bufgetid3(tracks
[cur_idx
].id3_hid
);
569 /* We didn't find the ID3 metadata, so we fill temp_id3 with the little info
570 we have and return that. */
572 memset(&temp_id3
, 0, sizeof(struct mp3entry
));
574 filename
= playlist_peek(0);
576 filename
= "No file!";
578 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
579 if (tagcache_fill_tags(&temp_id3
, filename
))
583 p
= strrchr(filename
, '/');
589 strncpy(temp_id3
.path
, p
, sizeof(temp_id3
.path
)-1);
590 temp_id3
.title
= &temp_id3
.path
[0];
595 struct mp3entry
* audio_next_track(void)
598 int offset
= ci
.new_track
+ wps_offset
;
600 if (!audio_have_tracks())
603 if (wps_offset
== -1 && *prevtrack_id3
.path
)
605 /* We're in a track transition. The next track for the WPS is the one
606 currently being decoded. */
607 return &curtrack_id3
;
610 next_idx
= (track_ridx
+ offset
+ 1) & MAX_TRACK_MASK
;
612 if (tracks
[next_idx
].id3_hid
>= 0)
613 return bufgetid3(tracks
[next_idx
].id3_hid
);
615 if (next_idx
== track_widx
)
617 /* The next track hasn't been buffered yet, so we return the static
618 version of its metadata. */
619 return &lasttrack_id3
;
625 bool audio_has_changed_track(void)
629 track_changed
= false;
636 void audio_play(long offset
)
640 #ifdef PLAYBACK_VOICE
641 /* Truncate any existing voice output so we don't have spelling
642 * etc. over the first part of the played track */
647 LOGFQUEUE("audio >| audio Q_AUDIO_PLAY: %ld", offset
);
648 /* Don't return until playback has actually started */
649 queue_send(&audio_queue
, Q_AUDIO_PLAY
, offset
);
652 void audio_stop(void)
655 LOGFQUEUE("audio >| audio Q_AUDIO_STOP");
656 /* Don't return until playback has actually stopped */
657 queue_send(&audio_queue
, Q_AUDIO_STOP
, 0);
660 void audio_pause(void)
662 LOGFQUEUE("audio >| audio Q_AUDIO_PAUSE");
663 /* Don't return until playback has actually paused */
664 queue_send(&audio_queue
, Q_AUDIO_PAUSE
, true);
667 void audio_resume(void)
669 LOGFQUEUE("audio >| audio Q_AUDIO_PAUSE resume");
670 /* Don't return until playback has actually resumed */
671 queue_send(&audio_queue
, Q_AUDIO_PAUSE
, false);
674 static void audio_skip(int direction
)
676 if (playlist_check(ci
.new_track
+ wps_offset
+ direction
))
678 if (global_settings
.beep
)
679 pcmbuf_beep(5000, 100, 2500*global_settings
.beep
);
681 LOGFQUEUE("audio > audio Q_AUDIO_SKIP %d", direction
);
682 queue_post(&audio_queue
, Q_AUDIO_SKIP
, direction
);
683 /* Update wps while our message travels inside deep playback queues. */
684 wps_offset
+= direction
;
685 track_changed
= true;
689 /* No more tracks. */
690 if (global_settings
.beep
)
691 pcmbuf_beep(1000, 100, 1000*global_settings
.beep
);
695 void audio_next(void)
700 void audio_prev(void)
705 void audio_next_dir(void)
707 LOGFQUEUE("audio > audio Q_AUDIO_DIR_SKIP 1");
708 queue_post(&audio_queue
, Q_AUDIO_DIR_SKIP
, 1);
711 void audio_prev_dir(void)
713 LOGFQUEUE("audio > audio Q_AUDIO_DIR_SKIP -1");
714 queue_post(&audio_queue
, Q_AUDIO_DIR_SKIP
, -1);
717 void audio_pre_ff_rewind(void)
719 LOGFQUEUE("audio > audio Q_AUDIO_PRE_FF_REWIND");
720 queue_post(&audio_queue
, Q_AUDIO_PRE_FF_REWIND
, 0);
723 void audio_ff_rewind(long newpos
)
725 LOGFQUEUE("audio > audio Q_AUDIO_FF_REWIND");
726 queue_post(&audio_queue
, Q_AUDIO_FF_REWIND
, newpos
);
729 void audio_flush_and_reload_tracks(void)
731 LOGFQUEUE("audio > audio Q_AUDIO_FLUSH");
732 queue_post(&audio_queue
, Q_AUDIO_FLUSH
, 0);
735 void audio_error_clear(void)
737 #ifdef AUDIO_HAVE_RECORDING
738 pcm_rec_error_clear();
742 int audio_status(void)
747 ret
|= AUDIO_STATUS_PLAY
;
750 ret
|= AUDIO_STATUS_PAUSE
;
752 #ifdef HAVE_RECORDING
753 /* Do this here for constitency with mpeg.c version */
754 ret
|= pcm_rec_status();
760 int audio_get_file_pos(void)
765 #ifndef HAVE_FLASH_STORAGE
766 void audio_set_buffer_margin(int setting
)
768 static const int lookup
[] = {5, 15, 30, 60, 120, 180, 300, 600};
769 buffer_margin
= lookup
[setting
];
770 logf("buffer margin: %ld", (long)buffer_margin
);
771 set_filebuf_watermark(buffer_margin
, 0);
775 /* Take necessary steps to enable or disable the crossfade setting */
776 void audio_set_crossfade(int enable
)
782 /* Tell it the next setting to use */
783 pcmbuf_crossfade_enable(enable
);
785 /* Return if size hasn't changed or this is too early to determine
786 which in the second case there's no way we could be playing
788 if (pcmbuf_is_same_size())
790 /* This function is a copout and just syncs some variables -
791 to be removed at a later date */
792 pcmbuf_crossfade_enable_finished();
797 was_playing
= playing
;
799 /* Playback has to be stopped before changing the buffer size */
802 /* Store the track resume position */
803 offset
= curtrack_id3
.offset
;
804 gui_syncsplash(0, str(LANG_RESTARTING_PLAYBACK
));
807 /* Blast it - audio buffer will have to be setup again next time
809 audio_get_buffer(true, &size
);
811 /* Restart playback if audio was running previously */
816 /* --- Routines called from multiple threads --- */
818 static void set_filebuf_watermark(int seconds
, size_t max
)
823 return; /* Audio buffers not yet set up */
825 bytes
= seconds
?MAX(curtrack_id3
.bitrate
* seconds
* (1000/8), max
):max
;
826 bytes
= MIN(bytes
, filebuflen
/ 2);
827 buf_set_watermark(bytes
);
830 const char *get_codec_filename(int cod_spec
)
834 #ifdef HAVE_RECORDING
835 /* Can choose decoder or encoder if one available */
836 int type
= cod_spec
& CODEC_TYPE_MASK
;
837 int afmt
= cod_spec
& CODEC_AFMT_MASK
;
839 if ((unsigned)afmt
>= AFMT_NUM_CODECS
)
840 type
= AFMT_UNKNOWN
| (type
& CODEC_TYPE_MASK
);
842 fname
= (type
== CODEC_TYPE_ENCODER
) ?
843 audio_formats
[afmt
].codec_enc_root_fn
:
844 audio_formats
[afmt
].codec_root_fn
;
847 (type
== CODEC_TYPE_ENCODER
) ? "Encoder" : "Decoder",
848 afmt
, fname
? fname
: "<unknown>");
849 #else /* !HAVE_RECORDING */
851 if ((unsigned)cod_spec
>= AFMT_NUM_CODECS
)
852 cod_spec
= AFMT_UNKNOWN
;
853 fname
= audio_formats
[cod_spec
].codec_root_fn
;
854 logf("Codec: %d - %s", cod_spec
, fname
? fname
: "<unknown>");
855 #endif /* HAVE_RECORDING */
858 } /* get_codec_filename */
860 /* --- Codec thread --- */
861 static bool codec_pcmbuf_insert_callback(
862 const void *ch1
, const void *ch2
, int count
)
864 const char *src
[2] = { ch1
, ch2
};
868 int out_count
= dsp_output_count(ci
.dsp
, count
);
872 /* Prevent audio from a previous track from playing */
873 if (ci
.new_track
|| ci
.stop_codec
)
876 while ((dest
= pcmbuf_request_buffer(&out_count
)) == NULL
)
880 if (ci
.seek_time
|| ci
.new_track
|| ci
.stop_codec
)
884 /* Get the real input_size for output_size bytes, guarding
885 * against resampling buffer overflows. */
886 inp_count
= dsp_input_count(ci
.dsp
, out_count
);
891 /* Input size has grown, no error, just don't write more than length */
892 if (inp_count
> count
)
895 out_count
= dsp_process(ci
.dsp
, dest
, src
, inp_count
);
900 pcmbuf_write_complete(out_count
);
906 } /* codec_pcmbuf_insert_callback */
908 static void* codec_get_memory_callback(size_t *size
)
910 *size
= MALLOC_BUFSIZE
;
914 /* Between the codec and PCM track change, we need to keep updating the
915 "elapsed" value of the previous (to the codec, but current to the
916 user/PCM/WPS) track, so that the progressbar reaches the end.
917 During that transition, the WPS will display prevtrack_id3. */
918 static void codec_pcmbuf_position_callback(size_t size
) ICODE_ATTR
;
919 static void codec_pcmbuf_position_callback(size_t size
)
921 /* This is called from an ISR, so be quick */
922 unsigned int time
= size
* 1000 / 4 / NATIVE_FREQUENCY
+
923 prevtrack_id3
.elapsed
;
925 if (time
>= prevtrack_id3
.length
)
927 pcmbuf_set_position_callback(NULL
);
928 prevtrack_id3
.elapsed
= prevtrack_id3
.length
;
931 prevtrack_id3
.elapsed
= time
;
934 static void codec_set_elapsed_callback(unsigned int value
)
936 unsigned int latency
;
940 #ifdef AB_REPEAT_ENABLE
941 ab_position_report(value
);
944 latency
= pcmbuf_get_latency();
946 curtrack_id3
.elapsed
= 0;
947 else if (value
- latency
> curtrack_id3
.elapsed
||
948 value
- latency
< curtrack_id3
.elapsed
- 2)
950 curtrack_id3
.elapsed
= value
- latency
;
954 static void codec_set_offset_callback(size_t value
)
956 unsigned int latency
;
961 latency
= pcmbuf_get_latency() * curtrack_id3
.bitrate
/ 8;
963 curtrack_id3
.offset
= 0;
965 curtrack_id3
.offset
= value
- latency
;
968 static void codec_advance_buffer_counters(size_t amount
)
970 bufadvance(CUR_TI
->audio_hid
, amount
);
974 /* copy up-to size bytes into ptr and return the actual size copied */
975 static size_t codec_filebuf_callback(void *ptr
, size_t size
)
979 if (ci
.stop_codec
|| !playing
)
982 copy_n
= bufread(CUR_TI
->audio_hid
, size
, ptr
);
984 /* Nothing requested OR nothing left */
988 /* Update read and other position pointers */
989 codec_advance_buffer_counters(copy_n
);
991 /* Return the actual amount of data copied to the buffer */
993 } /* codec_filebuf_callback */
995 static void* codec_request_buffer_callback(size_t *realsize
, size_t reqsize
)
997 size_t copy_n
= reqsize
;
1007 ret
= bufgetdata(CUR_TI
->audio_hid
, reqsize
, &ptr
);
1009 copy_n
= MIN((size_t)ret
, reqsize
);
1020 } /* codec_request_buffer_callback */
1022 static int get_codec_base_type(int type
)
1034 static void codec_advance_buffer_callback(size_t amount
)
1036 codec_advance_buffer_counters(amount
);
1037 codec_set_offset_callback(ci
.curpos
);
1040 static void codec_advance_buffer_loc_callback(void *ptr
)
1042 size_t amount
= buf_get_offset(CUR_TI
->audio_hid
, ptr
);
1043 codec_advance_buffer_callback(amount
);
1046 static void codec_seek_complete_callback(void)
1048 logf("seek_complete");
1049 if (pcm_is_paused())
1051 /* If this is not a seamless seek, clear the buffer */
1053 dsp_configure(ci
.dsp
, DSP_FLUSH
, 0);
1055 /* If playback was not 'deliberately' paused, unpause now */
1057 pcmbuf_pause(false);
1062 static bool codec_seek_buffer_callback(size_t newpos
)
1064 logf("codec_seek_buffer_callback");
1066 int ret
= bufseek(CUR_TI
->audio_hid
, newpos
);
1076 static void codec_configure_callback(int setting
, intptr_t value
)
1079 case CODEC_SET_FILEBUF_WATERMARK
:
1080 set_filebuf_watermark(buffer_margin
, value
);
1084 if (!dsp_configure(ci
.dsp
, setting
, value
))
1085 { logf("Illegal key:%d", setting
); }
1089 static void codec_track_changed(void)
1091 LOGFQUEUE("codec > audio Q_AUDIO_TRACK_CHANGED");
1092 queue_post(&audio_queue
, Q_AUDIO_TRACK_CHANGED
, 0);
1095 static void codec_pcmbuf_track_changed_callback(void)
1097 pcmbuf_set_position_callback(NULL
);
1098 pcmbuf_callback_queue_post(Q_AUDIO_TRACK_CHANGED
, 0);
1101 static void codec_discard_codec_callback(void)
1103 if (CUR_TI
->codec_hid
>= 0)
1105 bufclose(CUR_TI
->codec_hid
);
1106 CUR_TI
->codec_hid
= -1;
1110 static inline void codec_gapless_track_change(void)
1112 /* callback keeps the progress bar moving while the pcmbuf empties */
1113 pcmbuf_set_position_callback(codec_pcmbuf_position_callback
);
1114 /* set the pcmbuf callback for when the track really changes */
1115 pcmbuf_set_event_handler(codec_pcmbuf_track_changed_callback
);
1118 static inline void codec_crossfade_track_change(void)
1120 /* Initiate automatic crossfade mode */
1121 pcmbuf_crossfade_init(false);
1122 /* Notify the wps that the track change starts now */
1123 codec_track_changed();
1126 static void codec_track_skip_done(bool was_manual
)
1128 /* Manual track change (always crossfade or flush audio). */
1131 pcmbuf_crossfade_init(true);
1132 LOGFQUEUE("codec > audio Q_AUDIO_TRACK_CHANGED");
1133 queue_post(&audio_queue
, Q_AUDIO_TRACK_CHANGED
, 0);
1135 /* Automatic track change w/crossfade, if not in "Track Skip Only" mode. */
1136 else if (pcmbuf_is_crossfade_enabled() && !pcmbuf_is_crossfade_active()
1137 && global_settings
.crossfade
!= CROSSFADE_ENABLE_TRACKSKIP
)
1139 if (global_settings
.crossfade
== CROSSFADE_ENABLE_SHUFFLE_AND_TRACKSKIP
)
1141 if (global_settings
.playlist_shuffle
)
1142 /* shuffle mode is on, so crossfade: */
1143 codec_crossfade_track_change();
1145 /* shuffle mode is off, so do a gapless track change */
1146 codec_gapless_track_change();
1149 /* normal crossfade: */
1150 codec_crossfade_track_change();
1153 /* normal gapless playback. */
1154 codec_gapless_track_change();
1157 static bool codec_load_next_track(void)
1159 intptr_t result
= Q_CODEC_REQUEST_FAILED
;
1161 prev_track_elapsed
= curtrack_id3
.elapsed
;
1163 #ifdef AB_REPEAT_ENABLE
1164 ab_end_of_track_report();
1167 logf("Request new track");
1169 if (ci
.new_track
== 0)
1172 automatic_skip
= true;
1177 trigger_cpu_boost();
1178 LOGFQUEUE("codec >| audio Q_AUDIO_CHECK_NEW_TRACK");
1179 result
= queue_send(&audio_queue
, Q_AUDIO_CHECK_NEW_TRACK
, 0);
1184 case Q_CODEC_REQUEST_COMPLETE
:
1185 LOGFQUEUE("codec |< Q_CODEC_REQUEST_COMPLETE");
1186 codec_track_skip_done(!automatic_skip
);
1189 case Q_CODEC_REQUEST_FAILED
:
1190 LOGFQUEUE("codec |< Q_CODEC_REQUEST_FAILED");
1192 ci
.stop_codec
= true;
1193 codec_requested_stop
= true;
1197 LOGFQUEUE("codec |< default");
1198 ci
.stop_codec
= true;
1199 codec_requested_stop
= true;
1204 static bool codec_request_next_track_callback(void)
1208 if (ci
.stop_codec
|| !playing
)
1211 prev_codectype
= get_codec_base_type(curtrack_id3
.codectype
);
1213 if (!codec_load_next_track())
1216 /* Seek to the beginning of the new track because if the struct
1217 mp3entry was buffered, "elapsed" might not be zero (if the track has
1218 been played already but not unbuffered) */
1219 codec_seek_buffer_callback(curtrack_id3
.first_frame_offset
);
1221 /* Check if the next codec is the same file. */
1222 if (prev_codectype
== get_codec_base_type(curtrack_id3
.codectype
))
1224 logf("New track loaded");
1225 codec_discard_codec_callback();
1230 logf("New codec:%d/%d", curtrack_id3
.codectype
, prev_codectype
);
1235 static void codec_thread(void)
1237 struct queue_event ev
;
1243 if (!pcmbuf_is_crossfade_active()) {
1247 queue_wait(&codec_queue
, &ev
);
1248 codec_requested_stop
= false;
1251 case Q_CODEC_LOAD_DISK
:
1252 LOGFQUEUE("codec < Q_CODEC_LOAD_DISK");
1253 queue_reply(&codec_queue
, 1);
1254 audio_codec_loaded
= true;
1255 ci
.stop_codec
= false;
1256 status
= codec_load_file((const char *)ev
.data
, &ci
);
1260 LOGFQUEUE("codec < Q_CODEC_LOAD");
1261 if (CUR_TI
->codec_hid
< 0) {
1262 logf("Codec slot is empty!");
1263 /* Wait for the pcm buffer to go empty */
1264 while (pcm_is_playing())
1266 /* This must be set to prevent an infinite loop */
1267 ci
.stop_codec
= true;
1268 LOGFQUEUE("codec > codec Q_AUDIO_PLAY");
1269 queue_post(&codec_queue
, Q_AUDIO_PLAY
, 0);
1273 audio_codec_loaded
= true;
1274 ci
.stop_codec
= false;
1275 status
= codec_load_buf(CUR_TI
->codec_hid
, &ci
);
1278 #ifdef AUDIO_HAVE_RECORDING
1279 case Q_ENCODER_LOAD_DISK
:
1280 LOGFQUEUE("codec < Q_ENCODER_LOAD_DISK");
1281 audio_codec_loaded
= false; /* Not audio codec! */
1282 logf("loading encoder");
1283 ci
.stop_encoder
= false;
1284 status
= codec_load_file((const char *)ev
.data
, &ci
);
1285 logf("encoder stopped");
1287 #endif /* AUDIO_HAVE_RECORDING */
1290 LOGFQUEUE("codec < default");
1293 if (audio_codec_loaded
)
1302 audio_codec_loaded
= false;
1306 case Q_CODEC_LOAD_DISK
:
1308 LOGFQUEUE("codec < Q_CODEC_LOAD");
1311 if (ci
.new_track
|| status
!= CODEC_OK
)
1315 logf("Codec failure");
1316 gui_syncsplash(HZ
*2, "Codec failure");
1319 if (!codec_load_next_track())
1321 LOGFQUEUE("codec > audio Q_AUDIO_STOP");
1322 /* End of playlist */
1323 queue_post(&audio_queue
, Q_AUDIO_STOP
, 0);
1329 logf("Codec finished");
1332 /* Wait for the audio to stop playing before
1333 * triggering the WPS exit */
1334 while(pcm_is_playing())
1336 curtrack_id3
.elapsed
=
1337 curtrack_id3
.length
- pcmbuf_get_latency();
1341 if (codec_requested_stop
)
1343 LOGFQUEUE("codec > audio Q_AUDIO_STOP");
1344 queue_post(&audio_queue
, Q_AUDIO_STOP
, 0);
1350 if (CUR_TI
->codec_hid
>= 0)
1352 LOGFQUEUE("codec > codec Q_CODEC_LOAD");
1353 queue_post(&codec_queue
, Q_CODEC_LOAD
, 0);
1357 const char *codec_fn
=
1358 get_codec_filename(curtrack_id3
.codectype
);
1361 LOGFQUEUE("codec > codec Q_CODEC_LOAD_DISK");
1362 queue_post(&codec_queue
, Q_CODEC_LOAD_DISK
,
1363 (intptr_t)codec_fn
);
1369 #ifdef AUDIO_HAVE_RECORDING
1370 case Q_ENCODER_LOAD_DISK
:
1371 LOGFQUEUE("codec < Q_ENCODER_LOAD_DISK");
1373 if (status
== CODEC_OK
)
1376 logf("Encoder failure");
1377 gui_syncsplash(HZ
*2, "Encoder failure");
1379 if (ci
.enc_codec_loaded
< 0)
1382 logf("Encoder failed to load");
1383 ci
.enc_codec_loaded
= -1;
1385 #endif /* AUDIO_HAVE_RECORDING */
1388 LOGFQUEUE("codec < default");
1395 /* --- Buffering callbacks --- */
1397 static void buffering_low_buffer_callback(void *data
)
1400 logf("low buffer callback");
1402 if (filling
== STATE_FULL
) {
1403 /* force a refill */
1404 LOGFQUEUE("buffering > audio Q_AUDIO_FILL_BUFFER");
1405 queue_post(&audio_queue
, Q_AUDIO_FILL_BUFFER
, 0);
1409 static void buffering_handle_rebuffer_callback(void *data
)
1412 LOGFQUEUE("audio >| audio Q_AUDIO_FLUSH");
1413 queue_post(&audio_queue
, Q_AUDIO_FLUSH
, 0);
1416 static void buffering_handle_finished_callback(int *data
)
1418 logf("handle %d finished buffering", *data
);
1420 if (*data
== tracks
[track_widx
].id3_hid
)
1422 /* The metadata handle for the last loaded track has been buffered.
1423 We can ask the audio thread to load the rest of the track's data. */
1424 LOGFQUEUE("audio >| audio Q_AUDIO_FINISH_LOAD");
1425 queue_post(&audio_queue
, Q_AUDIO_FINISH_LOAD
, 0);
1429 /* This is most likely an audio handle, so we strip the useless
1430 trailing tags that are left. */
1436 /* --- Audio thread --- */
1438 static bool audio_have_tracks(void)
1440 return (audio_track_count() != 0);
1443 static int audio_free_track_count(void)
1445 /* Used tracks + free tracks adds up to MAX_TRACK - 1 */
1446 return MAX_TRACK
- 1 - audio_track_count();
1449 int audio_track_count(void)
1451 /* Calculate difference from track_ridx to track_widx
1452 * taking into account a possible wrap-around. */
1453 return (MAX_TRACK
+ track_widx
- track_ridx
) & MAX_TRACK_MASK
;
1456 long audio_filebufused(void)
1458 return (long) buf_used();
1461 /* Update track info after successful a codec track change */
1462 static void audio_update_trackinfo(void)
1464 /* Load the curent track's metadata into curtrack_id3 */
1465 if (CUR_TI
->id3_hid
>= 0)
1466 copy_mp3entry(&curtrack_id3
, bufgetid3(CUR_TI
->id3_hid
));
1468 /* Reset current position */
1469 curtrack_id3
.elapsed
= 0;
1470 curtrack_id3
.offset
= 0;
1472 /* Update the codec API */
1473 ci
.filesize
= CUR_TI
->filesize
;
1474 ci
.id3
= &curtrack_id3
;
1476 ci
.taginfo_ready
= &CUR_TI
->taginfo_ready
;
1479 /* Clear tracks between write and read, non inclusive */
1480 static void audio_clear_track_entries(void)
1482 int cur_idx
= track_widx
;
1484 logf("Clearing tracks:%d/%d", track_ridx
, track_widx
);
1486 /* Loop over all tracks from write-to-read */
1489 cur_idx
= (cur_idx
+ 1) & MAX_TRACK_MASK
;
1491 if (cur_idx
== track_ridx
)
1494 clear_track_info(&tracks
[cur_idx
]);
1498 /* Clear all tracks */
1499 static bool audio_release_tracks(void)
1503 logf("releasing all tracks");
1505 for(i
= 0; i
< MAX_TRACK
; i
++)
1507 cur_idx
= (track_ridx
+ i
) & MAX_TRACK_MASK
;
1508 if (!clear_track_info(&tracks
[cur_idx
]))
1515 static bool audio_loadcodec(bool start_play
)
1518 char codec_path
[MAX_PATH
]; /* Full path to codec */
1520 if (tracks
[track_widx
].id3_hid
< 0) {
1524 const char * codec_fn
=
1525 get_codec_filename(bufgetid3(tracks
[track_widx
].id3_hid
)->codectype
);
1526 if (codec_fn
== NULL
)
1529 tracks
[track_widx
].codec_hid
= -1;
1533 /* Load the codec directly from disk and save some memory. */
1534 track_ridx
= track_widx
;
1535 ci
.filesize
= CUR_TI
->filesize
;
1536 ci
.id3
= &curtrack_id3
;
1537 ci
.taginfo_ready
= &CUR_TI
->taginfo_ready
;
1539 LOGFQUEUE("codec > codec Q_CODEC_LOAD_DISK");
1540 queue_post(&codec_queue
, Q_CODEC_LOAD_DISK
, (intptr_t)codec_fn
);
1545 /* If we already have another track than this one buffered */
1546 if (track_widx
!= track_ridx
)
1548 prev_track
= (track_widx
- 1) & MAX_TRACK_MASK
;
1550 /* If the previous codec is the same as this one, there is no need
1551 * to put another copy of it on the file buffer */
1552 if (get_codec_base_type(
1553 bufgetid3(tracks
[track_widx
].id3_hid
)->codectype
) ==
1554 get_codec_base_type(
1555 bufgetid3(tracks
[prev_track
].id3_hid
)->codectype
)
1556 && audio_codec_loaded
)
1558 logf("Reusing prev. codec");
1564 codec_get_full_path(codec_path
, codec_fn
);
1566 tracks
[track_widx
].codec_hid
= bufopen(codec_path
, 0, TYPE_CODEC
);
1567 if (tracks
[track_widx
].codec_hid
< 0)
1570 logf("Loaded codec");
1575 /* Load metadata for the next track (with bufopen). The rest of the track
1576 loading will be handled by audio_finish_load_track once the metadata has been
1577 actually loaded by the buffering thread. */
1578 static bool audio_load_track(size_t offset
, bool start_play
)
1580 const char *trackname
;
1583 start_play_g
= start_play
; /* will be read by audio_finish_load_track */
1585 /* Stop buffer filling if there is no free track entries.
1586 Don't fill up the last track entry (we wan't to store next track
1588 if (!audio_free_track_count())
1590 logf("No free tracks");
1595 tracks
[track_widx
].taginfo_ready
= false;
1597 logf("Buffering track:%d/%d", track_widx
, track_ridx
);
1598 /* Get track name from current playlist read position. */
1599 while ((trackname
= playlist_peek(last_peek_offset
)) != NULL
)
1601 /* Handle broken playlists. */
1602 fd
= open(trackname
, O_RDONLY
);
1605 logf("Open failed");
1606 /* Skip invalid entry from playlist. */
1607 playlist_skip_entry(NULL
, last_peek_offset
);
1615 logf("End-of-playlist");
1616 memset(&lasttrack_id3
, 0, sizeof(struct mp3entry
));
1617 filling
= STATE_FINISHED
;
1621 tracks
[track_widx
].filesize
= filesize(fd
);
1623 if (offset
> tracks
[track_widx
].filesize
)
1626 /* Set default values */
1629 buf_set_watermark(AUDIO_DEFAULT_WATERMARK
);
1630 dsp_configure(ci
.dsp
, DSP_RESET
, 0);
1631 track_changed
= true;
1632 playlist_update_resume_info(audio_current_track());
1635 /* Get track metadata if we don't already have it. */
1636 if (tracks
[track_widx
].id3_hid
< 0)
1638 tracks
[track_widx
].id3_hid
= bufopen(trackname
, 0, TYPE_ID3
);
1640 if (tracks
[track_widx
].id3_hid
< 0)
1642 /* Buffer is full. */
1643 get_metadata(&lasttrack_id3
, fd
, trackname
);
1646 logf("buffer is full for now");
1647 filling
= STATE_FULL
;
1653 if (track_widx
== track_ridx
)
1655 buf_request_buffer_handle(tracks
[track_widx
].id3_hid
);
1656 copy_mp3entry(&curtrack_id3
, bufgetid3(tracks
[track_widx
].id3_hid
));
1657 curtrack_id3
.offset
= offset
;
1662 track_changed
= true;
1663 playlist_update_resume_info(audio_current_track());
1670 /* Second part of the track loading: We now have the metadata available, so we
1671 can load the codec, the album art and finally the audio data.
1672 This is called on the audio thread after the buffering thread calls the
1673 buffering_handle_finished_callback callback. */
1674 static void audio_finish_load_track(void)
1677 size_t file_offset
= 0;
1679 bool start_play
= start_play_g
;
1682 if (cuesheet_is_enabled() && tracks
[track_widx
].id3
.cuesheet_type
== 1)
1684 char cuepath
[MAX_PATH
];
1686 struct cuesheet
*cue
= start_play
? curr_cue
: temp_cue
;
1688 if (look_for_cuesheet_file(trackname
, cuepath
) &&
1689 parse_cuesheet(cuepath
, cue
))
1691 strcpy((cue
)->audio_filename
, trackname
);
1693 cue_spoof_id3(curr_cue
, &tracks
[track_widx
].id3
);
1698 if (tracks
[track_widx
].id3_hid
< 0) {
1699 logf("no metatdata");
1703 struct mp3entry
*track_id3
;
1705 if (track_widx
== track_ridx
)
1706 track_id3
= &curtrack_id3
;
1708 track_id3
= bufgetid3(tracks
[track_widx
].id3_hid
);
1710 if (track_id3
->length
== 0 || track_id3
->filesize
== 0)
1712 logf("audio_finish_load_track: invalid metadata");
1714 /* Invalid metadata */
1715 bufclose(tracks
[track_widx
].id3_hid
);
1716 tracks
[track_widx
].id3_hid
= -1;
1718 /* Skip invalid entry from playlist. */
1719 playlist_skip_entry(NULL
, last_peek_offset
--);
1721 /* load next track */
1722 LOGFQUEUE("audio > audio Q_AUDIO_FILL_BUFFER %d", (int)start_play
);
1723 queue_post(&audio_queue
, Q_AUDIO_FILL_BUFFER
, start_play
);
1728 #ifdef HAVE_ALBUMART
1729 if (tracks
[track_widx
].aa_hid
< 0 && gui_sync_wps_uses_albumart())
1731 char aa_path
[MAX_PATH
];
1732 if (find_albumart(track_id3
, aa_path
, sizeof(aa_path
)))
1733 tracks
[track_widx
].aa_hid
= bufopen(aa_path
, 0, TYPE_BITMAP
);
1737 /* Load the codec. */
1738 if (!audio_loadcodec(start_play
))
1740 if (tracks
[track_widx
].codec_hid
== ERR_BUFFER_FULL
)
1742 /* No space for codec on buffer, not an error */
1746 /* This is an error condition, either no codec was found, or reading
1747 * the codec file failed part way through, either way, skip the track */
1748 snprintf(msgbuf
, sizeof(msgbuf
)-1, "No codec for: %s", track_id3
->path
);
1749 /* We should not use gui_syncplash from audio thread! */
1750 gui_syncsplash(HZ
*2, msgbuf
);
1751 /* Skip invalid entry from playlist. */
1752 playlist_skip_entry(NULL
, last_peek_offset
);
1756 track_id3
->elapsed
= 0;
1757 offset
= track_id3
->offset
;
1759 enum data_type type
= TYPE_PACKET_AUDIO
;
1761 switch (track_id3
->codectype
) {
1766 file_offset
= offset
;
1767 track_id3
->offset
= offset
;
1773 file_offset
= offset
;
1774 track_id3
->offset
= offset
;
1775 track_id3
->elapsed
= track_id3
->length
/ 2;
1779 case AFMT_OGG_VORBIS
:
1789 track_id3
->offset
= offset
;
1795 logf("Loading atomic %d",track_id3
->codectype
);
1796 type
= TYPE_ATOMIC_AUDIO
;
1800 logf("alt:%s", track_id3
->path
);
1802 if (file_offset
> AUDIO_REBUFFER_GUESS_SIZE
)
1803 file_offset
-= AUDIO_REBUFFER_GUESS_SIZE
;
1804 else if (track_id3
->first_frame_offset
)
1805 file_offset
= track_id3
->first_frame_offset
;
1809 tracks
[track_widx
].audio_hid
= bufopen(track_id3
->path
, file_offset
, type
);
1811 if (tracks
[track_widx
].audio_hid
< 0)
1814 /* All required data is now available for the codec. */
1815 tracks
[track_widx
].taginfo_ready
= true;
1819 ci
.curpos
=file_offset
;
1820 buf_request_buffer_handle(tracks
[track_widx
].audio_hid
);
1823 track_widx
= (track_widx
+ 1) & MAX_TRACK_MASK
;
1825 send_event(PLAYBACK_EVENT_TRACK_BUFFER
, track_id3
);
1827 /* load next track */
1828 LOGFQUEUE("audio > audio Q_AUDIO_FILL_BUFFER");
1829 queue_post(&audio_queue
, Q_AUDIO_FILL_BUFFER
, 0);
1834 static void audio_fill_file_buffer(bool start_play
, size_t offset
)
1836 bool had_next_track
= audio_next_track() != NULL
;
1838 filling
= STATE_FILLING
;
1839 trigger_cpu_boost();
1841 /* No need to rebuffer if there are track skips pending. */
1842 if (ci
.new_track
!= 0)
1845 /* Must reset the buffer before use if trashed or voice only - voice
1846 file size shouldn't have changed so we can go straight from
1847 BUFFER_STATE_VOICED_ONLY to BUFFER_STATE_INITIALIZED */
1848 if (buffer_state
!= BUFFER_STATE_INITIALIZED
)
1849 audio_reset_buffer();
1851 logf("Starting buffer fill");
1854 audio_clear_track_entries();
1856 /* Save the current resume position once. */
1857 playlist_update_resume_info(audio_current_track());
1859 audio_load_track(offset
, start_play
);
1861 if (!had_next_track
&& audio_next_track())
1862 track_changed
= true;
1865 static void audio_rebuffer(void)
1867 logf("Forcing rebuffer");
1869 clear_track_info(CUR_TI
);
1871 /* Reset track pointers */
1872 track_widx
= track_ridx
;
1873 audio_clear_track_entries();
1875 /* Fill the buffer */
1876 last_peek_offset
= -1;
1879 if (!CUR_TI
->taginfo_ready
)
1880 memset(&curtrack_id3
, 0, sizeof(struct mp3entry
));
1882 audio_fill_file_buffer(false, 0);
1885 /* Called on request from the codec to get a new track. This is the codec part
1886 of the track transition. */
1887 static int audio_check_new_track(void)
1889 int track_count
= audio_track_count();
1890 int old_track_ridx
= track_ridx
;
1894 /* Now it's good time to send track finish events. */
1895 send_event(PLAYBACK_EVENT_TRACK_FINISH
, &curtrack_id3
);
1899 if (playlist_next_dir(ci
.new_track
))
1907 LOGFQUEUE("audio >|= codec Q_CODEC_REQUEST_FAILED");
1908 return Q_CODEC_REQUEST_FAILED
;
1915 /* If the playlist isn't that big */
1918 while (!playlist_check(ci
.new_track
))
1920 if (ci
.new_track
>= 0)
1922 LOGFQUEUE("audio >|= codec Q_CODEC_REQUEST_FAILED");
1923 return Q_CODEC_REQUEST_FAILED
;
1929 /* Update the playlist */
1930 last_peek_offset
-= ci
.new_track
;
1932 if (playlist_next(ci
.new_track
) < 0)
1934 LOGFQUEUE("audio >|= codec Q_CODEC_REQUEST_FAILED");
1935 return Q_CODEC_REQUEST_FAILED
;
1941 new_playlist
= false;
1944 /* Save the track metadata to allow the WPS to display it
1945 while PCM finishes playing that track */
1946 copy_mp3entry(&prevtrack_id3
, &curtrack_id3
);
1948 /* Update the main buffer copy of the track metadata with the one
1949 the codec has been using (for the unbuffer callbacks) */
1950 if (CUR_TI
->id3_hid
>= 0)
1951 copy_mp3entry(bufgetid3(CUR_TI
->id3_hid
), &curtrack_id3
);
1953 /* Save a pointer to the old track to allow later clearing */
1956 for (i
= 0; i
< ci
.new_track
; i
++)
1958 idx
= (track_ridx
+ i
) & MAX_TRACK_MASK
;
1959 struct mp3entry
*id3
= bufgetid3(tracks
[idx
].id3_hid
);
1960 ssize_t offset
= buf_handle_offset(tracks
[idx
].audio_hid
);
1961 if (!id3
|| offset
< 0 || (unsigned)offset
> id3
->first_frame_offset
)
1963 /* We don't have all the audio data for that track, so clear it,
1964 but keep the metadata. */
1965 if (tracks
[idx
].audio_hid
>= 0 && bufclose(tracks
[idx
].audio_hid
))
1967 tracks
[idx
].audio_hid
= -1;
1968 tracks
[idx
].filesize
= 0;
1973 /* Move to the new track */
1974 track_ridx
= (track_ridx
+ ci
.new_track
) & MAX_TRACK_MASK
;
1976 buf_set_base_handle(CUR_TI
->audio_hid
);
1980 wps_offset
= -ci
.new_track
;
1981 track_changed
= true;
1984 /* If it is not safe to even skip this many track entries */
1985 if (ci
.new_track
>= track_count
|| ci
.new_track
<= track_count
- MAX_TRACK
)
1992 forward
= ci
.new_track
> 0;
1995 /* If the target track is clearly not in memory */
1996 if (CUR_TI
->filesize
== 0 || !CUR_TI
->taginfo_ready
)
2002 /* When skipping backwards, it is possible that we've found a track that's
2003 * buffered, but which is around the track-wrap and therefore not the track
2004 * we are looking for */
2007 int cur_idx
= track_ridx
;
2008 bool taginfo_ready
= true;
2009 /* We've wrapped the buffer backwards if new > old */
2010 bool wrap
= track_ridx
> old_track_ridx
;
2014 cur_idx
= (cur_idx
+ 1) & MAX_TRACK_MASK
;
2016 /* if we've advanced past the wrap when cur_idx is zeroed */
2020 /* if we aren't still on the wrap and we've caught the old track */
2021 if (!(wrap
|| cur_idx
< old_track_ridx
))
2024 /* If we hit a track in between without valid tag info, bail */
2025 if (!tracks
[cur_idx
].taginfo_ready
)
2027 taginfo_ready
= false;
2038 audio_update_trackinfo();
2039 LOGFQUEUE("audio >|= codec Q_CODEC_REQUEST_COMPLETE");
2040 return Q_CODEC_REQUEST_COMPLETE
;
2043 unsigned long audio_prev_elapsed(void)
2045 return prev_track_elapsed
;
2048 static void audio_stop_codec_flush(void)
2050 ci
.stop_codec
= true;
2053 while (audio_codec_loaded
)
2056 /* If the audio codec is not loaded any more, and the audio is still
2057 * playing, it is now and _only_ now safe to call this function from the
2059 if (pcm_is_playing())
2062 pcmbuf_queue_clear();
2064 pcmbuf_pause(paused
);
2067 static void audio_stop_playback(void)
2069 /* If we were playing, save resume information */
2072 struct mp3entry
*id3
= NULL
;
2076 /* Set this early, the outside code yields and may allow the codec
2077 to try to wait for a reply on a buffer wait */
2078 ci
.stop_codec
= true;
2079 id3
= audio_current_track();
2082 /* Save the current playing spot, or NULL if the playlist has ended */
2083 playlist_update_resume_info(id3
);
2085 /* TODO: Create auto bookmark too? */
2087 prev_track_elapsed
= curtrack_id3
.elapsed
;
2089 remove_event(EVENT_BUFFER_LOW
, buffering_low_buffer_callback
);
2093 audio_stop_codec_flush();
2096 filling
= STATE_IDLE
;
2098 /* Mark all entries null. */
2099 audio_clear_track_entries();
2101 /* Close all tracks */
2102 audio_release_tracks();
2104 memset(&curtrack_id3
, 0, sizeof(struct mp3entry
));
2107 static void audio_play_start(size_t offset
)
2111 #if INPUT_SRC_CAPS != 0
2112 audio_set_input_source(AUDIO_SRC_PLAYBACK
, SRCF_PLAYBACK
);
2113 audio_set_output_source(AUDIO_SRC_PLAYBACK
);
2116 /* Wait for any previously playing audio to flush - TODO: Not necessary? */
2118 audio_stop_codec_flush();
2120 track_changed
= true;
2128 sound_set_volume(global_settings
.volume
);
2129 track_widx
= track_ridx
= 0;
2131 /* Clear all track entries. */
2132 for (i
= 0; i
< MAX_TRACK
; i
++) {
2133 clear_track_info(&tracks
[i
]);
2136 last_peek_offset
= -1;
2138 /* Officially playing */
2139 queue_reply(&audio_queue
, 1);
2141 #ifndef HAVE_FLASH_STORAGE
2142 set_filebuf_watermark(buffer_margin
, 0);
2145 audio_fill_file_buffer(true, offset
);
2147 add_event(EVENT_BUFFER_LOW
, false, buffering_low_buffer_callback
);
2149 LOGFQUEUE("audio > audio Q_AUDIO_TRACK_CHANGED");
2150 queue_post(&audio_queue
, Q_AUDIO_TRACK_CHANGED
, 0);
2154 /* Invalidates all but currently playing track. */
2155 static void audio_invalidate_tracks(void)
2157 if (audio_have_tracks())
2159 last_peek_offset
= 0;
2160 track_widx
= track_ridx
;
2162 /* Mark all other entries null (also buffered wrong metadata). */
2163 audio_clear_track_entries();
2165 track_widx
= (track_widx
+ 1) & MAX_TRACK_MASK
;
2167 audio_fill_file_buffer(false, 0);
2171 static void audio_new_playlist(void)
2173 /* Prepare to start a new fill from the beginning of the playlist */
2174 last_peek_offset
= -1;
2175 if (audio_have_tracks())
2178 skipped_during_pause
= true;
2179 track_widx
= track_ridx
;
2180 audio_clear_track_entries();
2182 track_widx
= (track_widx
+ 1) & MAX_TRACK_MASK
;
2184 /* Mark the current track as invalid to prevent skipping back to it */
2185 CUR_TI
->taginfo_ready
= false;
2188 /* Signal the codec to initiate a track change forward */
2189 new_playlist
= true;
2192 /* Officially playing */
2193 queue_reply(&audio_queue
, 1);
2195 audio_fill_file_buffer(false, 0);
2198 /* Called on manual track skip */
2199 static void audio_initiate_track_change(long direction
)
2201 logf("audio_initiate_track_change(%ld)", direction
);
2203 ci
.new_track
+= direction
;
2204 wps_offset
-= direction
;
2206 skipped_during_pause
= true;
2209 /* Called on manual dir skip */
2210 static void audio_initiate_dir_change(long direction
)
2213 ci
.new_track
= direction
;
2215 skipped_during_pause
= true;
2218 /* Called when PCM track change is complete */
2219 static void audio_finalise_track_change(void)
2221 logf("audio_finalise_track_change");
2226 automatic_skip
= false;
2228 /* Invalidate prevtrack_id3 */
2229 prevtrack_id3
.path
[0] = 0;
2231 if (prev_ti
&& prev_ti
->audio_hid
< 0)
2233 /* No audio left so we clear all the track info. */
2234 clear_track_info(prev_ti
);
2237 if (prev_ti
&& prev_ti
->id3_hid
>= 0)
2239 /* Reset the elapsed time to force the progressbar to be empty if
2240 the user skips back to this track */
2241 bufgetid3(prev_ti
->id3_hid
)->elapsed
= 0;
2245 send_event(PLAYBACK_EVENT_TRACK_CHANGE
, &curtrack_id3
);
2247 track_changed
= true;
2248 playlist_update_resume_info(audio_current_track());
2252 * Layout audio buffer as follows - iram buffer depends on target:
2253 * [|SWAP:iram][|TALK]|MALLOC|FILE|GUARD|PCM|[SWAP:dram[|iram]|]
2255 static void audio_reset_buffer(void)
2257 /* see audio_get_recording_buffer if this is modified */
2258 logf("audio_reset_buffer");
2260 /* If the setup of anything allocated before the file buffer is
2261 changed, do check the adjustments after the buffer_alloc call
2262 as it will likely be affected and need sliding over */
2264 /* Initially set up file buffer as all space available */
2265 malloc_buf
= audiobuf
+ talk_get_bufsize();
2266 /* Align the malloc buf to line size. Especially important to cf
2267 targets that do line reads/writes. */
2268 malloc_buf
= (unsigned char *)(((uintptr_t)malloc_buf
+ 15) & ~15);
2269 filebuf
= malloc_buf
+ MALLOC_BUFSIZE
; /* filebuf line align implied */
2270 filebuflen
= audiobufend
- filebuf
;
2274 /* Subtract whatever the pcm buffer says it used plus the guard buffer */
2275 filebuflen
-= pcmbuf_init(filebuf
+ filebuflen
) + GUARD_BUFSIZE
;
2277 /* Make sure filebuflen is a longword multiple after adjustment - filebuf
2278 will already be line aligned */
2281 buffering_reset(filebuf
, filebuflen
);
2283 /* Clear any references to the file buffer */
2284 buffer_state
= BUFFER_STATE_INITIALIZED
;
2286 #if defined(ROCKBOX_HAS_LOGF) && defined(LOGF_ENABLE)
2287 /* Make sure everything adds up - yes, some info is a bit redundant but
2288 aids viewing and the sumation of certain variables should add up to
2289 the location of others. */
2292 const unsigned char *pcmbuf
= pcmbuf_get_meminfo(&pcmbufsize
);
2293 logf("mabuf: %08X", (unsigned)malloc_buf
);
2294 logf("mabufe: %08X", (unsigned)(malloc_buf
+ MALLOC_BUFSIZE
));
2295 logf("fbuf: %08X", (unsigned)filebuf
);
2296 logf("fbufe: %08X", (unsigned)(filebuf
+ filebuflen
));
2297 logf("gbuf: %08X", (unsigned)(filebuf
+ filebuflen
));
2298 logf("gbufe: %08X", (unsigned)(filebuf
+ filebuflen
+ GUARD_BUFSIZE
));
2299 logf("pcmb: %08X", (unsigned)pcmbuf
);
2300 logf("pcmbe: %08X", (unsigned)(pcmbuf
+ pcmbufsize
));
2305 static void audio_thread(void)
2307 struct queue_event ev
;
2311 audio_thread_ready
= true;
2315 if (filling
!= STATE_FILLING
) {
2319 if (!pcmbuf_queue_scan(&ev
))
2320 queue_wait_w_tmo(&audio_queue
, &ev
, HZ
/2);
2324 case Q_AUDIO_FILL_BUFFER
:
2325 LOGFQUEUE("audio < Q_AUDIO_FILL_BUFFER %d", (int)ev
.data
);
2326 audio_fill_file_buffer((bool)ev
.data
, 0);
2329 case Q_AUDIO_FINISH_LOAD
:
2330 LOGFQUEUE("audio < Q_AUDIO_FINISH_LOAD");
2331 audio_finish_load_track();
2335 LOGFQUEUE("audio < Q_AUDIO_PLAY");
2336 if (playing
&& ev
.data
<= 0)
2337 audio_new_playlist();
2340 audio_stop_playback();
2341 audio_play_start((size_t)ev
.data
);
2346 LOGFQUEUE("audio < Q_AUDIO_STOP");
2348 audio_stop_playback();
2350 queue_clear(&audio_queue
);
2354 LOGFQUEUE("audio < Q_AUDIO_PAUSE");
2355 if (!(bool) ev
.data
&& skipped_during_pause
&& !pcmbuf_is_crossfade_active())
2356 pcmbuf_play_stop(); /* Flush old track on resume after skip */
2357 skipped_during_pause
= false;
2360 pcmbuf_pause((bool)ev
.data
);
2361 paused
= (bool)ev
.data
;
2365 LOGFQUEUE("audio < Q_AUDIO_SKIP");
2366 audio_initiate_track_change((long)ev
.data
);
2369 case Q_AUDIO_PRE_FF_REWIND
:
2370 LOGFQUEUE("audio < Q_AUDIO_PRE_FF_REWIND");
2376 case Q_AUDIO_FF_REWIND
:
2377 LOGFQUEUE("audio < Q_AUDIO_FF_REWIND");
2382 /* An automatic track skip is in progress. Finalize it,
2383 then go back to the previous track */
2384 audio_finalise_track_change();
2387 ci
.seek_time
= (long)ev
.data
+1;
2390 case Q_AUDIO_CHECK_NEW_TRACK
:
2391 LOGFQUEUE("audio < Q_AUDIO_CHECK_NEW_TRACK");
2392 queue_reply(&audio_queue
, audio_check_new_track());
2395 case Q_AUDIO_DIR_SKIP
:
2396 LOGFQUEUE("audio < Q_AUDIO_DIR_SKIP");
2397 audio_initiate_dir_change(ev
.data
);
2401 LOGFQUEUE("audio < Q_AUDIO_FLUSH");
2402 audio_invalidate_tracks();
2405 case Q_AUDIO_TRACK_CHANGED
:
2406 /* PCM track change done */
2407 LOGFQUEUE("audio < Q_AUDIO_TRACK_CHANGED");
2408 audio_finalise_track_change();
2412 case SYS_USB_CONNECTED
:
2413 LOGFQUEUE("audio < SYS_USB_CONNECTED");
2415 audio_stop_playback();
2416 #ifdef PLAYBACK_VOICE
2419 usb_acknowledge(SYS_USB_CONNECTED_ACK
);
2420 usb_wait_for_disconnect(&audio_queue
);
2422 /* Mark all entries null. */
2423 audio_clear_track_entries();
2425 /* release tracks to make sure all handles are closed */
2426 audio_release_tracks();
2431 LOGFQUEUE_SYS_TIMEOUT("audio < SYS_TIMEOUT");
2435 LOGFQUEUE("audio < default");
2441 /* Initialize the audio system - called from init() in main.c.
2442 * Last function because of all the references to internal symbols
2444 void audio_init(void)
2446 struct thread_entry
*audio_thread_p
;
2448 /* Can never do this twice */
2449 if (audio_is_initialized
)
2451 logf("audio: already initialized");
2455 logf("audio: initializing");
2457 /* Initialize queues before giving control elsewhere in case it likes
2458 to send messages. Thread creation will be delayed however so nothing
2459 starts running until ready if something yields such as talk_init. */
2460 queue_init(&audio_queue
, true);
2461 queue_init(&codec_queue
, false);
2462 queue_init(&pcmbuf_queue
, false);
2466 /* Initialize codec api. */
2467 ci
.read_filebuf
= codec_filebuf_callback
;
2468 ci
.pcmbuf_insert
= codec_pcmbuf_insert_callback
;
2469 ci
.get_codec_memory
= codec_get_memory_callback
;
2470 ci
.request_buffer
= codec_request_buffer_callback
;
2471 ci
.advance_buffer
= codec_advance_buffer_callback
;
2472 ci
.advance_buffer_loc
= codec_advance_buffer_loc_callback
;
2473 ci
.request_next_track
= codec_request_next_track_callback
;
2474 ci
.seek_buffer
= codec_seek_buffer_callback
;
2475 ci
.seek_complete
= codec_seek_complete_callback
;
2476 ci
.set_elapsed
= codec_set_elapsed_callback
;
2477 ci
.set_offset
= codec_set_offset_callback
;
2478 ci
.configure
= codec_configure_callback
;
2479 ci
.discard_codec
= codec_discard_codec_callback
;
2480 ci
.dsp
= (struct dsp_config
*)dsp_configure(NULL
, DSP_MYDSP
,
2483 /* initialize the buffer */
2486 /* audio_reset_buffer must to know the size of voice buffer so init
2490 codec_thread_p
= create_thread(
2491 codec_thread
, codec_stack
, sizeof(codec_stack
),
2492 CREATE_THREAD_FROZEN
,
2493 codec_thread_name
IF_PRIO(, PRIORITY_PLAYBACK
)
2496 queue_enable_queue_send(&codec_queue
, &codec_queue_sender_list
,
2499 audio_thread_p
= create_thread(audio_thread
, audio_stack
,
2500 sizeof(audio_stack
), CREATE_THREAD_FROZEN
,
2501 audio_thread_name
IF_PRIO(, PRIORITY_USER_INTERFACE
)
2504 queue_enable_queue_send(&audio_queue
, &audio_queue_sender_list
,
2507 #ifdef PLAYBACK_VOICE
2508 voice_thread_init();
2511 /* Set crossfade setting for next buffer init which should be about... */
2512 pcmbuf_crossfade_enable(global_settings
.crossfade
);
2514 /* initialize the buffering system */
2517 /* ...now! Set up the buffers */
2518 audio_reset_buffer();
2521 for(i
= 0; i
< MAX_TRACK
; i
++)
2523 tracks
[i
].audio_hid
= -1;
2524 tracks
[i
].id3_hid
= -1;
2525 tracks
[i
].codec_hid
= -1;
2526 #ifdef HAVE_ALBUMART
2527 tracks
[i
].aa_hid
= -1;
2531 add_event(EVENT_HANDLE_REBUFFER
, false, buffering_handle_rebuffer_callback
);
2532 add_event(EVENT_HANDLE_FINISHED
, false, buffering_handle_finished_callback
);
2534 /* Probably safe to say */
2535 audio_is_initialized
= true;
2537 sound_settings_apply();
2538 #ifndef HAVE_FLASH_STORAGE
2539 audio_set_buffer_margin(global_settings
.buffer_margin
);
2542 /* it's safe to let the threads run now */
2543 #ifdef PLAYBACK_VOICE
2544 voice_thread_resume();
2546 thread_thaw(codec_thread_p
);
2547 thread_thaw(audio_thread_p
);
2551 void audio_wait_for_init(void)
2553 /* audio thread will only set this once after it finished the final
2554 * audio hardware init so this little construct is safe - even
2556 while (!audio_thread_ready
)