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"
44 #include "voice_thread.h"
45 #include "mp3_playback.h"
60 #ifdef HAVE_LCD_BITMAP
62 #include "peakmeter.h"
73 #include "ata_idle_notify.h"
76 #include "recording.h"
80 #define PLAYBACK_VOICE
82 /* default point to start buffer refill */
83 #define AUDIO_DEFAULT_WATERMARK (1024*512)
84 /* amount of guess-space to allow for codecs that must hunt and peck
85 * for their correct seeek target, 32k seems a good size */
86 #define AUDIO_REBUFFER_GUESS_SIZE (1024*32)
88 /* Define LOGF_ENABLE to enable logf output in this file */
89 /*#define LOGF_ENABLE*/
92 /* macros to enable logf for queues
93 logging on SYS_TIMEOUT can be disabled */
95 /* Define this for logf output of all queuing except SYS_TIMEOUT */
96 #define PLAYBACK_LOGQUEUES
97 /* Define this to logf SYS_TIMEOUT messages */
98 /*#define PLAYBACK_LOGQUEUES_SYS_TIMEOUT*/
101 #ifdef PLAYBACK_LOGQUEUES
102 #define LOGFQUEUE logf
104 #define LOGFQUEUE(...)
107 #ifdef PLAYBACK_LOGQUEUES_SYS_TIMEOUT
108 #define LOGFQUEUE_SYS_TIMEOUT logf
110 #define LOGFQUEUE_SYS_TIMEOUT(...)
114 /* Define one constant that includes recording related functionality */
115 #if defined(HAVE_RECORDING) && !defined(SIMULATOR)
116 #define AUDIO_HAVE_RECORDING
125 Q_AUDIO_PRE_FF_REWIND
,
127 Q_AUDIO_CHECK_NEW_TRACK
,
129 Q_AUDIO_TRACK_CHANGED
,
133 Q_CODEC_REQUEST_COMPLETE
,
134 Q_CODEC_REQUEST_FAILED
,
139 #ifdef AUDIO_HAVE_RECORDING
146 STATE_IDLE
, /* audio is stopped: nothing to do */
147 STATE_FILLING
, /* adding tracks to the buffer */
148 STATE_FULL
, /* can't add any more tracks */
149 STATE_FINISHED
, /* all remaining tracks have been added */
152 /* As defined in plugins/lib/xxx2wav.h */
154 #define MALLOC_BUFSIZE (512*1024)
155 #define GUARD_BUFSIZE (32*1024)
157 #define MALLOC_BUFSIZE (100*1024)
158 #define GUARD_BUFSIZE (8*1024)
161 /* As defined in plugin.lds */
163 #define CODEC_IRAM_ORIGIN ((unsigned char *)0x4000c000)
164 #define CODEC_IRAM_SIZE ((size_t)0xc000)
165 #elif defined(IAUDIO_X5) || defined(IAUDIO_M5)
166 #define CODEC_IRAM_ORIGIN ((unsigned char *)0x10010000)
167 #define CODEC_IRAM_SIZE ((size_t)0x10000)
169 #define CODEC_IRAM_ORIGIN ((unsigned char *)0x1000c000)
170 #define CODEC_IRAM_SIZE ((size_t)0xc000)
173 bool audio_is_initialized
= false;
174 static bool audio_thread_ready NOCACHEBSS_ATTR
= false;
176 /* Variables are commented with the threads that use them: *
177 * A=audio, C=codec, V=voice. A suffix of - indicates that *
178 * the variable is read but not updated on that thread. */
179 /* TBD: Split out "audio" and "playback" (ie. calling) threads */
181 /* Main state control */
182 static volatile bool audio_codec_loaded NOCACHEBSS_ATTR
= false; /* Codec loaded? (C/A-) */
183 static volatile bool playing NOCACHEBSS_ATTR
= false; /* Is audio playing? (A) */
184 static volatile bool paused NOCACHEBSS_ATTR
= false; /* Is audio paused? (A/C-) */
186 /* Ring buffer where compressed audio and codecs are loaded */
187 static unsigned char *filebuf
= NULL
; /* Start of buffer (A/C-) */
188 static unsigned char *malloc_buf
= NULL
; /* Start of malloc buffer (A/C-) */
189 /* FIXME: make filebuflen static */
190 size_t filebuflen
= 0; /* Size of buffer (A/C-) */
191 /* FIXME: make buf_ridx (C/A-) */
193 /* Possible arrangements of the buffer */
194 #define BUFFER_STATE_TRASHED -1 /* trashed; must be reset */
195 #define BUFFER_STATE_INITIALIZED 0 /* voice+audio OR audio-only */
196 #define BUFFER_STATE_VOICED_ONLY 1 /* voice-only */
197 static int buffer_state
= BUFFER_STATE_TRASHED
; /* Buffer state */
199 /* Used to keep the WPS up-to-date during track transtition */
200 static struct mp3entry prevtrack_id3
;
202 /* Used to provide the codec with a pointer */
203 static struct mp3entry curtrack_id3
;
205 /* Used to make next track info available while playing last track on buffer */
206 static struct mp3entry lasttrack_id3
;
208 /* Track info structure about songs in the file buffer (A/C-) */
210 int audio_hid
; /* The ID for the track's buffer handle */
211 int id3_hid
; /* The ID for the track's metadata handle */
212 int codec_hid
; /* The ID for the track's codec handle */
214 int aa_hid
; /* The ID for the track's album art handle */
217 size_t filesize
; /* File total length */
219 bool taginfo_ready
; /* Is metadata read */
222 static struct track_info tracks
[MAX_TRACK
];
223 static volatile int track_ridx
= 0; /* Track being decoded (A/C-) */
224 static int track_widx
= 0; /* Track being buffered (A) */
226 #define CUR_TI (&tracks[track_ridx]) /* Playing track info pointer (A/C-) */
227 static struct track_info
*prev_ti
= NULL
; /* Pointer to the previously played
230 /* Set by the audio thread when the current track information has updated
231 * and the WPS may need to update its cached information */
232 static bool track_changed
= false;
234 /* Information used only for filling the buffer */
235 /* Playlist steps from playing track to next track to be buffered (A) */
236 static int last_peek_offset
= 0;
238 /* Scrobbler support */
239 static unsigned long prev_track_elapsed
= 0; /* Previous track elapsed time (C/A-)*/
241 static enum filling_state filling
;
243 /* Track change controls */
244 static bool automatic_skip
= false; /* Who initiated in-progress skip? (C/A-) */
245 static bool playlist_end
= false; /* Has the current playlist ended? (A) */
246 static bool auto_dir_skip
= false; /* Have we changed dirs automatically? */
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 /* Set to true if the codec thread should send an audio stop request
253 * (typically because the end of the playlist has been reached).
255 static bool codec_requested_stop
= false;
257 static size_t buffer_margin
= 0; /* Buffer margin aka anti-skip buffer (A/C-) */
259 /* Multiple threads */
260 /* Set the watermark to trigger buffer fill (A/C) FIXME */
261 static void set_filebuf_watermark(int seconds
, size_t max
);
264 static struct event_queue audio_queue NOCACHEBSS_ATTR
;
265 static struct queue_sender_list audio_queue_sender_list NOCACHEBSS_ATTR
;
266 static long audio_stack
[(DEFAULT_STACK_SIZE
+ 0x1000)/sizeof(long)];
267 static const char audio_thread_name
[] = "audio";
269 static void audio_thread(void);
270 static void audio_initiate_track_change(long direction
);
271 static bool audio_have_tracks(void);
272 static void audio_reset_buffer(void);
275 extern struct codec_api ci
;
276 static struct event_queue codec_queue NOCACHEBSS_ATTR
;
277 static struct queue_sender_list codec_queue_sender_list
;
278 static long codec_stack
[(DEFAULT_STACK_SIZE
+ 0x2000)/sizeof(long)]
280 static const char codec_thread_name
[] = "codec";
281 struct thread_entry
*codec_thread_p
; /* For modifying thread priority later. */
283 /* PCM buffer messaging */
284 static struct event_queue pcmbuf_queue NOCACHEBSS_ATTR
;
286 /* Function to be called by pcm buffer callbacks.
287 * Permissible Context(s): Audio interrupt
289 static void pcmbuf_callback_queue_post(long id
, intptr_t data
)
291 /* No lock since we're already in audio interrupt context */
292 queue_post(&pcmbuf_queue
, id
, data
);
295 /* Scan the pcmbuf queue and return true if a message pulled.
296 * Permissible Context(s): Thread
298 static bool pcmbuf_queue_scan(struct queue_event
*ev
)
300 if (!queue_empty(&pcmbuf_queue
))
302 /* Transfer message to audio queue */
304 /* Pull message - never, ever any blocking call! */
305 queue_wait_w_tmo(&pcmbuf_queue
, ev
, 0);
313 /* Clear the pcmbuf queue of messages
314 * Permissible Context(s): Thread
316 static void pcmbuf_queue_clear(void)
319 queue_clear(&pcmbuf_queue
);
323 /* --- Helper functions --- */
325 static struct mp3entry
*bufgetid3(int handle_id
)
330 struct mp3entry
*id3
;
331 ssize_t ret
= bufgetdata(handle_id
, 0, (void *)&id3
);
333 if (ret
< 0 || ret
!= sizeof(struct mp3entry
))
339 static bool clear_track_info(struct track_info
*track
)
341 /* bufclose returns true if the handle is not found, or if it is closed
342 * successfully, so these checks are safe on non-existant handles */
346 if (track
->codec_hid
>= 0) {
347 if (bufclose(track
->codec_hid
))
348 track
->codec_hid
= -1;
353 if (track
->id3_hid
>= 0) {
354 if (bufclose(track
->id3_hid
))
360 if (track
->audio_hid
>= 0) {
361 if (bufclose(track
->audio_hid
))
362 track
->audio_hid
= -1;
368 if (track
->aa_hid
>= 0) {
369 if (bufclose(track
->aa_hid
))
377 track
->taginfo_ready
= false;
382 /* --- External interfaces --- */
384 /* This sends a stop message and the audio thread will dump all it's
385 subsequenct messages */
386 void audio_hard_stop(void)
389 LOGFQUEUE("audio >| audio Q_AUDIO_STOP: 1");
390 queue_send(&audio_queue
, Q_AUDIO_STOP
, 1);
391 #ifdef PLAYBACK_VOICE
396 bool audio_restore_playback(int type
)
400 case AUDIO_WANT_PLAYBACK
:
401 if (buffer_state
!= BUFFER_STATE_INITIALIZED
)
402 audio_reset_buffer();
404 case AUDIO_WANT_VOICE
:
405 if (buffer_state
== BUFFER_STATE_TRASHED
)
406 audio_reset_buffer();
413 unsigned char *audio_get_buffer(bool talk_buf
, size_t *buffer_size
)
415 unsigned char *buf
, *end
;
417 if (audio_is_initialized
)
421 /* else buffer_state will be BUFFER_STATE_TRASHED at this point */
423 if (buffer_size
== NULL
)
425 /* Special case for talk_init to use since it already knows it's
427 buffer_state
= BUFFER_STATE_TRASHED
;
431 if (talk_buf
|| buffer_state
== BUFFER_STATE_TRASHED
432 || !talk_voice_required())
434 logf("get buffer: talk, audio");
435 /* Ok to use everything from audiobuf to audiobufend - voice is loaded,
436 the talk buffer is not needed because voice isn't being used, or
437 could be BUFFER_STATE_TRASHED already. If state is
438 BUFFER_STATE_VOICED_ONLY, no problem as long as memory isn't written
439 without the caller knowing what's going on. Changing certain settings
440 may move it to a worse condition but the memory in use by something
441 else will remain undisturbed.
443 if (buffer_state
!= BUFFER_STATE_TRASHED
)
446 buffer_state
= BUFFER_STATE_TRASHED
;
454 /* Safe to just return this if already BUFFER_STATE_VOICED_ONLY or
455 still BUFFER_STATE_INITIALIZED */
456 /* Skip talk buffer and move pcm buffer to end to maximize available
457 contiguous memory - no audio running means voice will not need the
459 logf("get buffer: audio");
460 buf
= audiobuf
+ talk_get_bufsize();
461 end
= audiobufend
- pcmbuf_init(audiobufend
);
462 buffer_state
= BUFFER_STATE_VOICED_ONLY
;
465 *buffer_size
= end
- buf
;
470 #ifdef HAVE_RECORDING
471 unsigned char *audio_get_recording_buffer(size_t *buffer_size
)
473 /* Stop audio, voice and obtain all available buffer space */
477 unsigned char *end
= audiobufend
;
478 buffer_state
= BUFFER_STATE_TRASHED
;
479 *buffer_size
= end
- audiobuf
;
481 return (unsigned char *)audiobuf
;
484 bool audio_load_encoder(int afmt
)
487 const char *enc_fn
= get_codec_filename(afmt
| CODEC_TYPE_ENCODER
);
491 audio_remove_encoder();
492 ci
.enc_codec_loaded
= 0; /* clear any previous error condition */
494 LOGFQUEUE("codec > Q_ENCODER_LOAD_DISK");
495 queue_post(&codec_queue
, Q_ENCODER_LOAD_DISK
, (intptr_t)enc_fn
);
497 while (ci
.enc_codec_loaded
== 0)
500 logf("codec loaded: %d", ci
.enc_codec_loaded
);
502 return ci
.enc_codec_loaded
> 0;
507 } /* audio_load_encoder */
509 void audio_remove_encoder(void)
512 /* force encoder codec unload (if currently loaded) */
513 if (ci
.enc_codec_loaded
<= 0)
516 ci
.stop_encoder
= true;
517 while (ci
.enc_codec_loaded
> 0)
520 } /* audio_remove_encoder */
522 #endif /* HAVE_RECORDING */
525 int audio_current_aa_hid(void)
528 int offset
= ci
.new_track
+ wps_offset
;
530 cur_idx
= track_ridx
+ offset
;
531 cur_idx
&= MAX_TRACK_MASK
;
533 return tracks
[cur_idx
].aa_hid
;
537 struct mp3entry
* audio_current_track(void)
539 const char *filename
;
541 static struct mp3entry temp_id3
;
543 int offset
= ci
.new_track
+ wps_offset
;
545 cur_idx
= (track_ridx
+ offset
) & MAX_TRACK_MASK
;
547 if (cur_idx
== track_ridx
&& *curtrack_id3
.path
)
550 return &curtrack_id3
;
552 else if (offset
== -1 && *prevtrack_id3
.path
)
554 /* We're in a track transition. The codec has moved on to the nex track,
555 but the audio being played is still the same (now previous) track.
556 prevtrack_id3.elapsed is being updated in an ISR by
557 codec_pcmbuf_position_callback */
558 return &prevtrack_id3
;
560 else if (tracks
[cur_idx
].id3_hid
>= 0)
562 /* Get the ID3 metadata from the main buffer */
563 return bufgetid3(tracks
[cur_idx
].id3_hid
);
566 /* We didn't find the ID3 metadata, so we fill temp_id3 with the little info
567 we have and return that. */
569 memset(&temp_id3
, 0, sizeof(struct mp3entry
));
571 filename
= playlist_peek(0);
573 filename
= "No file!";
575 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
576 if (tagcache_fill_tags(&temp_id3
, filename
))
580 p
= strrchr(filename
, '/');
586 strncpy(temp_id3
.path
, p
, sizeof(temp_id3
.path
)-1);
587 temp_id3
.title
= &temp_id3
.path
[0];
592 struct mp3entry
* audio_next_track(void)
595 int offset
= ci
.new_track
+ wps_offset
;
597 if (!audio_have_tracks())
600 if (wps_offset
== -1 && *prevtrack_id3
.path
)
602 /* We're in a track transition. The next track for the WPS is the one
603 currently being decoded. */
604 return &curtrack_id3
;
607 next_idx
= (track_ridx
+ offset
+ 1) & MAX_TRACK_MASK
;
609 if (next_idx
== track_widx
)
611 /* The next track hasn't been buffered yet, so we return the static
612 version of its metadata. */
613 return &lasttrack_id3
;
616 if (tracks
[next_idx
].id3_hid
< 0)
619 return bufgetid3(tracks
[next_idx
].id3_hid
);
622 bool audio_has_changed_track(void)
626 track_changed
= false;
633 void audio_play(long offset
)
637 #ifdef PLAYBACK_VOICE
638 /* Truncate any existing voice output so we don't have spelling
639 * etc. over the first part of the played track */
644 LOGFQUEUE("audio >| audio Q_AUDIO_PLAY: %ld", offset
);
645 /* Don't return until playback has actually started */
646 queue_send(&audio_queue
, Q_AUDIO_PLAY
, offset
);
649 void audio_stop(void)
652 LOGFQUEUE("audio >| audio Q_AUDIO_STOP");
653 /* Don't return until playback has actually stopped */
654 queue_send(&audio_queue
, Q_AUDIO_STOP
, 0);
657 void audio_pause(void)
659 LOGFQUEUE("audio >| audio Q_AUDIO_PAUSE");
660 /* Don't return until playback has actually paused */
661 queue_send(&audio_queue
, Q_AUDIO_PAUSE
, true);
664 void audio_resume(void)
666 LOGFQUEUE("audio >| audio Q_AUDIO_PAUSE resume");
667 /* Don't return until playback has actually resumed */
668 queue_send(&audio_queue
, Q_AUDIO_PAUSE
, false);
671 static void audio_skip(int direction
)
673 if (playlist_check(ci
.new_track
+ wps_offset
+ direction
))
675 if (global_settings
.beep
)
676 pcmbuf_beep(5000, 100, 2500*global_settings
.beep
);
678 LOGFQUEUE("audio > audio Q_AUDIO_SKIP %d", direction
);
679 queue_post(&audio_queue
, Q_AUDIO_SKIP
, direction
);
680 /* Update wps while our message travels inside deep playback queues. */
681 wps_offset
+= direction
;
682 /* Immediately update the playlist index */
683 playlist_next(direction
);
684 track_changed
= true;
688 /* No more tracks. */
689 if (global_settings
.beep
)
690 pcmbuf_beep(1000, 100, 1000*global_settings
.beep
);
694 void audio_next(void)
699 void audio_prev(void)
704 void audio_next_dir(void)
706 LOGFQUEUE("audio > audio Q_AUDIO_DIR_SKIP 1");
707 queue_post(&audio_queue
, Q_AUDIO_DIR_SKIP
, 1);
710 void audio_prev_dir(void)
712 LOGFQUEUE("audio > audio Q_AUDIO_DIR_SKIP -1");
713 queue_post(&audio_queue
, Q_AUDIO_DIR_SKIP
, -1);
716 void audio_pre_ff_rewind(void)
718 LOGFQUEUE("audio > audio Q_AUDIO_PRE_FF_REWIND");
719 queue_post(&audio_queue
, Q_AUDIO_PRE_FF_REWIND
, 0);
722 void audio_ff_rewind(long newpos
)
724 LOGFQUEUE("audio > audio Q_AUDIO_FF_REWIND");
725 queue_post(&audio_queue
, Q_AUDIO_FF_REWIND
, newpos
);
728 void audio_flush_and_reload_tracks(void)
730 LOGFQUEUE("audio > audio Q_AUDIO_FLUSH");
731 queue_post(&audio_queue
, Q_AUDIO_FLUSH
, 0);
734 void audio_error_clear(void)
736 #ifdef AUDIO_HAVE_RECORDING
737 pcm_rec_error_clear();
741 int audio_status(void)
746 ret
|= AUDIO_STATUS_PLAY
;
749 ret
|= AUDIO_STATUS_PAUSE
;
751 #ifdef HAVE_RECORDING
752 /* Do this here for constitency with mpeg.c version */
753 ret
|= pcm_rec_status();
759 int audio_get_file_pos(void)
764 #ifndef HAVE_FLASH_STORAGE
765 void audio_set_buffer_margin(int setting
)
767 static const int lookup
[] = {5, 15, 30, 60, 120, 180, 300, 600};
768 buffer_margin
= lookup
[setting
];
769 logf("buffer margin: %ld", (long)buffer_margin
);
770 set_filebuf_watermark(buffer_margin
, 0);
774 /* Take necessary steps to enable or disable the crossfade setting */
775 void audio_set_crossfade(int enable
)
781 /* Tell it the next setting to use */
782 pcmbuf_crossfade_enable(enable
);
784 /* Return if size hasn't changed or this is too early to determine
785 which in the second case there's no way we could be playing
787 if (pcmbuf_is_same_size())
789 /* This function is a copout and just syncs some variables -
790 to be removed at a later date */
791 pcmbuf_crossfade_enable_finished();
796 was_playing
= playing
;
798 /* Playback has to be stopped before changing the buffer size */
801 /* Store the track resume position */
802 offset
= curtrack_id3
.offset
;
803 gui_syncsplash(0, str(LANG_RESTARTING_PLAYBACK
));
806 /* Blast it - audio buffer will have to be setup again next time
808 audio_get_buffer(true, &size
);
810 /* Restart playback if audio was running previously */
815 /* --- Routines called from multiple threads --- */
817 static void set_filebuf_watermark(int seconds
, size_t max
)
822 return; /* Audio buffers not yet set up */
824 bytes
= seconds
?MAX(curtrack_id3
.bitrate
* seconds
* (1000/8), max
):max
;
825 bytes
= MIN(bytes
, filebuflen
/ 2);
826 buf_set_watermark(bytes
);
829 const char *get_codec_filename(int cod_spec
)
833 #ifdef HAVE_RECORDING
834 /* Can choose decoder or encoder if one available */
835 int type
= cod_spec
& CODEC_TYPE_MASK
;
836 int afmt
= cod_spec
& CODEC_AFMT_MASK
;
838 if ((unsigned)afmt
>= AFMT_NUM_CODECS
)
839 type
= AFMT_UNKNOWN
| (type
& CODEC_TYPE_MASK
);
841 fname
= (type
== CODEC_TYPE_ENCODER
) ?
842 audio_formats
[afmt
].codec_enc_root_fn
:
843 audio_formats
[afmt
].codec_root_fn
;
846 (type
== CODEC_TYPE_ENCODER
) ? "Encoder" : "Decoder",
847 afmt
, fname
? fname
: "<unknown>");
848 #else /* !HAVE_RECORDING */
850 if ((unsigned)cod_spec
>= AFMT_NUM_CODECS
)
851 cod_spec
= AFMT_UNKNOWN
;
852 fname
= audio_formats
[cod_spec
].codec_root_fn
;
853 logf("Codec: %d - %s", cod_spec
, fname
? fname
: "<unknown>");
854 #endif /* HAVE_RECORDING */
857 } /* get_codec_filename */
859 /* --- Codec thread --- */
860 static bool codec_pcmbuf_insert_callback(
861 const void *ch1
, const void *ch2
, int count
)
863 const char *src
[2] = { ch1
, ch2
};
867 int out_count
= dsp_output_count(ci
.dsp
, count
);
871 /* Prevent audio from a previous track from playing */
872 if (ci
.new_track
|| ci
.stop_codec
)
875 while ((dest
= pcmbuf_request_buffer(&out_count
)) == NULL
)
879 if (ci
.seek_time
|| ci
.new_track
|| ci
.stop_codec
)
883 /* Get the real input_size for output_size bytes, guarding
884 * against resampling buffer overflows. */
885 inp_count
= dsp_input_count(ci
.dsp
, out_count
);
890 /* Input size has grown, no error, just don't write more than length */
891 if (inp_count
> count
)
894 out_count
= dsp_process(ci
.dsp
, dest
, src
, inp_count
);
899 pcmbuf_write_complete(out_count
);
905 } /* codec_pcmbuf_insert_callback */
907 static void* codec_get_memory_callback(size_t *size
)
909 *size
= MALLOC_BUFSIZE
;
913 /* Between the codec and PCM track change, we need to keep updating the
914 "elapsed" value of the previous (to the codec, but current to the
915 user/PCM/WPS) track, so that the progressbar reaches the end.
916 During that transition, the WPS will display prevtrack_id3. */
917 static void codec_pcmbuf_position_callback(size_t size
) ICODE_ATTR
;
918 static void codec_pcmbuf_position_callback(size_t size
)
920 /* This is called from an ISR, so be quick */
921 unsigned int time
= size
* 1000 / 4 / NATIVE_FREQUENCY
+
922 prevtrack_id3
.elapsed
;
924 if (time
>= prevtrack_id3
.length
)
926 pcmbuf_set_position_callback(NULL
);
927 prevtrack_id3
.elapsed
= prevtrack_id3
.length
;
930 prevtrack_id3
.elapsed
= time
;
933 static void codec_set_elapsed_callback(unsigned int value
)
935 unsigned int latency
;
939 #ifdef AB_REPEAT_ENABLE
940 ab_position_report(value
);
943 latency
= pcmbuf_get_latency();
945 curtrack_id3
.elapsed
= 0;
946 else if (value
- latency
> curtrack_id3
.elapsed
||
947 value
- latency
< curtrack_id3
.elapsed
- 2)
949 curtrack_id3
.elapsed
= value
- latency
;
953 static void codec_set_offset_callback(size_t value
)
955 unsigned int latency
;
960 latency
= pcmbuf_get_latency() * curtrack_id3
.bitrate
/ 8;
962 curtrack_id3
.offset
= 0;
964 curtrack_id3
.offset
= value
- latency
;
967 static void codec_advance_buffer_counters(size_t amount
)
969 bufadvance(CUR_TI
->audio_hid
, amount
);
973 /* copy up-to size bytes into ptr and return the actual size copied */
974 static size_t codec_filebuf_callback(void *ptr
, size_t size
)
978 if (ci
.stop_codec
|| !playing
)
981 copy_n
= bufread(CUR_TI
->audio_hid
, size
, ptr
);
983 /* Nothing requested OR nothing left */
987 /* Update read and other position pointers */
988 codec_advance_buffer_counters(copy_n
);
990 /* Return the actual amount of data copied to the buffer */
992 } /* codec_filebuf_callback */
994 static void* codec_request_buffer_callback(size_t *realsize
, size_t reqsize
)
996 size_t copy_n
= reqsize
;
1006 ret
= bufgetdata(CUR_TI
->audio_hid
, reqsize
, &ptr
);
1008 copy_n
= MIN((size_t)ret
, reqsize
);
1019 } /* codec_request_buffer_callback */
1021 static int get_codec_base_type(int type
)
1033 static void codec_advance_buffer_callback(size_t amount
)
1035 codec_advance_buffer_counters(amount
);
1036 codec_set_offset_callback(ci
.curpos
);
1039 static void codec_advance_buffer_loc_callback(void *ptr
)
1041 size_t amount
= buf_get_offset(CUR_TI
->audio_hid
, ptr
);
1042 codec_advance_buffer_callback(amount
);
1045 /* Copied from mpeg.c. Should be moved somewhere else. */
1046 static int codec_get_file_pos(void)
1049 struct mp3entry
*id3
= audio_current_track();
1055 /* Use the TOC to find the new position */
1056 unsigned int percent
, remainder
;
1057 int curtoc
, nexttoc
, plen
;
1059 percent
= (id3
->elapsed
*100)/id3
->length
;
1063 curtoc
= id3
->toc
[percent
];
1066 nexttoc
= id3
->toc
[percent
+1];
1070 pos
= (id3
->filesize
/256)*curtoc
;
1072 /* Use the remainder to get a more accurate position */
1073 remainder
= (id3
->elapsed
*100)%id3
->length
;
1074 remainder
= (remainder
*100)/id3
->length
;
1075 plen
= (nexttoc
- curtoc
)*(id3
->filesize
/256);
1076 pos
+= (plen
/100)*remainder
;
1080 /* No TOC exists, estimate the new position */
1081 pos
= (id3
->filesize
/ (id3
->length
/ 1000)) *
1082 (id3
->elapsed
/ 1000);
1085 else if (id3
->bitrate
)
1086 pos
= id3
->elapsed
* (id3
->bitrate
/ 8);
1090 pos
+= id3
->first_frame_offset
;
1092 /* Don't seek right to the end of the file so that we can
1093 transition properly to the next song */
1094 if (pos
>= (int)(id3
->filesize
- id3
->id3v1len
))
1095 pos
= id3
->filesize
- id3
->id3v1len
- 1;
1100 static off_t
codec_mp3_get_filepos_callback(int newtime
)
1104 curtrack_id3
.elapsed
= newtime
;
1105 newpos
= codec_get_file_pos();
1110 static void codec_seek_complete_callback(void)
1112 logf("seek_complete");
1113 if (pcm_is_paused())
1115 /* If this is not a seamless seek, clear the buffer */
1117 dsp_configure(ci
.dsp
, DSP_FLUSH
, 0);
1119 /* If playback was not 'deliberately' paused, unpause now */
1121 pcmbuf_pause(false);
1126 static bool codec_seek_buffer_callback(size_t newpos
)
1128 logf("codec_seek_buffer_callback");
1130 int ret
= bufseek(CUR_TI
->audio_hid
, newpos
);
1140 static void codec_configure_callback(int setting
, intptr_t value
)
1143 case CODEC_SET_FILEBUF_WATERMARK
:
1144 set_filebuf_watermark(buffer_margin
, value
);
1148 if (!dsp_configure(ci
.dsp
, setting
, value
))
1149 { logf("Illegal key:%d", setting
); }
1153 static void codec_track_changed(void)
1155 LOGFQUEUE("codec > audio Q_AUDIO_TRACK_CHANGED");
1156 queue_post(&audio_queue
, Q_AUDIO_TRACK_CHANGED
, 0);
1159 static void codec_pcmbuf_track_changed_callback(void)
1161 pcmbuf_set_position_callback(NULL
);
1162 pcmbuf_callback_queue_post(Q_AUDIO_TRACK_CHANGED
, 0);
1165 static void codec_discard_codec_callback(void)
1167 if (CUR_TI
->codec_hid
>= 0)
1169 bufclose(CUR_TI
->codec_hid
);
1170 CUR_TI
->codec_hid
= -1;
1174 static inline void codec_gapless_track_change(void)
1176 /* callback keeps the progress bar moving while the pcmbuf empties */
1177 pcmbuf_set_position_callback(codec_pcmbuf_position_callback
);
1178 /* set the pcmbuf callback for when the track really changes */
1179 pcmbuf_set_event_handler(codec_pcmbuf_track_changed_callback
);
1182 static inline void codec_crossfade_track_change(void)
1184 /* Initiate automatic crossfade mode */
1185 pcmbuf_crossfade_init(false);
1186 /* Notify the wps that the track change starts now */
1187 codec_track_changed();
1190 static void codec_track_skip_done(bool was_manual
)
1192 /* Manual track change (always crossfade or flush audio). */
1195 pcmbuf_crossfade_init(true);
1196 LOGFQUEUE("codec > audio Q_AUDIO_TRACK_CHANGED");
1197 queue_post(&audio_queue
, Q_AUDIO_TRACK_CHANGED
, 0);
1199 /* Automatic track change w/crossfade, if not in "Track Skip Only" mode. */
1200 else if (pcmbuf_is_crossfade_enabled() && !pcmbuf_is_crossfade_active()
1201 && global_settings
.crossfade
!= CROSSFADE_ENABLE_TRACKSKIP
)
1203 if (global_settings
.crossfade
== CROSSFADE_ENABLE_SHUFFLE_AND_TRACKSKIP
)
1205 if (global_settings
.playlist_shuffle
)
1206 /* shuffle mode is on, so crossfade: */
1207 codec_crossfade_track_change();
1209 /* shuffle mode is off, so do a gapless track change */
1210 codec_gapless_track_change();
1213 /* normal crossfade: */
1214 codec_crossfade_track_change();
1217 /* normal gapless playback. */
1218 codec_gapless_track_change();
1221 static bool codec_load_next_track(void)
1223 intptr_t result
= Q_CODEC_REQUEST_FAILED
;
1225 prev_track_elapsed
= curtrack_id3
.elapsed
;
1227 #ifdef AB_REPEAT_ENABLE
1228 ab_end_of_track_report();
1231 logf("Request new track");
1233 if (ci
.new_track
== 0)
1236 automatic_skip
= true;
1241 trigger_cpu_boost();
1242 LOGFQUEUE("codec >| audio Q_AUDIO_CHECK_NEW_TRACK");
1243 result
= queue_send(&audio_queue
, Q_AUDIO_CHECK_NEW_TRACK
, 0);
1248 case Q_CODEC_REQUEST_COMPLETE
:
1249 LOGFQUEUE("codec |< Q_CODEC_REQUEST_COMPLETE");
1250 codec_track_skip_done(!automatic_skip
);
1253 case Q_CODEC_REQUEST_FAILED
:
1254 LOGFQUEUE("codec |< Q_CODEC_REQUEST_FAILED");
1256 ci
.stop_codec
= true;
1257 codec_requested_stop
= true;
1261 LOGFQUEUE("codec |< default");
1262 ci
.stop_codec
= true;
1263 codec_requested_stop
= true;
1268 static bool codec_request_next_track_callback(void)
1272 if (ci
.stop_codec
|| !playing
)
1275 prev_codectype
= get_codec_base_type(curtrack_id3
.codectype
);
1277 if (!codec_load_next_track())
1280 /* Check if the next codec is the same file. */
1281 if (prev_codectype
== get_codec_base_type(curtrack_id3
.codectype
))
1283 logf("New track loaded");
1284 codec_discard_codec_callback();
1289 logf("New codec:%d/%d", curtrack_id3
.codectype
, prev_codectype
);
1294 static void codec_thread(void)
1296 struct queue_event ev
;
1302 queue_wait(&codec_queue
, &ev
);
1303 codec_requested_stop
= false;
1306 case Q_CODEC_LOAD_DISK
:
1307 LOGFQUEUE("codec < Q_CODEC_LOAD_DISK");
1308 queue_reply(&codec_queue
, 1);
1309 audio_codec_loaded
= true;
1310 ci
.stop_codec
= false;
1311 status
= codec_load_file((const char *)ev
.data
, &ci
);
1315 LOGFQUEUE("codec < Q_CODEC_LOAD");
1316 if (CUR_TI
->codec_hid
< 0) {
1317 logf("Codec slot is empty!");
1318 /* Wait for the pcm buffer to go empty */
1319 while (pcm_is_playing())
1321 /* This must be set to prevent an infinite loop */
1322 ci
.stop_codec
= true;
1323 LOGFQUEUE("codec > codec Q_AUDIO_PLAY");
1324 queue_post(&codec_queue
, Q_AUDIO_PLAY
, 0);
1328 audio_codec_loaded
= true;
1329 ci
.stop_codec
= false;
1330 status
= codec_load_buf(CUR_TI
->codec_hid
, &ci
);
1333 #ifdef AUDIO_HAVE_RECORDING
1334 case Q_ENCODER_LOAD_DISK
:
1335 LOGFQUEUE("codec < Q_ENCODER_LOAD_DISK");
1336 audio_codec_loaded
= false; /* Not audio codec! */
1337 logf("loading encoder");
1338 ci
.stop_encoder
= false;
1339 status
= codec_load_file((const char *)ev
.data
, &ci
);
1340 logf("encoder stopped");
1342 #endif /* AUDIO_HAVE_RECORDING */
1345 LOGFQUEUE("codec < default");
1348 if (audio_codec_loaded
)
1357 audio_codec_loaded
= false;
1361 case Q_CODEC_LOAD_DISK
:
1363 LOGFQUEUE("codec < Q_CODEC_LOAD");
1366 if (ci
.new_track
|| status
!= CODEC_OK
)
1370 logf("Codec failure");
1371 gui_syncsplash(HZ
*2, "Codec failure");
1374 if (!codec_load_next_track())
1376 LOGFQUEUE("codec > audio Q_AUDIO_STOP");
1377 /* End of playlist */
1378 queue_post(&audio_queue
, Q_AUDIO_STOP
, 0);
1384 logf("Codec finished");
1387 /* Wait for the audio to stop playing before
1388 * triggering the WPS exit */
1389 while(pcm_is_playing())
1391 curtrack_id3
.elapsed
=
1392 curtrack_id3
.length
- pcmbuf_get_latency();
1396 if (codec_requested_stop
)
1398 LOGFQUEUE("codec > audio Q_AUDIO_STOP");
1399 queue_post(&audio_queue
, Q_AUDIO_STOP
, 0);
1405 if (CUR_TI
->codec_hid
>= 0)
1407 LOGFQUEUE("codec > codec Q_CODEC_LOAD");
1408 queue_post(&codec_queue
, Q_CODEC_LOAD
, 0);
1412 const char *codec_fn
=
1413 get_codec_filename(curtrack_id3
.codectype
);
1416 LOGFQUEUE("codec > codec Q_CODEC_LOAD_DISK");
1417 queue_post(&codec_queue
, Q_CODEC_LOAD_DISK
,
1418 (intptr_t)codec_fn
);
1424 #ifdef AUDIO_HAVE_RECORDING
1425 case Q_ENCODER_LOAD_DISK
:
1426 LOGFQUEUE("codec < Q_ENCODER_LOAD_DISK");
1428 if (status
== CODEC_OK
)
1431 logf("Encoder failure");
1432 gui_syncsplash(HZ
*2, "Encoder failure");
1434 if (ci
.enc_codec_loaded
< 0)
1437 logf("Encoder failed to load");
1438 ci
.enc_codec_loaded
= -1;
1440 #endif /* AUDIO_HAVE_RECORDING */
1443 LOGFQUEUE("codec < default");
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 CUR_TI
->taginfo_ready
= (CUR_TI
->id3_hid
>= 0);
1480 if (CUR_TI
->id3_hid
>= 0)
1481 copy_mp3entry(&curtrack_id3
, bufgetid3(CUR_TI
->id3_hid
));
1483 int next_idx
= (track_ridx
+ 1) & MAX_TRACK_MASK
;
1484 tracks
[next_idx
].taginfo_ready
= (tracks
[next_idx
].id3_hid
>= 0);
1486 /* Reset current position */
1487 curtrack_id3
.elapsed
= 0;
1488 curtrack_id3
.offset
= 0;
1490 /* Update the codec API */
1491 ci
.filesize
= CUR_TI
->filesize
;
1492 ci
.id3
= &curtrack_id3
;
1494 ci
.taginfo_ready
= &CUR_TI
->taginfo_ready
;
1497 static void buffering_audio_callback(enum callback_event ev
, int value
)
1500 logf("buffering_audio_callback");
1504 case EVENT_BUFFER_LOW
:
1505 if (filling
== STATE_FULL
) {
1506 /* force a refill */
1507 LOGFQUEUE("buffering > audio Q_AUDIO_FILL_BUFFER");
1508 queue_post(&audio_queue
, Q_AUDIO_FILL_BUFFER
, 0);
1512 case EVENT_HANDLE_REBUFFER
:
1513 LOGFQUEUE("audio >| audio Q_AUDIO_FLUSH");
1514 queue_send(&audio_queue
, Q_AUDIO_FLUSH
, 0);
1517 case EVENT_HANDLE_FINISHED
:
1518 logf("handle %d finished buffering", value
);
1527 /* Clear tracks between write and read, non inclusive */
1528 static void audio_clear_track_entries(void)
1530 int cur_idx
= track_widx
;
1532 logf("Clearing tracks:%d/%d", track_ridx
, track_widx
);
1534 /* Loop over all tracks from write-to-read */
1537 cur_idx
= (cur_idx
+ 1) & MAX_TRACK_MASK
;
1539 if (cur_idx
== track_ridx
)
1542 clear_track_info(&tracks
[cur_idx
]);
1546 /* Clear all tracks */
1547 static bool audio_release_tracks(void)
1551 logf("releasing all tracks");
1553 for(i
= 0; i
< MAX_TRACK
; i
++)
1555 cur_idx
= (track_ridx
+ i
) & MAX_TRACK_MASK
;
1556 if (!clear_track_info(&tracks
[cur_idx
]))
1563 static bool audio_loadcodec(bool start_play
)
1566 char codec_path
[MAX_PATH
]; /* Full path to codec */
1568 if (tracks
[track_widx
].id3_hid
< 0) {
1572 const char * codec_fn
=
1573 get_codec_filename(bufgetid3(tracks
[track_widx
].id3_hid
)->codectype
);
1574 if (codec_fn
== NULL
)
1577 tracks
[track_widx
].codec_hid
= -1;
1581 /* Load the codec directly from disk and save some memory. */
1582 track_ridx
= track_widx
;
1583 ci
.filesize
= CUR_TI
->filesize
;
1584 ci
.id3
= &curtrack_id3
;
1585 ci
.taginfo_ready
= &CUR_TI
->taginfo_ready
;
1587 LOGFQUEUE("codec > codec Q_CODEC_LOAD_DISK");
1588 queue_post(&codec_queue
, Q_CODEC_LOAD_DISK
, (intptr_t)codec_fn
);
1593 /* If we already have another track than this one buffered */
1594 if (track_widx
!= track_ridx
)
1596 prev_track
= (track_widx
- 1) & MAX_TRACK_MASK
;
1598 /* If the previous codec is the same as this one, there is no need
1599 * to put another copy of it on the file buffer */
1600 if (get_codec_base_type(
1601 bufgetid3(tracks
[track_widx
].id3_hid
)->codectype
) ==
1602 get_codec_base_type(
1603 bufgetid3(tracks
[prev_track
].id3_hid
)->codectype
)
1604 && audio_codec_loaded
)
1606 logf("Reusing prev. codec");
1612 codec_get_full_path(codec_path
, codec_fn
);
1614 tracks
[track_widx
].codec_hid
= bufopen(codec_path
, 0, TYPE_CODEC
);
1615 if (tracks
[track_widx
].codec_hid
< 0)
1618 logf("Loaded codec");
1623 /* TODO: Copied from mpeg.c. Should be moved somewhere else. */
1624 static void audio_set_elapsed(struct mp3entry
* id3
)
1626 unsigned long offset
= id3
->offset
> id3
->first_frame_offset
?
1627 id3
->offset
- id3
->first_frame_offset
: 0;
1630 if ( id3
->has_toc
) {
1631 /* calculate elapsed time using TOC */
1633 unsigned int remainder
, plen
, relpos
, nextpos
;
1635 /* find wich percent we're at */
1636 for (i
=0; i
<100; i
++ )
1637 if ( offset
< id3
->toc
[i
] * (id3
->filesize
/ 256) )
1644 relpos
= id3
->toc
[i
];
1647 nextpos
= id3
->toc
[i
+1];
1651 remainder
= offset
- (relpos
* (id3
->filesize
/ 256));
1653 /* set time for this percent (divide before multiply to prevent
1654 overflow on long files. loss of precision is negligible on
1656 id3
->elapsed
= i
* (id3
->length
/ 100);
1658 /* calculate remainder time */
1659 plen
= (nextpos
- relpos
) * (id3
->filesize
/ 256);
1660 id3
->elapsed
+= (((remainder
* 100) / plen
) *
1661 (id3
->length
/ 10000));
1664 /* no TOC exists. set a rough estimate using average bitrate */
1665 int tpk
= id3
->length
/
1666 ((id3
->filesize
- id3
->first_frame_offset
- id3
->id3v1len
) /
1668 id3
->elapsed
= offset
/ 1024 * tpk
;
1673 /* constant bitrate, use exact calculation */
1674 if (id3
->bitrate
!= 0)
1675 id3
->elapsed
= offset
/ (id3
->bitrate
/ 8);
1679 /* Load one track by making the appropriate bufopen calls. Return true if
1680 everything required was loaded correctly, false if not. */
1681 static bool audio_load_track(int offset
, bool start_play
)
1683 const char *trackname
;
1686 int file_offset
= 0;
1687 struct mp3entry id3
;
1689 /* Stop buffer filling if there is no free track entries.
1690 Don't fill up the last track entry (we wan't to store next track
1692 if (!audio_free_track_count())
1694 logf("No free tracks");
1699 tracks
[track_widx
].taginfo_ready
= false;
1702 logf("Buffering track:%d/%d", track_widx
, track_ridx
);
1703 /* Get track name from current playlist read position. */
1704 while ((trackname
= playlist_peek(last_peek_offset
)) != NULL
)
1706 /* Handle broken playlists. */
1707 fd
= open(trackname
, O_RDONLY
);
1710 logf("Open failed");
1711 /* Skip invalid entry from playlist. */
1712 playlist_skip_entry(NULL
, last_peek_offset
);
1720 logf("End-of-playlist");
1721 playlist_end
= true;
1722 memset(&lasttrack_id3
, 0, sizeof(struct mp3entry
));
1723 filling
= STATE_FINISHED
;
1727 tracks
[track_widx
].filesize
= filesize(fd
);
1729 if ((unsigned)offset
> tracks
[track_widx
].filesize
)
1732 /* Set default values */
1735 buf_set_watermark(AUDIO_DEFAULT_WATERMARK
);
1736 dsp_configure(ci
.dsp
, DSP_RESET
, 0);
1737 track_changed
= true;
1738 playlist_update_resume_info(audio_current_track());
1741 /* Get track metadata if we don't already have it. */
1742 if (tracks
[track_widx
].id3_hid
< 0)
1744 if (get_metadata(&id3
, fd
, trackname
))
1746 send_event(PLAYBACK_EVENT_TRACK_BUFFER
, &id3
);
1748 tracks
[track_widx
].id3_hid
=
1749 bufalloc(&id3
, sizeof(struct mp3entry
), TYPE_ID3
);
1751 if (tracks
[track_widx
].id3_hid
< 0)
1755 copy_mp3entry(&lasttrack_id3
, &id3
);
1759 if (track_widx
== track_ridx
)
1760 copy_mp3entry(&curtrack_id3
, &id3
);
1764 track_changed
= true;
1765 playlist_update_resume_info(audio_current_track());
1770 logf("mde:%s!",trackname
);
1772 /* Skip invalid entry from playlist. */
1773 playlist_skip_entry(NULL
, last_peek_offset
);
1783 if (cuesheet_is_enabled() && tracks
[track_widx
].id3
.cuesheet_type
== 1)
1785 char cuepath
[MAX_PATH
];
1787 struct cuesheet
*cue
= start_play
? curr_cue
: temp_cue
;
1789 if (look_for_cuesheet_file(trackname
, cuepath
) &&
1790 parse_cuesheet(cuepath
, cue
))
1792 strcpy((cue
)->audio_filename
, trackname
);
1794 cue_spoof_id3(curr_cue
, &tracks
[track_widx
].id3
);
1799 struct mp3entry
*track_id3
;
1801 if (track_widx
== track_ridx
)
1802 track_id3
= &curtrack_id3
;
1804 track_id3
= bufgetid3(tracks
[track_widx
].id3_hid
);
1806 #ifdef HAVE_ALBUMART
1807 if (tracks
[track_widx
].aa_hid
< 0 && gui_sync_wps_uses_albumart())
1809 char aa_path
[MAX_PATH
];
1810 if (find_albumart(track_id3
, aa_path
, sizeof(aa_path
)))
1811 tracks
[track_widx
].aa_hid
= bufopen(aa_path
, 0, TYPE_BITMAP
);
1815 /* Load the codec. */
1816 if (!audio_loadcodec(start_play
))
1818 if (tracks
[track_widx
].codec_hid
== ERR_BUFFER_FULL
)
1820 /* No space for codec on buffer, not an error */
1824 /* This is an error condition, either no codec was found, or reading
1825 * the codec file failed part way through, either way, skip the track */
1826 snprintf(msgbuf
, sizeof(msgbuf
)-1, "No codec for: %s", trackname
);
1827 /* We should not use gui_syncplash from audio thread! */
1828 gui_syncsplash(HZ
*2, msgbuf
);
1829 /* Skip invalid entry from playlist. */
1830 playlist_skip_entry(NULL
, last_peek_offset
);
1834 track_id3
->elapsed
= 0;
1836 enum data_type type
= TYPE_PACKET_AUDIO
;
1838 switch (track_id3
->codectype
) {
1843 file_offset
= offset
;
1844 track_id3
->offset
= offset
;
1845 audio_set_elapsed(track_id3
);
1851 file_offset
= offset
;
1852 track_id3
->offset
= offset
;
1853 track_id3
->elapsed
= track_id3
->length
/ 2;
1857 case AFMT_OGG_VORBIS
:
1866 track_id3
->offset
= offset
;
1872 logf("Loading atomic %d",track_id3
->codectype
);
1873 type
= TYPE_ATOMIC_AUDIO
;
1877 logf("alt:%s", trackname
);
1879 if (file_offset
> AUDIO_REBUFFER_GUESS_SIZE
)
1880 file_offset
-= AUDIO_REBUFFER_GUESS_SIZE
;
1881 else if (track_id3
->first_frame_offset
)
1882 file_offset
= track_id3
->first_frame_offset
;
1886 tracks
[track_widx
].audio_hid
= bufopen(trackname
, file_offset
, type
);
1888 if (tracks
[track_widx
].audio_hid
< 0)
1891 /* All required data is now available for the codec. */
1892 tracks
[track_widx
].taginfo_ready
= true;
1896 ci
.curpos
=file_offset
;
1897 buf_request_buffer_handle(tracks
[track_widx
].audio_hid
);
1900 track_widx
= (track_widx
+ 1) & MAX_TRACK_MASK
;
1905 logf("buffer is full for now");
1906 filling
= STATE_FULL
;
1910 static void audio_fill_file_buffer(bool start_play
, size_t offset
)
1912 struct queue_event ev
;
1913 bool had_next_track
= audio_next_track() != NULL
;
1914 bool continue_buffering
;
1916 filling
= STATE_FILLING
;
1918 /* No need to rebuffer if there are track skips pending. */
1919 if (ci
.new_track
!= 0)
1922 /* Must reset the buffer before use if trashed or voice only - voice
1923 file size shouldn't have changed so we can go straight from
1924 BUFFER_STATE_VOICED_ONLY to BUFFER_STATE_INITIALIZED */
1925 if (buffer_state
!= BUFFER_STATE_INITIALIZED
)
1926 audio_reset_buffer();
1928 logf("Starting buffer fill");
1931 audio_clear_track_entries();
1933 /* Save the current resume position once. */
1934 playlist_update_resume_info(audio_current_track());
1936 continue_buffering
= audio_load_track(offset
, start_play
);
1939 if (queue_peek(&audio_queue
, &ev
))
1940 /* There's a message in the queue. break the loop to treat it */
1942 continue_buffering
= audio_load_track(0, false);
1943 } while (continue_buffering
);
1945 if (!had_next_track
&& audio_next_track())
1946 track_changed
= true;
1950 static void audio_rebuffer(void)
1952 logf("Forcing rebuffer");
1954 clear_track_info(CUR_TI
);
1956 /* Reset track pointers */
1957 track_widx
= track_ridx
;
1958 audio_clear_track_entries();
1960 /* Fill the buffer */
1961 last_peek_offset
= -1;
1964 if (!CUR_TI
->taginfo_ready
)
1965 memset(&curtrack_id3
, 0, sizeof(struct mp3entry
));
1967 audio_fill_file_buffer(false, 0);
1970 /* Called on request from the codec to get a new track. This is the codec part
1971 of the track transition. */
1972 static int audio_check_new_track(void)
1974 int track_count
= audio_track_count();
1975 int old_track_ridx
= track_ridx
;
1977 int next_playlist_index
;
1979 bool end_of_playlist
; /* Temporary flag, not the same as playlist_end */
1981 /* Now it's good time to send track unbuffer events. */
1982 send_event(PLAYBACK_EVENT_TRACK_FINISH
, &curtrack_id3
);
1987 if (playlist_next_dir(ci
.new_track
))
1995 LOGFQUEUE("audio >|= codec Q_CODEC_REQUEST_FAILED");
1996 return Q_CODEC_REQUEST_FAILED
;
2003 end_of_playlist
= playlist_peek(automatic_skip
? ci
.new_track
: 0) == NULL
;
2004 auto_dir_skip
= end_of_playlist
&& global_settings
.next_folder
;
2006 /* If the playlist isn't that big */
2007 if (automatic_skip
&& !playlist_check(ci
.new_track
))
2009 if (ci
.new_track
>= 0)
2011 LOGFQUEUE("audio >|= codec Q_CODEC_REQUEST_FAILED");
2012 return Q_CODEC_REQUEST_FAILED
;
2014 /* Find the beginning backward if the user over-skips it */
2015 while (!playlist_check(++ci
.new_track
))
2016 if (ci
.new_track
>= 0)
2018 LOGFQUEUE("audio >|= codec Q_CODEC_REQUEST_FAILED");
2019 return Q_CODEC_REQUEST_FAILED
;
2023 /* Update the playlist */
2024 last_peek_offset
-= ci
.new_track
;
2028 /* If the track change was the result of an auto dir skip,
2029 we need to update the playlist now */
2030 next_playlist_index
= playlist_next(ci
.new_track
);
2032 if (next_playlist_index
< 0)
2034 LOGFQUEUE("audio >|= codec Q_CODEC_REQUEST_FAILED");
2035 return Q_CODEC_REQUEST_FAILED
;
2042 new_playlist
= false;
2045 /* Save the track metadata to allow the WPS to display it
2046 while PCM finishes playing that track */
2047 copy_mp3entry(&prevtrack_id3
, &curtrack_id3
);
2049 /* Update the main buffer copy of the track metadata with the one
2050 the codec has been using (for the unbuffer callbacks) */
2051 if (CUR_TI
->id3_hid
>= 0)
2052 copy_mp3entry(bufgetid3(CUR_TI
->id3_hid
), &curtrack_id3
);
2054 /* Save a pointer to the old track to allow later clearing */
2057 for (i
= 0; i
< ci
.new_track
; i
++)
2059 idx
= (track_ridx
+ i
) & MAX_TRACK_MASK
;
2060 struct mp3entry
*id3
= bufgetid3(tracks
[idx
].id3_hid
);
2061 ssize_t offset
= buf_handle_offset(tracks
[idx
].audio_hid
);
2062 if (!id3
|| offset
< 0 || (unsigned)offset
> id3
->first_frame_offset
)
2064 /* We don't have all the audio data for that track, so clear it,
2065 but keep the metadata. */
2066 if (tracks
[idx
].audio_hid
>= 0 && bufclose(tracks
[idx
].audio_hid
))
2068 tracks
[idx
].audio_hid
= -1;
2069 tracks
[idx
].filesize
= 0;
2074 /* Move to the new track */
2075 track_ridx
= (track_ridx
+ ci
.new_track
) & MAX_TRACK_MASK
;
2077 buf_set_base_handle(CUR_TI
->audio_hid
);
2081 playlist_end
= false;
2082 wps_offset
= -ci
.new_track
;
2083 track_changed
= true;
2086 /* If it is not safe to even skip this many track entries */
2087 if (ci
.new_track
>= track_count
|| ci
.new_track
<= track_count
- MAX_TRACK
)
2094 forward
= ci
.new_track
> 0;
2097 /* If the target track is clearly not in memory */
2098 if (CUR_TI
->filesize
== 0 || !CUR_TI
->taginfo_ready
)
2104 /* When skipping backwards, it is possible that we've found a track that's
2105 * buffered, but which is around the track-wrap and therefor not the track
2106 * we are looking for */
2109 int cur_idx
= track_ridx
;
2110 bool taginfo_ready
= true;
2111 /* We've wrapped the buffer backwards if new > old */
2112 bool wrap
= track_ridx
> old_track_ridx
;
2116 cur_idx
= (cur_idx
+ 1) & MAX_TRACK_MASK
;
2118 /* if we've advanced past the wrap when cur_idx is zeroed */
2122 /* if we aren't still on the wrap and we've caught the old track */
2123 if (!(wrap
|| cur_idx
< old_track_ridx
))
2126 /* If we hit a track in between without valid tag info, bail */
2127 if (!tracks
[cur_idx
].taginfo_ready
)
2129 taginfo_ready
= false;
2140 audio_update_trackinfo();
2141 LOGFQUEUE("audio >|= codec Q_CODEC_REQUEST_COMPLETE");
2142 return Q_CODEC_REQUEST_COMPLETE
;
2145 unsigned long audio_prev_elapsed(void)
2147 return prev_track_elapsed
;
2150 static void audio_stop_codec_flush(void)
2152 ci
.stop_codec
= true;
2155 while (audio_codec_loaded
)
2158 /* If the audio codec is not loaded any more, and the audio is still
2159 * playing, it is now and _only_ now safe to call this function from the
2161 if (pcm_is_playing())
2164 pcmbuf_queue_clear();
2166 pcmbuf_pause(paused
);
2169 static void audio_stop_playback(void)
2171 /* If we were playing, save resume information */
2174 struct mp3entry
*id3
= NULL
;
2176 if (!playlist_end
|| !ci
.stop_codec
)
2178 /* Set this early, the outside code yields and may allow the codec
2179 to try to wait for a reply on a buffer wait */
2180 ci
.stop_codec
= true;
2181 id3
= audio_current_track();
2184 /* Save the current playing spot, or NULL if the playlist has ended */
2185 playlist_update_resume_info(id3
);
2187 /* TODO: Create auto bookmark too? */
2189 prev_track_elapsed
= curtrack_id3
.elapsed
;
2193 audio_stop_codec_flush();
2196 filling
= STATE_IDLE
;
2198 /* Mark all entries null. */
2199 audio_clear_track_entries();
2201 /* Close all tracks */
2202 audio_release_tracks();
2204 unregister_buffering_callback(buffering_audio_callback
);
2206 memset(&curtrack_id3
, 0, sizeof(struct mp3entry
));
2209 static void audio_play_start(size_t offset
)
2213 #if INPUT_SRC_CAPS != 0
2214 audio_set_input_source(AUDIO_SRC_PLAYBACK
, SRCF_PLAYBACK
);
2215 audio_set_output_source(AUDIO_SRC_PLAYBACK
);
2218 /* Wait for any previously playing audio to flush - TODO: Not necessary? */
2220 audio_stop_codec_flush();
2222 track_changed
= true;
2223 playlist_end
= false;
2231 sound_set_volume(global_settings
.volume
);
2232 track_widx
= track_ridx
= 0;
2234 /* Clear all track entries. */
2235 for (i
= 0; i
< MAX_TRACK
; i
++) {
2236 clear_track_info(&tracks
[i
]);
2239 last_peek_offset
= -1;
2241 /* Officially playing */
2242 queue_reply(&audio_queue
, 1);
2244 #ifndef HAVE_FLASH_STORAGE
2245 set_filebuf_watermark(buffer_margin
, 0);
2248 audio_fill_file_buffer(true, offset
);
2249 register_buffering_callback(buffering_audio_callback
);
2251 LOGFQUEUE("audio > audio Q_AUDIO_TRACK_CHANGED");
2252 queue_post(&audio_queue
, Q_AUDIO_TRACK_CHANGED
, 0);
2256 /* Invalidates all but currently playing track. */
2257 static void audio_invalidate_tracks(void)
2259 if (audio_have_tracks())
2261 last_peek_offset
= 0;
2262 playlist_end
= false;
2263 track_widx
= track_ridx
;
2265 /* Mark all other entries null (also buffered wrong metadata). */
2266 audio_clear_track_entries();
2268 track_widx
= (track_widx
+ 1) & MAX_TRACK_MASK
;
2270 audio_fill_file_buffer(false, 0);
2274 static void audio_new_playlist(void)
2276 /* Prepare to start a new fill from the beginning of the playlist */
2277 last_peek_offset
= -1;
2278 if (audio_have_tracks())
2281 skipped_during_pause
= true;
2282 playlist_end
= false;
2283 track_widx
= track_ridx
;
2284 audio_clear_track_entries();
2286 track_widx
= (track_widx
+ 1) & MAX_TRACK_MASK
;
2288 /* Mark the current track as invalid to prevent skipping back to it */
2289 CUR_TI
->taginfo_ready
= false;
2292 /* Signal the codec to initiate a track change forward */
2293 new_playlist
= true;
2296 /* Officially playing */
2297 queue_reply(&audio_queue
, 1);
2299 audio_fill_file_buffer(false, 0);
2302 /* Called on manual track skip */
2303 static void audio_initiate_track_change(long direction
)
2305 logf("audio_initiate_track_change(%ld)", direction
);
2307 playlist_end
= false;
2308 ci
.new_track
+= direction
;
2309 wps_offset
-= direction
;
2311 skipped_during_pause
= true;
2314 /* Called on manual dir skip */
2315 static void audio_initiate_dir_change(long direction
)
2317 playlist_end
= false;
2319 ci
.new_track
= direction
;
2321 skipped_during_pause
= true;
2324 /* Called when PCM track change is complete */
2325 static void audio_finalise_track_change(void)
2327 logf("audio_finalise_track_change");
2332 playlist_next(-wps_offset
);
2335 automatic_skip
= false;
2338 auto_dir_skip
= false;
2340 /* Invalidate prevtrack_id3 */
2341 prevtrack_id3
.path
[0] = 0;
2343 if (prev_ti
&& prev_ti
->audio_hid
< 0)
2345 /* No audio left so we clear all the track info. */
2346 clear_track_info(prev_ti
);
2349 if (prev_ti
&& prev_ti
->id3_hid
>= 0)
2351 /* Reset the elapsed time to force the progressbar to be empty if
2352 the user skips back to this track */
2353 bufgetid3(prev_ti
->id3_hid
)->elapsed
= 0;
2356 send_event(PLAYBACK_EVENT_TRACK_CHANGE
, &curtrack_id3
);
2358 track_changed
= true;
2359 playlist_update_resume_info(audio_current_track());
2363 * Layout audio buffer as follows - iram buffer depends on target:
2364 * [|SWAP:iram][|TALK]|MALLOC|FILE|GUARD|PCM|[SWAP:dram[|iram]|]
2366 static void audio_reset_buffer(void)
2368 /* see audio_get_recording_buffer if this is modified */
2369 logf("audio_reset_buffer");
2371 /* If the setup of anything allocated before the file buffer is
2372 changed, do check the adjustments after the buffer_alloc call
2373 as it will likely be affected and need sliding over */
2375 /* Initially set up file buffer as all space available */
2376 malloc_buf
= audiobuf
+ talk_get_bufsize();
2377 /* Align the malloc buf to line size. Especially important to cf
2378 targets that do line reads/writes. */
2379 malloc_buf
= (unsigned char *)(((uintptr_t)malloc_buf
+ 15) & ~15);
2380 filebuf
= malloc_buf
+ MALLOC_BUFSIZE
; /* filebuf line align implied */
2381 filebuflen
= audiobufend
- filebuf
;
2385 /* Subtract whatever the pcm buffer says it used plus the guard buffer */
2386 filebuflen
-= pcmbuf_init(filebuf
+ filebuflen
) + GUARD_BUFSIZE
;
2388 /* Make sure filebuflen is a longword multiple after adjustment - filebuf
2389 will already be line aligned */
2392 buffering_reset(filebuf
, filebuflen
);
2394 /* Clear any references to the file buffer */
2395 buffer_state
= BUFFER_STATE_INITIALIZED
;
2397 #if defined(ROCKBOX_HAS_LOGF) && defined(LOGF_ENABLE)
2398 /* Make sure everything adds up - yes, some info is a bit redundant but
2399 aids viewing and the sumation of certain variables should add up to
2400 the location of others. */
2403 const unsigned char *pcmbuf
= pcmbuf_get_meminfo(&pcmbufsize
);
2404 logf("mabuf: %08X", (unsigned)malloc_buf
);
2405 logf("mabufe: %08X", (unsigned)(malloc_buf
+ MALLOC_BUFSIZE
));
2406 logf("fbuf: %08X", (unsigned)filebuf
);
2407 logf("fbufe: %08X", (unsigned)(filebuf
+ filebuflen
));
2408 logf("gbuf: %08X", (unsigned)(filebuf
+ filebuflen
));
2409 logf("gbufe: %08X", (unsigned)(filebuf
+ filebuflen
+ GUARD_BUFSIZE
));
2410 logf("pcmb: %08X", (unsigned)pcmbuf
);
2411 logf("pcmbe: %08X", (unsigned)(pcmbuf
+ pcmbufsize
));
2416 static void audio_thread(void)
2418 struct queue_event ev
;
2422 audio_thread_ready
= true;
2427 if (!pcmbuf_queue_scan(&ev
))
2428 queue_wait_w_tmo(&audio_queue
, &ev
, HZ
/2);
2432 case Q_AUDIO_FILL_BUFFER
:
2433 LOGFQUEUE("audio < Q_AUDIO_FILL_BUFFER");
2434 audio_fill_file_buffer(false, 0);
2438 LOGFQUEUE("audio < Q_AUDIO_PLAY");
2439 if (playing
&& ev
.data
<= 0)
2440 audio_new_playlist();
2443 audio_stop_playback();
2444 audio_play_start((size_t)ev
.data
);
2449 LOGFQUEUE("audio < Q_AUDIO_STOP");
2451 audio_stop_playback();
2453 queue_clear(&audio_queue
);
2457 LOGFQUEUE("audio < Q_AUDIO_PAUSE");
2458 if (!(bool) ev
.data
&& skipped_during_pause
&& !pcmbuf_is_crossfade_active())
2459 pcmbuf_play_stop(); /* Flush old track on resume after skip */
2460 skipped_during_pause
= false;
2463 pcmbuf_pause((bool)ev
.data
);
2464 paused
= (bool)ev
.data
;
2468 LOGFQUEUE("audio < Q_AUDIO_SKIP");
2469 audio_initiate_track_change((long)ev
.data
);
2472 case Q_AUDIO_PRE_FF_REWIND
:
2473 LOGFQUEUE("audio < Q_AUDIO_PRE_FF_REWIND");
2479 case Q_AUDIO_FF_REWIND
:
2480 LOGFQUEUE("audio < Q_AUDIO_FF_REWIND");
2485 /* An automatic track skip is in progress. Finalize it,
2486 then go back to the previous track */
2487 audio_finalise_track_change();
2490 ci
.seek_time
= (long)ev
.data
+1;
2493 case Q_AUDIO_CHECK_NEW_TRACK
:
2494 LOGFQUEUE("audio < Q_AUDIO_CHECK_NEW_TRACK");
2495 queue_reply(&audio_queue
, audio_check_new_track());
2498 case Q_AUDIO_DIR_SKIP
:
2499 LOGFQUEUE("audio < Q_AUDIO_DIR_SKIP");
2500 playlist_end
= false;
2501 audio_initiate_dir_change(ev
.data
);
2505 LOGFQUEUE("audio < Q_AUDIO_FLUSH");
2506 audio_invalidate_tracks();
2509 case Q_AUDIO_TRACK_CHANGED
:
2510 /* PCM track change done */
2511 LOGFQUEUE("audio < Q_AUDIO_TRACK_CHANGED");
2512 audio_finalise_track_change();
2516 case SYS_USB_CONNECTED
:
2517 LOGFQUEUE("audio < SYS_USB_CONNECTED");
2519 audio_stop_playback();
2520 #ifdef PLAYBACK_VOICE
2523 usb_acknowledge(SYS_USB_CONNECTED_ACK
);
2524 usb_wait_for_disconnect(&audio_queue
);
2526 /* Mark all entries null. */
2527 audio_clear_track_entries();
2529 /* release tracks to make sure all handles are closed */
2530 audio_release_tracks();
2535 LOGFQUEUE_SYS_TIMEOUT("audio < SYS_TIMEOUT");
2536 if (filling
== STATE_FILLING
)
2537 audio_fill_file_buffer(false, 0);
2541 LOGFQUEUE("audio < default");
2547 /* Initialize the audio system - called from init() in main.c.
2548 * Last function because of all the references to internal symbols
2550 void audio_init(void)
2552 struct thread_entry
*audio_thread_p
;
2554 /* Can never do this twice */
2555 if (audio_is_initialized
)
2557 logf("audio: already initialized");
2561 logf("audio: initializing");
2563 /* Initialize queues before giving control elsewhere in case it likes
2564 to send messages. Thread creation will be delayed however so nothing
2565 starts running until ready if something yields such as talk_init. */
2566 queue_init(&audio_queue
, true);
2567 queue_init(&codec_queue
, false);
2568 queue_init(&pcmbuf_queue
, false);
2572 /* Initialize codec api. */
2573 ci
.read_filebuf
= codec_filebuf_callback
;
2574 ci
.pcmbuf_insert
= codec_pcmbuf_insert_callback
;
2575 ci
.get_codec_memory
= codec_get_memory_callback
;
2576 ci
.request_buffer
= codec_request_buffer_callback
;
2577 ci
.advance_buffer
= codec_advance_buffer_callback
;
2578 ci
.advance_buffer_loc
= codec_advance_buffer_loc_callback
;
2579 ci
.request_next_track
= codec_request_next_track_callback
;
2580 ci
.mp3_get_filepos
= codec_mp3_get_filepos_callback
;
2581 ci
.seek_buffer
= codec_seek_buffer_callback
;
2582 ci
.seek_complete
= codec_seek_complete_callback
;
2583 ci
.set_elapsed
= codec_set_elapsed_callback
;
2584 ci
.set_offset
= codec_set_offset_callback
;
2585 ci
.configure
= codec_configure_callback
;
2586 ci
.discard_codec
= codec_discard_codec_callback
;
2587 ci
.dsp
= (struct dsp_config
*)dsp_configure(NULL
, DSP_MYDSP
,
2590 /* initialize the buffer */
2593 /* audio_reset_buffer must to know the size of voice buffer so init
2597 codec_thread_p
= create_thread(
2598 codec_thread
, codec_stack
, sizeof(codec_stack
),
2599 CREATE_THREAD_FROZEN
,
2600 codec_thread_name
IF_PRIO(, PRIORITY_PLAYBACK
)
2603 queue_enable_queue_send(&codec_queue
, &codec_queue_sender_list
,
2606 audio_thread_p
= create_thread(audio_thread
, audio_stack
,
2607 sizeof(audio_stack
), CREATE_THREAD_FROZEN
,
2608 audio_thread_name
IF_PRIO(, PRIORITY_USER_INTERFACE
)
2611 queue_enable_queue_send(&audio_queue
, &audio_queue_sender_list
,
2614 #ifdef PLAYBACK_VOICE
2615 voice_thread_init();
2618 /* Set crossfade setting for next buffer init which should be about... */
2619 pcmbuf_crossfade_enable(global_settings
.crossfade
);
2621 /* initialize the buffering system */
2624 /* ...now! Set up the buffers */
2625 audio_reset_buffer();
2628 for(i
= 0; i
< MAX_TRACK
; i
++)
2630 tracks
[i
].audio_hid
= -1;
2631 tracks
[i
].id3_hid
= -1;
2632 tracks
[i
].codec_hid
= -1;
2633 #ifdef HAVE_ALBUMART
2634 tracks
[i
].aa_hid
= -1;
2638 /* Probably safe to say */
2639 audio_is_initialized
= true;
2641 sound_settings_apply();
2642 #ifndef HAVE_FLASH_STORAGE
2643 audio_set_buffer_margin(global_settings
.buffer_margin
);
2646 /* it's safe to let the threads run now */
2647 #ifdef PLAYBACK_VOICE
2648 voice_thread_resume();
2650 thread_thaw(codec_thread_p
);
2651 thread_thaw(audio_thread_p
);
2655 void audio_wait_for_init(void)
2657 /* audio thread will only set this once after it finished the final
2658 * audio hardware init so this little construct is safe - even
2660 while (!audio_thread_ready
)