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
145 /* As defined in plugins/lib/xxx2wav.h */
147 #define MALLOC_BUFSIZE (512*1024)
148 #define GUARD_BUFSIZE (32*1024)
150 #define MALLOC_BUFSIZE (100*1024)
151 #define GUARD_BUFSIZE (8*1024)
154 /* As defined in plugin.lds */
156 #define CODEC_IRAM_ORIGIN ((unsigned char *)0x4000c000)
157 #define CODEC_IRAM_SIZE ((size_t)0xc000)
158 #elif defined(IAUDIO_X5) || defined(IAUDIO_M5)
159 #define CODEC_IRAM_ORIGIN ((unsigned char *)0x10010000)
160 #define CODEC_IRAM_SIZE ((size_t)0x10000)
162 #define CODEC_IRAM_ORIGIN ((unsigned char *)0x1000c000)
163 #define CODEC_IRAM_SIZE ((size_t)0xc000)
166 bool audio_is_initialized
= false;
167 static bool audio_thread_ready NOCACHEBSS_ATTR
= false;
169 /* Variables are commented with the threads that use them: *
170 * A=audio, C=codec, V=voice. A suffix of - indicates that *
171 * the variable is read but not updated on that thread. */
172 /* TBD: Split out "audio" and "playback" (ie. calling) threads */
174 /* Main state control */
175 static volatile bool audio_codec_loaded NOCACHEBSS_ATTR
= false; /* Codec loaded? (C/A-) */
176 static volatile bool playing NOCACHEBSS_ATTR
= false; /* Is audio playing? (A) */
177 static volatile bool paused NOCACHEBSS_ATTR
= false; /* Is audio paused? (A/C-) */
179 /* Ring buffer where compressed audio and codecs are loaded */
180 static unsigned char *filebuf
= NULL
; /* Start of buffer (A/C-) */
181 static unsigned char *malloc_buf
= NULL
; /* Start of malloc buffer (A/C-) */
182 /* FIXME: make filebuflen static */
183 size_t filebuflen
= 0; /* Size of buffer (A/C-) */
184 /* FIXME: make buf_ridx (C/A-) */
186 /* Possible arrangements of the buffer */
187 #define BUFFER_STATE_TRASHED -1 /* trashed; must be reset */
188 #define BUFFER_STATE_INITIALIZED 0 /* voice+audio OR audio-only */
189 #define BUFFER_STATE_VOICED_ONLY 1 /* voice-only */
190 static int buffer_state
= BUFFER_STATE_TRASHED
; /* Buffer state */
192 /* Used to keep the WPS up-to-date during track transtition */
193 static struct mp3entry prevtrack_id3
;
195 /* Used to provide the codec with a pointer */
196 static struct mp3entry curtrack_id3
;
198 /* Used to make next track info available while playing last track on buffer */
199 static struct mp3entry lasttrack_id3
;
201 /* Track info structure about songs in the file buffer (A/C-) */
203 int audio_hid
; /* The ID for the track's buffer handle */
204 int id3_hid
; /* The ID for the track's metadata handle */
205 int codec_hid
; /* The ID for the track's codec handle */
207 int aa_hid
; /* The ID for the track's album art handle */
210 size_t filesize
; /* File total length */
212 bool taginfo_ready
; /* Is metadata read */
215 static struct track_info tracks
[MAX_TRACK
];
216 static volatile int track_ridx
= 0; /* Track being decoded (A/C-) */
217 static int track_widx
= 0; /* Track being buffered (A) */
219 #define CUR_TI (&tracks[track_ridx]) /* Playing track info pointer (A/C-) */
220 static struct track_info
*prev_ti
= NULL
; /* Pointer to the previously played
223 /* Set by the audio thread when the current track information has updated
224 * and the WPS may need to update its cached information */
225 static bool track_changed
= false;
227 /* Information used only for filling the buffer */
228 /* Playlist steps from playing track to next track to be buffered (A) */
229 static int last_peek_offset
= 0;
231 /* Scrobbler support */
232 static unsigned long prev_track_elapsed
= 0; /* Previous track elapsed time (C/A-)*/
234 /* Track change controls */
235 static bool automatic_skip
= false; /* Who initiated in-progress skip? (C/A-) */
236 static bool playlist_end
= false; /* Has the current playlist ended? (A) */
237 static bool auto_dir_skip
= false; /* Have we changed dirs automatically? */
238 static bool dir_skip
= false; /* Is a directory skip pending? (A) */
239 static bool new_playlist
= false; /* Are we starting a new playlist? (A) */
240 static int wps_offset
= 0; /* Pending track change offset, to keep WPS responsive (A) */
241 static bool skipped_during_pause
= false; /* Do we need to clear the PCM buffer when playback resumes (A) */
243 /* Set to true if the codec thread should send an audio stop request
244 * (typically because the end of the playlist has been reached).
246 static bool codec_requested_stop
= false;
248 struct playback_event
{
249 enum PLAYBACK_EVENT_TYPE type
;
250 void (*callback
)(void *data
);
253 struct playback_event events
[PLAYBACK_MAX_EVENTS
];
255 static size_t buffer_margin
= 0; /* Buffer margin aka anti-skip buffer (A/C-) */
257 /* Multiple threads */
258 /* Set the watermark to trigger buffer fill (A/C) FIXME */
259 static void set_filebuf_watermark(int seconds
, size_t max
);
262 static struct event_queue audio_queue NOCACHEBSS_ATTR
;
263 static struct queue_sender_list audio_queue_sender_list NOCACHEBSS_ATTR
;
264 static long audio_stack
[(DEFAULT_STACK_SIZE
+ 0x1000)/sizeof(long)];
265 static const char audio_thread_name
[] = "audio";
267 static void audio_thread(void);
268 static void audio_initiate_track_change(long direction
);
269 static bool audio_have_tracks(void);
270 static void audio_reset_buffer(void);
273 extern struct codec_api ci
;
274 static struct event_queue codec_queue NOCACHEBSS_ATTR
;
275 static struct queue_sender_list codec_queue_sender_list
;
276 static long codec_stack
[(DEFAULT_STACK_SIZE
+ 0x2000)/sizeof(long)]
278 static const char codec_thread_name
[] = "codec";
279 struct thread_entry
*codec_thread_p
; /* For modifying thread priority later. */
281 /* PCM buffer messaging */
282 static struct event_queue pcmbuf_queue NOCACHEBSS_ATTR
;
284 /* Function to be called by pcm buffer callbacks.
285 * Permissible Context(s): Audio interrupt
287 static void pcmbuf_callback_queue_post(long id
, intptr_t data
)
289 /* No lock since we're already in audio interrupt context */
290 queue_post(&pcmbuf_queue
, id
, data
);
293 /* Scan the pcmbuf queue and return true if a message pulled.
294 * Permissible Context(s): Thread
296 static bool pcmbuf_queue_scan(struct queue_event
*ev
)
298 if (!queue_empty(&pcmbuf_queue
))
300 /* Transfer message to audio queue */
302 /* Pull message - never, ever any blocking call! */
303 queue_wait_w_tmo(&pcmbuf_queue
, ev
, 0);
311 /* Clear the pcmbuf queue of messages
312 * Permissible Context(s): Thread
314 static void pcmbuf_queue_clear(void)
317 queue_clear(&pcmbuf_queue
);
321 /* --- Helper functions --- */
323 static struct mp3entry
*bufgetid3(int handle_id
)
328 struct mp3entry
*id3
;
329 ssize_t ret
= bufgetdata(handle_id
, 0, (void *)&id3
);
331 if (ret
< 0 || ret
!= sizeof(struct mp3entry
))
337 static bool clear_track_info(struct track_info
*track
)
339 /* bufclose returns true if the handle is not found, or if it is closed
340 * successfully, so these checks are safe on non-existant handles */
344 if (track
->codec_hid
>= 0) {
345 if (bufclose(track
->codec_hid
))
346 track
->codec_hid
= -1;
351 if (track
->id3_hid
>= 0) {
352 if (bufclose(track
->id3_hid
))
358 if (track
->audio_hid
>= 0) {
359 if (bufclose(track
->audio_hid
))
360 track
->audio_hid
= -1;
366 if (track
->aa_hid
>= 0) {
367 if (bufclose(track
->aa_hid
))
375 track
->taginfo_ready
= false;
380 /* --- External interfaces --- */
382 /* This sends a stop message and the audio thread will dump all it's
383 subsequenct messages */
384 void audio_hard_stop(void)
387 LOGFQUEUE("audio >| audio Q_AUDIO_STOP: 1");
388 queue_send(&audio_queue
, Q_AUDIO_STOP
, 1);
389 #ifdef PLAYBACK_VOICE
394 bool audio_restore_playback(int type
)
398 case AUDIO_WANT_PLAYBACK
:
399 if (buffer_state
!= BUFFER_STATE_INITIALIZED
)
400 audio_reset_buffer();
402 case AUDIO_WANT_VOICE
:
403 if (buffer_state
== BUFFER_STATE_TRASHED
)
404 audio_reset_buffer();
411 unsigned char *audio_get_buffer(bool talk_buf
, size_t *buffer_size
)
413 unsigned char *buf
, *end
;
415 if (audio_is_initialized
)
419 /* else buffer_state will be BUFFER_STATE_TRASHED at this point */
421 if (buffer_size
== NULL
)
423 /* Special case for talk_init to use since it already knows it's
425 buffer_state
= BUFFER_STATE_TRASHED
;
429 if (talk_buf
|| buffer_state
== BUFFER_STATE_TRASHED
430 || !talk_voice_required())
432 logf("get buffer: talk, audio");
433 /* Ok to use everything from audiobuf to audiobufend - voice is loaded,
434 the talk buffer is not needed because voice isn't being used, or
435 could be BUFFER_STATE_TRASHED already. If state is
436 BUFFER_STATE_VOICED_ONLY, no problem as long as memory isn't written
437 without the caller knowing what's going on. Changing certain settings
438 may move it to a worse condition but the memory in use by something
439 else will remain undisturbed.
441 if (buffer_state
!= BUFFER_STATE_TRASHED
)
444 buffer_state
= BUFFER_STATE_TRASHED
;
452 /* Safe to just return this if already BUFFER_STATE_VOICED_ONLY or
453 still BUFFER_STATE_INITIALIZED */
454 /* Skip talk buffer and move pcm buffer to end to maximize available
455 contiguous memory - no audio running means voice will not need the
457 logf("get buffer: audio");
458 buf
= audiobuf
+ talk_get_bufsize();
459 end
= audiobufend
- pcmbuf_init(audiobufend
);
460 buffer_state
= BUFFER_STATE_VOICED_ONLY
;
463 *buffer_size
= end
- buf
;
468 #ifdef HAVE_RECORDING
469 unsigned char *audio_get_recording_buffer(size_t *buffer_size
)
471 /* Stop audio, voice and obtain all available buffer space */
475 unsigned char *end
= audiobufend
;
476 buffer_state
= BUFFER_STATE_TRASHED
;
477 *buffer_size
= end
- audiobuf
;
479 return (unsigned char *)audiobuf
;
482 bool audio_load_encoder(int afmt
)
485 const char *enc_fn
= get_codec_filename(afmt
| CODEC_TYPE_ENCODER
);
489 audio_remove_encoder();
490 ci
.enc_codec_loaded
= 0; /* clear any previous error condition */
492 LOGFQUEUE("codec > Q_ENCODER_LOAD_DISK");
493 queue_post(&codec_queue
, Q_ENCODER_LOAD_DISK
, (intptr_t)enc_fn
);
495 while (ci
.enc_codec_loaded
== 0)
498 logf("codec loaded: %d", ci
.enc_codec_loaded
);
500 return ci
.enc_codec_loaded
> 0;
505 } /* audio_load_encoder */
507 void audio_remove_encoder(void)
510 /* force encoder codec unload (if currently loaded) */
511 if (ci
.enc_codec_loaded
<= 0)
514 ci
.stop_encoder
= true;
515 while (ci
.enc_codec_loaded
> 0)
518 } /* audio_remove_encoder */
520 #endif /* HAVE_RECORDING */
523 int audio_current_aa_hid(void)
526 int offset
= ci
.new_track
+ wps_offset
;
528 cur_idx
= track_ridx
+ offset
;
529 cur_idx
&= MAX_TRACK_MASK
;
531 return tracks
[cur_idx
].aa_hid
;
535 struct mp3entry
* audio_current_track(void)
537 const char *filename
;
539 static struct mp3entry temp_id3
;
541 int offset
= ci
.new_track
+ wps_offset
;
543 cur_idx
= (track_ridx
+ offset
) & MAX_TRACK_MASK
;
545 if (cur_idx
== track_ridx
&& *curtrack_id3
.path
)
548 return &curtrack_id3
;
550 else if (offset
== -1 && *prevtrack_id3
.path
)
552 /* We're in a track transition. The codec has moved on to the nex track,
553 but the audio being played is still the same (now previous) track.
554 prevtrack_id3.elapsed is being updated in an ISR by
555 codec_pcmbuf_position_callback */
556 return &prevtrack_id3
;
558 else if (tracks
[cur_idx
].id3_hid
>= 0)
560 /* Get the ID3 metadata from the main buffer */
561 return bufgetid3(tracks
[cur_idx
].id3_hid
);
564 /* We didn't find the ID3 metadata, so we fill temp_id3 with the little info
565 we have and return that. */
567 memset(&temp_id3
, 0, sizeof(struct mp3entry
));
569 filename
= playlist_peek(0);
571 filename
= "No file!";
573 #if defined(HAVE_TC_RAMCACHE) && defined(HAVE_DIRCACHE)
574 if (tagcache_fill_tags(&temp_id3
, filename
))
578 p
= strrchr(filename
, '/');
584 strncpy(temp_id3
.path
, p
, sizeof(temp_id3
.path
)-1);
585 temp_id3
.title
= &temp_id3
.path
[0];
590 struct mp3entry
* audio_next_track(void)
593 int offset
= ci
.new_track
+ wps_offset
;
595 if (!audio_have_tracks())
598 if (wps_offset
== -1 && *prevtrack_id3
.path
)
600 /* We're in a track transition. The next track for the WPS is the one
601 currently being decoded. */
602 return &curtrack_id3
;
605 next_idx
= (track_ridx
+ offset
+ 1) & MAX_TRACK_MASK
;
607 if (next_idx
== track_widx
)
609 /* The next track hasn't been buffered yet, so we return the static
610 version of its metadata. */
611 return &lasttrack_id3
;
614 if (tracks
[next_idx
].id3_hid
< 0)
617 return bufgetid3(tracks
[next_idx
].id3_hid
);
620 bool audio_has_changed_track(void)
624 track_changed
= false;
631 void audio_play(long offset
)
635 #ifdef PLAYBACK_VOICE
636 /* Truncate any existing voice output so we don't have spelling
637 * etc. over the first part of the played track */
642 LOGFQUEUE("audio >| audio Q_AUDIO_PLAY: %ld", offset
);
643 /* Don't return until playback has actually started */
644 queue_send(&audio_queue
, Q_AUDIO_PLAY
, offset
);
647 void audio_stop(void)
650 LOGFQUEUE("audio >| audio Q_AUDIO_STOP");
651 /* Don't return until playback has actually stopped */
652 queue_send(&audio_queue
, Q_AUDIO_STOP
, 0);
655 void audio_pause(void)
657 LOGFQUEUE("audio >| audio Q_AUDIO_PAUSE");
658 /* Don't return until playback has actually paused */
659 queue_send(&audio_queue
, Q_AUDIO_PAUSE
, true);
662 void audio_resume(void)
664 LOGFQUEUE("audio >| audio Q_AUDIO_PAUSE resume");
665 /* Don't return until playback has actually resumed */
666 queue_send(&audio_queue
, Q_AUDIO_PAUSE
, false);
669 static void audio_skip(int direction
)
671 if (playlist_check(ci
.new_track
+ wps_offset
+ direction
))
673 if (global_settings
.beep
)
674 pcmbuf_beep(5000, 100, 2500*global_settings
.beep
);
676 LOGFQUEUE("audio > audio Q_AUDIO_SKIP %d", direction
);
677 queue_post(&audio_queue
, Q_AUDIO_SKIP
, direction
);
678 /* Update wps while our message travels inside deep playback queues. */
679 wps_offset
+= direction
;
680 /* Immediately update the playlist index */
681 playlist_next(direction
);
682 track_changed
= true;
686 /* No more tracks. */
687 if (global_settings
.beep
)
688 pcmbuf_beep(1000, 100, 1000*global_settings
.beep
);
692 void audio_next(void)
697 void audio_prev(void)
702 void audio_next_dir(void)
704 LOGFQUEUE("audio > audio Q_AUDIO_DIR_SKIP 1");
705 queue_post(&audio_queue
, Q_AUDIO_DIR_SKIP
, 1);
708 void audio_prev_dir(void)
710 LOGFQUEUE("audio > audio Q_AUDIO_DIR_SKIP -1");
711 queue_post(&audio_queue
, Q_AUDIO_DIR_SKIP
, -1);
714 void audio_pre_ff_rewind(void)
716 LOGFQUEUE("audio > audio Q_AUDIO_PRE_FF_REWIND");
717 queue_post(&audio_queue
, Q_AUDIO_PRE_FF_REWIND
, 0);
720 void audio_ff_rewind(long newpos
)
722 LOGFQUEUE("audio > audio Q_AUDIO_FF_REWIND");
723 queue_post(&audio_queue
, Q_AUDIO_FF_REWIND
, newpos
);
726 void audio_flush_and_reload_tracks(void)
728 LOGFQUEUE("audio > audio Q_AUDIO_FLUSH");
729 queue_post(&audio_queue
, Q_AUDIO_FLUSH
, 0);
732 void audio_error_clear(void)
734 #ifdef AUDIO_HAVE_RECORDING
735 pcm_rec_error_clear();
739 int audio_status(void)
744 ret
|= AUDIO_STATUS_PLAY
;
747 ret
|= AUDIO_STATUS_PAUSE
;
749 #ifdef HAVE_RECORDING
750 /* Do this here for constitency with mpeg.c version */
751 ret
|= pcm_rec_status();
757 int audio_get_file_pos(void)
762 #ifndef HAVE_FLASH_STORAGE
763 void audio_set_buffer_margin(int setting
)
765 static const int lookup
[] = {5, 15, 30, 60, 120, 180, 300, 600};
766 buffer_margin
= lookup
[setting
];
767 logf("buffer margin: %ld", (long)buffer_margin
);
768 set_filebuf_watermark(buffer_margin
, 0);
772 /* Take nescessary steps to enable or disable the crossfade setting */
773 void audio_set_crossfade(int enable
)
779 /* Tell it the next setting to use */
780 pcmbuf_crossfade_enable(enable
);
782 /* Return if size hasn't changed or this is too early to determine
783 which in the second case there's no way we could be playing
785 if (pcmbuf_is_same_size())
787 /* This function is a copout and just syncs some variables -
788 to be removed at a later date */
789 pcmbuf_crossfade_enable_finished();
794 was_playing
= playing
;
796 /* Playback has to be stopped before changing the buffer size */
799 /* Store the track resume position */
800 offset
= curtrack_id3
.offset
;
801 gui_syncsplash(0, str(LANG_RESTARTING_PLAYBACK
));
804 /* Blast it - audio buffer will have to be setup again next time
806 audio_get_buffer(true, &size
);
808 /* Restart playback if audio was running previously */
813 /* --- Routines called from multiple threads --- */
815 static void set_filebuf_watermark(int seconds
, size_t max
)
820 return; /* Audio buffers not yet set up */
822 bytes
= seconds
?MAX(curtrack_id3
.bitrate
* seconds
* (1000/8), max
):max
;
823 bytes
= MIN(bytes
, filebuflen
/ 2);
824 buf_set_watermark(bytes
);
827 const char * get_codec_filename(int cod_spec
)
831 #ifdef HAVE_RECORDING
832 /* Can choose decoder or encoder if one available */
833 int type
= cod_spec
& CODEC_TYPE_MASK
;
834 int afmt
= cod_spec
& CODEC_AFMT_MASK
;
836 if ((unsigned)afmt
>= AFMT_NUM_CODECS
)
837 type
= AFMT_UNKNOWN
| (type
& CODEC_TYPE_MASK
);
839 fname
= (type
== CODEC_TYPE_ENCODER
) ?
840 audio_formats
[afmt
].codec_enc_root_fn
:
841 audio_formats
[afmt
].codec_root_fn
;
844 (type
== CODEC_TYPE_ENCODER
) ? "Encoder" : "Decoder",
845 afmt
, fname
? fname
: "<unknown>");
846 #else /* !HAVE_RECORDING */
848 if ((unsigned)cod_spec
>= AFMT_NUM_CODECS
)
849 cod_spec
= AFMT_UNKNOWN
;
850 fname
= audio_formats
[cod_spec
].codec_root_fn
;
851 logf("Codec: %d - %s", cod_spec
, fname
? fname
: "<unknown>");
852 #endif /* HAVE_RECORDING */
855 } /* get_codec_filename */
857 /* --- Codec thread --- */
858 static bool codec_pcmbuf_insert_callback(
859 const void *ch1
, const void *ch2
, int count
)
861 const char *src
[2] = { ch1
, ch2
};
865 int out_count
= dsp_output_count(ci
.dsp
, count
);
869 /* Prevent audio from a previous track from playing */
870 if (ci
.new_track
|| ci
.stop_codec
)
873 while ((dest
= pcmbuf_request_buffer(&out_count
)) == NULL
)
877 if (ci
.seek_time
|| ci
.new_track
|| ci
.stop_codec
)
881 /* Get the real input_size for output_size bytes, guarding
882 * against resampling buffer overflows. */
883 inp_count
= dsp_input_count(ci
.dsp
, out_count
);
888 /* Input size has grown, no error, just don't write more than length */
889 if (inp_count
> count
)
892 out_count
= dsp_process(ci
.dsp
, dest
, src
, inp_count
);
897 pcmbuf_write_complete(out_count
);
903 } /* codec_pcmbuf_insert_callback */
905 static void* codec_get_memory_callback(size_t *size
)
907 *size
= MALLOC_BUFSIZE
;
911 /* Between the codec and PCM track change, we need to keep updating the
912 "elapsed" value of the previous (to the codec, but current to the
913 user/PCM/WPS) track, so that the progressbar reaches the end.
914 During that transition, the WPS will display prevtrack_id3. */
915 static void codec_pcmbuf_position_callback(size_t size
) ICODE_ATTR
;
916 static void codec_pcmbuf_position_callback(size_t size
)
918 /* This is called from an ISR, so be quick */
919 unsigned int time
= size
* 1000 / 4 / NATIVE_FREQUENCY
+
920 prevtrack_id3
.elapsed
;
922 if (time
>= prevtrack_id3
.length
)
924 pcmbuf_set_position_callback(NULL
);
925 prevtrack_id3
.elapsed
= prevtrack_id3
.length
;
928 prevtrack_id3
.elapsed
= time
;
931 static void codec_set_elapsed_callback(unsigned int value
)
933 unsigned int latency
;
937 #ifdef AB_REPEAT_ENABLE
938 ab_position_report(value
);
941 latency
= pcmbuf_get_latency();
943 curtrack_id3
.elapsed
= 0;
944 else if (value
- latency
> curtrack_id3
.elapsed
||
945 value
- latency
< curtrack_id3
.elapsed
- 2)
947 curtrack_id3
.elapsed
= value
- latency
;
951 static void codec_set_offset_callback(size_t value
)
953 unsigned int latency
;
958 latency
= pcmbuf_get_latency() * curtrack_id3
.bitrate
/ 8;
960 curtrack_id3
.offset
= 0;
962 curtrack_id3
.offset
= value
- latency
;
965 static void codec_advance_buffer_counters(size_t amount
)
967 bufadvance(CUR_TI
->audio_hid
, amount
);
971 /* copy up-to size bytes into ptr and return the actual size copied */
972 static size_t codec_filebuf_callback(void *ptr
, size_t size
)
976 if (ci
.stop_codec
|| !playing
)
979 copy_n
= bufread(CUR_TI
->audio_hid
, size
, ptr
);
981 /* Nothing requested OR nothing left */
985 /* Update read and other position pointers */
986 codec_advance_buffer_counters(copy_n
);
988 /* Return the actual amount of data copied to the buffer */
990 } /* codec_filebuf_callback */
992 static void* codec_request_buffer_callback(size_t *realsize
, size_t reqsize
)
994 size_t copy_n
= reqsize
;
1004 ret
= bufgetdata(CUR_TI
->audio_hid
, reqsize
, &ptr
);
1006 copy_n
= MIN((size_t)ret
, reqsize
);
1017 } /* codec_request_buffer_callback */
1019 static int get_codec_base_type(int type
)
1031 static void codec_advance_buffer_callback(size_t amount
)
1033 codec_advance_buffer_counters(amount
);
1034 codec_set_offset_callback(ci
.curpos
);
1037 static void codec_advance_buffer_loc_callback(void *ptr
)
1039 size_t amount
= buf_get_offset(CUR_TI
->audio_hid
, ptr
);
1040 codec_advance_buffer_callback(amount
);
1043 /* Copied from mpeg.c. Should be moved somewhere else. */
1044 static int codec_get_file_pos(void)
1047 struct mp3entry
*id3
= audio_current_track();
1053 /* Use the TOC to find the new position */
1054 unsigned int percent
, remainder
;
1055 int curtoc
, nexttoc
, plen
;
1057 percent
= (id3
->elapsed
*100)/id3
->length
;
1061 curtoc
= id3
->toc
[percent
];
1064 nexttoc
= id3
->toc
[percent
+1];
1068 pos
= (id3
->filesize
/256)*curtoc
;
1070 /* Use the remainder to get a more accurate position */
1071 remainder
= (id3
->elapsed
*100)%id3
->length
;
1072 remainder
= (remainder
*100)/id3
->length
;
1073 plen
= (nexttoc
- curtoc
)*(id3
->filesize
/256);
1074 pos
+= (plen
/100)*remainder
;
1078 /* No TOC exists, estimate the new position */
1079 pos
= (id3
->filesize
/ (id3
->length
/ 1000)) *
1080 (id3
->elapsed
/ 1000);
1083 else if (id3
->bitrate
)
1084 pos
= id3
->elapsed
* (id3
->bitrate
/ 8);
1088 pos
+= id3
->first_frame_offset
;
1090 /* Don't seek right to the end of the file so that we can
1091 transition properly to the next song */
1092 if (pos
>= (int)(id3
->filesize
- id3
->id3v1len
))
1093 pos
= id3
->filesize
- id3
->id3v1len
- 1;
1098 static off_t
codec_mp3_get_filepos_callback(int newtime
)
1102 curtrack_id3
.elapsed
= newtime
;
1103 newpos
= codec_get_file_pos();
1108 static void codec_seek_complete_callback(void)
1110 logf("seek_complete");
1111 if (pcm_is_paused())
1113 /* If this is not a seamless seek, clear the buffer */
1115 dsp_configure(ci
.dsp
, DSP_FLUSH
, 0);
1117 /* If playback was not 'deliberately' paused, unpause now */
1119 pcmbuf_pause(false);
1124 static bool codec_seek_buffer_callback(size_t newpos
)
1126 logf("codec_seek_buffer_callback");
1128 int ret
= bufseek(CUR_TI
->audio_hid
, newpos
);
1138 static void codec_configure_callback(int setting
, intptr_t value
)
1141 case CODEC_SET_FILEBUF_WATERMARK
:
1142 set_filebuf_watermark(buffer_margin
, value
);
1146 if (!dsp_configure(ci
.dsp
, setting
, value
))
1147 { logf("Illegal key:%d", setting
); }
1151 static void codec_track_changed(void)
1153 LOGFQUEUE("codec > audio Q_AUDIO_TRACK_CHANGED");
1154 queue_post(&audio_queue
, Q_AUDIO_TRACK_CHANGED
, 0);
1157 static void codec_pcmbuf_track_changed_callback(void)
1159 pcmbuf_set_position_callback(NULL
);
1160 pcmbuf_callback_queue_post(Q_AUDIO_TRACK_CHANGED
, 0);
1163 static void codec_discard_codec_callback(void)
1165 if (CUR_TI
->codec_hid
>= 0)
1167 bufclose(CUR_TI
->codec_hid
);
1168 CUR_TI
->codec_hid
= -1;
1172 static inline void codec_gapless_track_change(void)
1174 /* callback keeps the progress bar moving while the pcmbuf empties */
1175 pcmbuf_set_position_callback(codec_pcmbuf_position_callback
);
1176 /* set the pcmbuf callback for when the track really changes */
1177 pcmbuf_set_event_handler(codec_pcmbuf_track_changed_callback
);
1180 static inline void codec_crossfade_track_change(void)
1182 /* Initiate automatic crossfade mode */
1183 pcmbuf_crossfade_init(false);
1184 /* Notify the wps that the track change starts now */
1185 codec_track_changed();
1188 static void codec_track_skip_done(bool was_manual
)
1190 /* Manual track change (always crossfade or flush audio). */
1193 pcmbuf_crossfade_init(true);
1194 LOGFQUEUE("codec > audio Q_AUDIO_TRACK_CHANGED");
1195 queue_post(&audio_queue
, Q_AUDIO_TRACK_CHANGED
, 0);
1197 /* Automatic track change w/crossfade, if not in "Track Skip Only" mode. */
1198 else if (pcmbuf_is_crossfade_enabled() && !pcmbuf_is_crossfade_active()
1199 && global_settings
.crossfade
!= CROSSFADE_ENABLE_TRACKSKIP
)
1201 if (global_settings
.crossfade
== CROSSFADE_ENABLE_SHUFFLE_AND_TRACKSKIP
)
1203 if (global_settings
.playlist_shuffle
)
1204 /* shuffle mode is on, so crossfade: */
1205 codec_crossfade_track_change();
1207 /* shuffle mode is off, so do a gapless track change */
1208 codec_gapless_track_change();
1211 /* normal crossfade: */
1212 codec_crossfade_track_change();
1215 /* normal gapless playback. */
1216 codec_gapless_track_change();
1219 static bool codec_load_next_track(void)
1221 intptr_t result
= Q_CODEC_REQUEST_FAILED
;
1223 prev_track_elapsed
= curtrack_id3
.elapsed
;
1225 #ifdef AB_REPEAT_ENABLE
1226 ab_end_of_track_report();
1229 logf("Request new track");
1231 if (ci
.new_track
== 0)
1234 automatic_skip
= true;
1239 trigger_cpu_boost();
1240 LOGFQUEUE("codec >| audio Q_AUDIO_CHECK_NEW_TRACK");
1241 result
= queue_send(&audio_queue
, Q_AUDIO_CHECK_NEW_TRACK
, 0);
1246 case Q_CODEC_REQUEST_COMPLETE
:
1247 LOGFQUEUE("codec |< Q_CODEC_REQUEST_COMPLETE");
1248 codec_track_skip_done(!automatic_skip
);
1251 case Q_CODEC_REQUEST_FAILED
:
1252 LOGFQUEUE("codec |< Q_CODEC_REQUEST_FAILED");
1254 ci
.stop_codec
= true;
1255 codec_requested_stop
= true;
1259 LOGFQUEUE("codec |< default");
1260 ci
.stop_codec
= true;
1261 codec_requested_stop
= true;
1266 static bool codec_request_next_track_callback(void)
1270 if (ci
.stop_codec
|| !playing
)
1273 prev_codectype
= get_codec_base_type(curtrack_id3
.codectype
);
1275 if (!codec_load_next_track())
1278 /* Check if the next codec is the same file. */
1279 if (prev_codectype
== get_codec_base_type(curtrack_id3
.codectype
))
1281 logf("New track loaded");
1282 codec_discard_codec_callback();
1287 logf("New codec:%d/%d", curtrack_id3
.codectype
, prev_codectype
);
1292 static void codec_thread(void)
1294 struct queue_event ev
;
1300 queue_wait(&codec_queue
, &ev
);
1301 codec_requested_stop
= false;
1304 case Q_CODEC_LOAD_DISK
:
1305 LOGFQUEUE("codec < Q_CODEC_LOAD_DISK");
1306 queue_reply(&codec_queue
, 1);
1307 audio_codec_loaded
= true;
1308 ci
.stop_codec
= false;
1309 status
= codec_load_file((const char *)ev
.data
, &ci
);
1313 LOGFQUEUE("codec < Q_CODEC_LOAD");
1314 if (CUR_TI
->codec_hid
< 0) {
1315 logf("Codec slot is empty!");
1316 /* Wait for the pcm buffer to go empty */
1317 while (pcm_is_playing())
1319 /* This must be set to prevent an infinite loop */
1320 ci
.stop_codec
= true;
1321 LOGFQUEUE("codec > codec Q_AUDIO_PLAY");
1322 queue_post(&codec_queue
, Q_AUDIO_PLAY
, 0);
1326 audio_codec_loaded
= true;
1327 ci
.stop_codec
= false;
1328 status
= codec_load_buf(CUR_TI
->codec_hid
, &ci
);
1331 #ifdef AUDIO_HAVE_RECORDING
1332 case Q_ENCODER_LOAD_DISK
:
1333 LOGFQUEUE("codec < Q_ENCODER_LOAD_DISK");
1334 audio_codec_loaded
= false; /* Not audio codec! */
1335 logf("loading encoder");
1336 ci
.stop_encoder
= false;
1337 status
= codec_load_file((const char *)ev
.data
, &ci
);
1338 logf("encoder stopped");
1340 #endif /* AUDIO_HAVE_RECORDING */
1343 LOGFQUEUE("codec < default");
1346 if (audio_codec_loaded
)
1355 audio_codec_loaded
= false;
1359 case Q_CODEC_LOAD_DISK
:
1361 LOGFQUEUE("codec < Q_CODEC_LOAD");
1364 if (ci
.new_track
|| status
!= CODEC_OK
)
1368 logf("Codec failure");
1369 gui_syncsplash(HZ
*2, "Codec failure");
1372 if (!codec_load_next_track())
1374 LOGFQUEUE("codec > audio Q_AUDIO_STOP");
1375 /* End of playlist */
1376 queue_post(&audio_queue
, Q_AUDIO_STOP
, 0);
1382 logf("Codec finished");
1385 /* Wait for the audio to stop playing before
1386 * triggering the WPS exit */
1387 while(pcm_is_playing())
1389 curtrack_id3
.elapsed
=
1390 curtrack_id3
.length
- pcmbuf_get_latency();
1394 if (codec_requested_stop
)
1396 LOGFQUEUE("codec > audio Q_AUDIO_STOP");
1397 queue_post(&audio_queue
, Q_AUDIO_STOP
, 0);
1403 if (CUR_TI
->codec_hid
>= 0)
1405 LOGFQUEUE("codec > codec Q_CODEC_LOAD");
1406 queue_post(&codec_queue
, Q_CODEC_LOAD
, 0);
1410 const char *codec_fn
=
1411 get_codec_filename(curtrack_id3
.codectype
);
1414 LOGFQUEUE("codec > codec Q_CODEC_LOAD_DISK");
1415 queue_post(&codec_queue
, Q_CODEC_LOAD_DISK
,
1416 (intptr_t)codec_fn
);
1422 #ifdef AUDIO_HAVE_RECORDING
1423 case Q_ENCODER_LOAD_DISK
:
1424 LOGFQUEUE("codec < Q_ENCODER_LOAD_DISK");
1426 if (status
== CODEC_OK
)
1429 logf("Encoder failure");
1430 gui_syncsplash(HZ
*2, "Encoder failure");
1432 if (ci
.enc_codec_loaded
< 0)
1435 logf("Encoder failed to load");
1436 ci
.enc_codec_loaded
= -1;
1438 #endif /* AUDIO_HAVE_RECORDING */
1441 LOGFQUEUE("codec < default");
1448 /* --- Audio thread --- */
1450 void playback_add_event(enum PLAYBACK_EVENT_TYPE type
, void (*handler
))
1454 /* Try to find a free slot. */
1455 for (i
= 0; i
< PLAYBACK_MAX_EVENTS
; i
++)
1457 if (events
[i
].callback
== NULL
)
1459 events
[i
].type
= type
;
1460 events
[i
].callback
= handler
;
1465 panicf("playback event line full");
1468 void playback_remove_event(enum PLAYBACK_EVENT_TYPE type
, void (*handler
))
1472 for (i
= 0; i
< PLAYBACK_MAX_EVENTS
; i
++)
1474 if (events
[i
].type
== type
&& events
[i
].callback
== handler
)
1476 events
[i
].callback
= NULL
;
1481 panicf("playback event not found");
1484 static void send_event(enum PLAYBACK_EVENT_TYPE type
, void *data
)
1488 for (i
= 0; i
< PLAYBACK_MAX_EVENTS
; i
++)
1490 if (events
[i
].type
== type
&& events
[i
].callback
!= NULL
)
1491 events
[i
].callback(data
);
1495 static bool audio_have_tracks(void)
1497 return (audio_track_count() != 0);
1500 static int audio_free_track_count(void)
1502 /* Used tracks + free tracks adds up to MAX_TRACK - 1 */
1503 return MAX_TRACK
- 1 - audio_track_count();
1506 int audio_track_count(void)
1508 /* Calculate difference from track_ridx to track_widx
1509 * taking into account a possible wrap-around. */
1510 return (MAX_TRACK
+ track_widx
- track_ridx
) & MAX_TRACK_MASK
;
1513 long audio_filebufused(void)
1515 return (long) buf_used();
1518 /* Update track info after successful a codec track change */
1519 static void audio_update_trackinfo(void)
1521 /* Load the curent track's metadata into curtrack_id3 */
1522 CUR_TI
->taginfo_ready
= (CUR_TI
->id3_hid
>= 0);
1523 if (CUR_TI
->id3_hid
>= 0)
1524 copy_mp3entry(&curtrack_id3
, bufgetid3(CUR_TI
->id3_hid
));
1526 int next_idx
= (track_ridx
+ 1) & MAX_TRACK_MASK
;
1527 tracks
[next_idx
].taginfo_ready
= (tracks
[next_idx
].id3_hid
>= 0);
1529 /* Reset current position */
1530 curtrack_id3
.elapsed
= 0;
1531 curtrack_id3
.offset
= 0;
1533 /* Update the codec API */
1534 ci
.filesize
= CUR_TI
->filesize
;
1535 ci
.id3
= &curtrack_id3
;
1537 ci
.taginfo_ready
= &CUR_TI
->taginfo_ready
;
1540 static void buffering_audio_callback(enum callback_event ev
, int value
)
1543 logf("buffering_audio_callback");
1547 case EVENT_BUFFER_LOW
:
1548 LOGFQUEUE("buffering > audio Q_AUDIO_FILL_BUFFER");
1549 queue_remove_from_head(&audio_queue
, Q_AUDIO_FILL_BUFFER
);
1550 queue_post(&audio_queue
, Q_AUDIO_FILL_BUFFER
, 0);
1553 case EVENT_HANDLE_REBUFFER
:
1554 LOGFQUEUE("audio >| audio Q_AUDIO_FLUSH");
1555 queue_send(&audio_queue
, Q_AUDIO_FLUSH
, 0);
1558 case EVENT_HANDLE_FINISHED
:
1559 logf("handle %d finished buffering", value
);
1568 /* Clear tracks between write and read, non inclusive */
1569 static void audio_clear_track_entries(void)
1571 int cur_idx
= track_widx
;
1573 logf("Clearing tracks:%d/%d", track_ridx
, track_widx
);
1575 /* Loop over all tracks from write-to-read */
1578 cur_idx
= (cur_idx
+ 1) & MAX_TRACK_MASK
;
1580 if (cur_idx
== track_ridx
)
1583 clear_track_info(&tracks
[cur_idx
]);
1587 /* Clear all tracks */
1588 static bool audio_release_tracks(void)
1592 logf("releasing all tracks");
1594 for(i
= 0; i
< MAX_TRACK
; i
++)
1596 cur_idx
= (track_ridx
+ i
) & MAX_TRACK_MASK
;
1597 if (!clear_track_info(&tracks
[cur_idx
]))
1604 static bool audio_loadcodec(bool start_play
)
1607 char codec_path
[MAX_PATH
]; /* Full path to codec */
1609 if (tracks
[track_widx
].id3_hid
< 0) {
1613 const char * codec_fn
=
1614 get_codec_filename(bufgetid3(tracks
[track_widx
].id3_hid
)->codectype
);
1615 if (codec_fn
== NULL
)
1618 tracks
[track_widx
].codec_hid
= -1;
1622 /* Load the codec directly from disk and save some memory. */
1623 track_ridx
= track_widx
;
1624 ci
.filesize
= CUR_TI
->filesize
;
1625 ci
.id3
= &curtrack_id3
;
1626 ci
.taginfo_ready
= &CUR_TI
->taginfo_ready
;
1628 LOGFQUEUE("codec > codec Q_CODEC_LOAD_DISK");
1629 queue_post(&codec_queue
, Q_CODEC_LOAD_DISK
, (intptr_t)codec_fn
);
1634 /* If we already have another track than this one buffered */
1635 if (track_widx
!= track_ridx
)
1637 prev_track
= (track_widx
- 1) & MAX_TRACK_MASK
;
1639 /* If the previous codec is the same as this one, there is no need
1640 * to put another copy of it on the file buffer */
1641 if (get_codec_base_type(
1642 bufgetid3(tracks
[track_widx
].id3_hid
)->codectype
) ==
1643 get_codec_base_type(
1644 bufgetid3(tracks
[prev_track
].id3_hid
)->codectype
)
1645 && audio_codec_loaded
)
1647 logf("Reusing prev. codec");
1653 codec_get_full_path(codec_path
, codec_fn
);
1655 tracks
[track_widx
].codec_hid
= bufopen(codec_path
, 0, TYPE_CODEC
);
1656 if (tracks
[track_widx
].codec_hid
< 0)
1659 logf("Loaded codec");
1664 /* TODO: Copied from mpeg.c. Should be moved somewhere else. */
1665 static void audio_set_elapsed(struct mp3entry
* id3
)
1667 unsigned long offset
= id3
->offset
> id3
->first_frame_offset
?
1668 id3
->offset
- id3
->first_frame_offset
: 0;
1671 if ( id3
->has_toc
) {
1672 /* calculate elapsed time using TOC */
1674 unsigned int remainder
, plen
, relpos
, nextpos
;
1676 /* find wich percent we're at */
1677 for (i
=0; i
<100; i
++ )
1678 if ( offset
< id3
->toc
[i
] * (id3
->filesize
/ 256) )
1685 relpos
= id3
->toc
[i
];
1688 nextpos
= id3
->toc
[i
+1];
1692 remainder
= offset
- (relpos
* (id3
->filesize
/ 256));
1694 /* set time for this percent (divide before multiply to prevent
1695 overflow on long files. loss of precision is negligible on
1697 id3
->elapsed
= i
* (id3
->length
/ 100);
1699 /* calculate remainder time */
1700 plen
= (nextpos
- relpos
) * (id3
->filesize
/ 256);
1701 id3
->elapsed
+= (((remainder
* 100) / plen
) *
1702 (id3
->length
/ 10000));
1705 /* no TOC exists. set a rough estimate using average bitrate */
1706 int tpk
= id3
->length
/
1707 ((id3
->filesize
- id3
->first_frame_offset
- id3
->id3v1len
) /
1709 id3
->elapsed
= offset
/ 1024 * tpk
;
1714 /* constant bitrate, use exact calculation */
1715 if (id3
->bitrate
!= 0)
1716 id3
->elapsed
= offset
/ (id3
->bitrate
/ 8);
1720 /* Load one track by making the appropriate bufopen calls. Return true if
1721 everything required was loaded correctly, false if not. */
1722 static bool audio_load_track(int offset
, bool start_play
)
1727 int file_offset
= 0;
1728 struct mp3entry id3
;
1730 /* Stop buffer filling if there is no free track entries.
1731 Don't fill up the last track entry (we wan't to store next track
1733 if (!audio_free_track_count())
1735 logf("No free tracks");
1740 tracks
[track_widx
].taginfo_ready
= false;
1743 logf("Buffering track:%d/%d", track_widx
, track_ridx
);
1744 /* Get track name from current playlist read position. */
1745 while ((trackname
= playlist_peek(last_peek_offset
)) != NULL
)
1747 /* Handle broken playlists. */
1748 fd
= open(trackname
, O_RDONLY
);
1751 logf("Open failed");
1752 /* Skip invalid entry from playlist. */
1753 playlist_skip_entry(NULL
, last_peek_offset
);
1761 logf("End-of-playlist");
1762 playlist_end
= true;
1763 memset(&lasttrack_id3
, 0, sizeof(struct mp3entry
));
1767 tracks
[track_widx
].filesize
= filesize(fd
);
1769 if ((unsigned)offset
> tracks
[track_widx
].filesize
)
1772 /* Set default values */
1775 buf_set_watermark(AUDIO_DEFAULT_WATERMARK
);
1776 dsp_configure(ci
.dsp
, DSP_RESET
, 0);
1777 track_changed
= true;
1778 playlist_update_resume_info(audio_current_track());
1781 /* Get track metadata if we don't already have it. */
1782 if (tracks
[track_widx
].id3_hid
< 0)
1784 if (get_metadata(&id3
, fd
, trackname
))
1786 send_event(PLAYBACK_EVENT_TRACK_BUFFER
, &id3
);
1788 tracks
[track_widx
].id3_hid
=
1789 bufalloc(&id3
, sizeof(struct mp3entry
), TYPE_ID3
);
1791 if (tracks
[track_widx
].id3_hid
< 0)
1795 copy_mp3entry(&lasttrack_id3
, &id3
);
1799 if (track_widx
== track_ridx
)
1800 copy_mp3entry(&curtrack_id3
, &id3
);
1804 track_changed
= true;
1805 playlist_update_resume_info(audio_current_track());
1810 logf("mde:%s!",trackname
);
1812 /* Skip invalid entry from playlist. */
1813 playlist_skip_entry(NULL
, last_peek_offset
);
1823 if (cuesheet_is_enabled() && tracks
[track_widx
].id3
.cuesheet_type
== 1)
1825 char cuepath
[MAX_PATH
];
1827 struct cuesheet
*cue
= start_play
? curr_cue
: temp_cue
;
1829 if (look_for_cuesheet_file(trackname
, cuepath
) &&
1830 parse_cuesheet(cuepath
, cue
))
1832 strcpy((cue
)->audio_filename
, trackname
);
1834 cue_spoof_id3(curr_cue
, &tracks
[track_widx
].id3
);
1839 struct mp3entry
*track_id3
;
1841 if (track_widx
== track_ridx
)
1842 track_id3
= &curtrack_id3
;
1844 track_id3
= bufgetid3(tracks
[track_widx
].id3_hid
);
1846 #ifdef HAVE_ALBUMART
1847 if (tracks
[track_widx
].aa_hid
< 0 && gui_sync_wps_uses_albumart())
1849 char aa_path
[MAX_PATH
];
1850 if (find_albumart(track_id3
, aa_path
, sizeof(aa_path
)))
1851 tracks
[track_widx
].aa_hid
= bufopen(aa_path
, 0, TYPE_BITMAP
);
1855 /* Load the codec. */
1856 if (!audio_loadcodec(start_play
))
1858 if (tracks
[track_widx
].codec_hid
== ERR_BUFFER_FULL
)
1860 /* No space for codec on buffer, not an error */
1864 /* This is an error condition, either no codec was found, or reading
1865 * the codec file failed part way through, either way, skip the track */
1866 snprintf(msgbuf
, sizeof(msgbuf
)-1, "No codec for: %s", trackname
);
1867 /* We should not use gui_syncplash from audio thread! */
1868 gui_syncsplash(HZ
*2, msgbuf
);
1869 /* Skip invalid entry from playlist. */
1870 playlist_skip_entry(NULL
, last_peek_offset
);
1874 track_id3
->elapsed
= 0;
1876 enum data_type type
= TYPE_PACKET_AUDIO
;
1878 switch (track_id3
->codectype
) {
1883 file_offset
= offset
;
1884 track_id3
->offset
= offset
;
1885 audio_set_elapsed(track_id3
);
1891 file_offset
= offset
;
1892 track_id3
->offset
= offset
;
1893 track_id3
->elapsed
= track_id3
->length
/ 2;
1897 case AFMT_OGG_VORBIS
:
1906 track_id3
->offset
= offset
;
1912 logf("Loading atomic %d",track_id3
->codectype
);
1913 type
= TYPE_ATOMIC_AUDIO
;
1917 logf("alt:%s", trackname
);
1919 if (file_offset
> AUDIO_REBUFFER_GUESS_SIZE
)
1920 file_offset
-= AUDIO_REBUFFER_GUESS_SIZE
;
1921 else if (track_id3
->first_frame_offset
)
1922 file_offset
= track_id3
->first_frame_offset
;
1926 tracks
[track_widx
].audio_hid
= bufopen(trackname
, file_offset
, type
);
1928 if (tracks
[track_widx
].audio_hid
< 0)
1931 /* All required data is now available for the codec. */
1932 tracks
[track_widx
].taginfo_ready
= true;
1936 ci
.curpos
=file_offset
;
1937 buf_request_buffer_handle(tracks
[track_widx
].audio_hid
);
1940 track_widx
= (track_widx
+ 1) & MAX_TRACK_MASK
;
1945 static void audio_fill_file_buffer(bool start_play
, size_t offset
)
1947 struct queue_event ev
;
1948 bool had_next_track
= audio_next_track() != NULL
;
1949 bool continue_buffering
;
1951 /* No need to rebuffer if there are track skips pending. */
1952 if (ci
.new_track
!= 0)
1955 /* Must reset the buffer before use if trashed or voice only - voice
1956 file size shouldn't have changed so we can go straight from
1957 BUFFER_STATE_VOICED_ONLY to BUFFER_STATE_INITIALIZED */
1958 if (buffer_state
!= BUFFER_STATE_INITIALIZED
)
1959 audio_reset_buffer();
1961 logf("Starting buffer fill");
1964 audio_clear_track_entries();
1966 /* Save the current resume position once. */
1967 playlist_update_resume_info(audio_current_track());
1970 continue_buffering
= audio_load_track(offset
, start_play
);
1974 if (queue_peek(&audio_queue
, &ev
)) {
1975 if (ev
.id
!= Q_AUDIO_FILL_BUFFER
)
1977 /* There's a message in the queue. break the loop to treat it,
1978 and go back to filling after that. */
1979 LOGFQUEUE("buffering > audio Q_AUDIO_FILL_BUFFER");
1980 queue_post(&audio_queue
, Q_AUDIO_FILL_BUFFER
, 0);
1984 } while (continue_buffering
);
1986 if (!had_next_track
&& audio_next_track())
1987 track_changed
= true;
1991 static void audio_rebuffer(void)
1993 logf("Forcing rebuffer");
1995 clear_track_info(CUR_TI
);
1997 /* Reset track pointers */
1998 track_widx
= track_ridx
;
1999 audio_clear_track_entries();
2001 /* Fill the buffer */
2002 last_peek_offset
= -1;
2005 if (!CUR_TI
->taginfo_ready
)
2006 memset(&curtrack_id3
, 0, sizeof(struct mp3entry
));
2008 audio_fill_file_buffer(false, 0);
2011 /* Called on request from the codec to get a new track. This is the codec part
2012 of the track transition. */
2013 static int audio_check_new_track(void)
2015 int track_count
= audio_track_count();
2016 int old_track_ridx
= track_ridx
;
2018 int next_playlist_index
;
2020 bool end_of_playlist
; /* Temporary flag, not the same as playlist_end */
2022 /* Now it's good time to send track unbuffer events. */
2023 send_event(PLAYBACK_EVENT_TRACK_FINISH
, &curtrack_id3
);
2028 if (playlist_next_dir(ci
.new_track
))
2036 LOGFQUEUE("audio >|= codec Q_CODEC_REQUEST_FAILED");
2037 return Q_CODEC_REQUEST_FAILED
;
2044 end_of_playlist
= playlist_peek(automatic_skip
? ci
.new_track
: 0) == NULL
;
2045 auto_dir_skip
= end_of_playlist
&& global_settings
.next_folder
;
2047 /* If the playlist isn't that big */
2048 if (automatic_skip
&& !playlist_check(ci
.new_track
))
2050 if (ci
.new_track
>= 0)
2052 LOGFQUEUE("audio >|= codec Q_CODEC_REQUEST_FAILED");
2053 return Q_CODEC_REQUEST_FAILED
;
2055 /* Find the beginning backward if the user over-skips it */
2056 while (!playlist_check(++ci
.new_track
))
2057 if (ci
.new_track
>= 0)
2059 LOGFQUEUE("audio >|= codec Q_CODEC_REQUEST_FAILED");
2060 return Q_CODEC_REQUEST_FAILED
;
2064 /* Update the playlist */
2065 last_peek_offset
-= ci
.new_track
;
2069 /* If the track change was the result of an auto dir skip,
2070 we need to update the playlist now */
2071 next_playlist_index
= playlist_next(ci
.new_track
);
2073 if (next_playlist_index
< 0)
2075 LOGFQUEUE("audio >|= codec Q_CODEC_REQUEST_FAILED");
2076 return Q_CODEC_REQUEST_FAILED
;
2083 new_playlist
= false;
2086 /* Save the track metadata to allow the WPS to display it
2087 while PCM finishes playing that track */
2088 copy_mp3entry(&prevtrack_id3
, &curtrack_id3
);
2090 /* Update the main buffer copy of the track metadata with the one
2091 the codec has been using (for the unbuffer callbacks) */
2092 if (CUR_TI
->id3_hid
>= 0)
2093 copy_mp3entry(bufgetid3(CUR_TI
->id3_hid
), &curtrack_id3
);
2095 /* Save a pointer to the old track to allow later clearing */
2098 for (i
= 0; i
< ci
.new_track
; i
++)
2100 idx
= (track_ridx
+ i
) & MAX_TRACK_MASK
;
2101 struct mp3entry
*id3
= bufgetid3(tracks
[idx
].id3_hid
);
2102 ssize_t offset
= buf_handle_offset(tracks
[idx
].audio_hid
);
2103 if (!id3
|| offset
< 0 || (unsigned)offset
> id3
->first_frame_offset
)
2105 /* We don't have all the audio data for that track, so clear it,
2106 but keep the metadata. */
2107 if (tracks
[idx
].audio_hid
>= 0 && bufclose(tracks
[idx
].audio_hid
))
2109 tracks
[idx
].audio_hid
= -1;
2110 tracks
[idx
].filesize
= 0;
2115 /* Move to the new track */
2116 track_ridx
= (track_ridx
+ ci
.new_track
) & MAX_TRACK_MASK
;
2118 buf_set_base_handle(CUR_TI
->audio_hid
);
2122 playlist_end
= false;
2123 wps_offset
= -ci
.new_track
;
2124 track_changed
= true;
2127 /* If it is not safe to even skip this many track entries */
2128 if (ci
.new_track
>= track_count
|| ci
.new_track
<= track_count
- MAX_TRACK
)
2135 forward
= ci
.new_track
> 0;
2138 /* If the target track is clearly not in memory */
2139 if (CUR_TI
->filesize
== 0 || !CUR_TI
->taginfo_ready
)
2145 /* When skipping backwards, it is possible that we've found a track that's
2146 * buffered, but which is around the track-wrap and therefor not the track
2147 * we are looking for */
2150 int cur_idx
= track_ridx
;
2151 bool taginfo_ready
= true;
2152 /* We've wrapped the buffer backwards if new > old */
2153 bool wrap
= track_ridx
> old_track_ridx
;
2157 cur_idx
= (cur_idx
+ 1) & MAX_TRACK_MASK
;
2159 /* if we've advanced past the wrap when cur_idx is zeroed */
2163 /* if we aren't still on the wrap and we've caught the old track */
2164 if (!(wrap
|| cur_idx
< old_track_ridx
))
2167 /* If we hit a track in between without valid tag info, bail */
2168 if (!tracks
[cur_idx
].taginfo_ready
)
2170 taginfo_ready
= false;
2181 audio_update_trackinfo();
2182 LOGFQUEUE("audio >|= codec Q_CODEC_REQUEST_COMPLETE");
2183 return Q_CODEC_REQUEST_COMPLETE
;
2186 unsigned long audio_prev_elapsed(void)
2188 return prev_track_elapsed
;
2191 static void audio_stop_codec_flush(void)
2193 ci
.stop_codec
= true;
2196 while (audio_codec_loaded
)
2199 /* If the audio codec is not loaded any more, and the audio is still
2200 * playing, it is now and _only_ now safe to call this function from the
2202 if (pcm_is_playing())
2205 pcmbuf_queue_clear();
2207 pcmbuf_pause(paused
);
2210 static void audio_stop_playback(void)
2212 /* If we were playing, save resume information */
2215 struct mp3entry
*id3
= NULL
;
2217 if (!playlist_end
|| !ci
.stop_codec
)
2219 /* Set this early, the outside code yields and may allow the codec
2220 to try to wait for a reply on a buffer wait */
2221 ci
.stop_codec
= true;
2222 id3
= audio_current_track();
2225 /* Save the current playing spot, or NULL if the playlist has ended */
2226 playlist_update_resume_info(id3
);
2228 /* TODO: Create auto bookmark too? */
2230 prev_track_elapsed
= curtrack_id3
.elapsed
;
2234 audio_stop_codec_flush();
2237 /* Mark all entries null. */
2238 audio_clear_track_entries();
2240 /* Close all tracks */
2241 audio_release_tracks();
2243 unregister_buffering_callback(buffering_audio_callback
);
2245 memset(&curtrack_id3
, 0, sizeof(struct mp3entry
));
2248 static void audio_play_start(size_t offset
)
2252 #if INPUT_SRC_CAPS != 0
2253 audio_set_input_source(AUDIO_SRC_PLAYBACK
, SRCF_PLAYBACK
);
2254 audio_set_output_source(AUDIO_SRC_PLAYBACK
);
2257 /* Wait for any previously playing audio to flush - TODO: Not necessary? */
2259 audio_stop_codec_flush();
2261 track_changed
= true;
2262 playlist_end
= false;
2270 sound_set_volume(global_settings
.volume
);
2271 track_widx
= track_ridx
= 0;
2273 /* Clear all track entries. */
2274 for (i
= 0; i
< MAX_TRACK
; i
++) {
2275 clear_track_info(&tracks
[i
]);
2278 last_peek_offset
= -1;
2280 /* Officially playing */
2281 queue_reply(&audio_queue
, 1);
2283 #ifndef HAVE_FLASH_STORAGE
2284 set_filebuf_watermark(buffer_margin
, 0);
2286 audio_fill_file_buffer(true, offset
);
2287 register_buffering_callback(buffering_audio_callback
);
2289 LOGFQUEUE("audio > audio Q_AUDIO_TRACK_CHANGED");
2290 queue_post(&audio_queue
, Q_AUDIO_TRACK_CHANGED
, 0);
2294 /* Invalidates all but currently playing track. */
2295 static void audio_invalidate_tracks(void)
2297 if (audio_have_tracks())
2299 last_peek_offset
= 0;
2300 playlist_end
= false;
2301 track_widx
= track_ridx
;
2303 /* Mark all other entries null (also buffered wrong metadata). */
2304 audio_clear_track_entries();
2306 track_widx
= (track_widx
+ 1) & MAX_TRACK_MASK
;
2308 audio_fill_file_buffer(false, 0);
2312 static void audio_new_playlist(void)
2314 /* Prepare to start a new fill from the beginning of the playlist */
2315 last_peek_offset
= -1;
2316 if (audio_have_tracks())
2319 skipped_during_pause
= true;
2320 playlist_end
= false;
2321 track_widx
= track_ridx
;
2322 audio_clear_track_entries();
2324 track_widx
= (track_widx
+ 1) & MAX_TRACK_MASK
;
2326 /* Mark the current track as invalid to prevent skipping back to it */
2327 CUR_TI
->taginfo_ready
= false;
2330 /* Signal the codec to initiate a track change forward */
2331 new_playlist
= true;
2334 /* Officially playing */
2335 queue_reply(&audio_queue
, 1);
2337 audio_fill_file_buffer(false, 0);
2340 /* Called on manual track skip */
2341 static void audio_initiate_track_change(long direction
)
2343 logf("audio_initiate_track_change(%ld)", direction
);
2345 playlist_end
= false;
2346 ci
.new_track
+= direction
;
2347 wps_offset
-= direction
;
2349 skipped_during_pause
= true;
2352 /* Called on manual dir skip */
2353 static void audio_initiate_dir_change(long direction
)
2355 playlist_end
= false;
2357 ci
.new_track
= direction
;
2359 skipped_during_pause
= true;
2362 /* Called when PCM track change is complete */
2363 static void audio_finalise_track_change(void)
2365 logf("audio_finalise_track_change");
2370 playlist_next(-wps_offset
);
2373 automatic_skip
= false;
2376 auto_dir_skip
= false;
2378 /* Invalidate prevtrack_id3 */
2379 prevtrack_id3
.path
[0] = 0;
2381 if (prev_ti
&& prev_ti
->audio_hid
< 0)
2383 /* No audio left so we clear all the track info. */
2384 clear_track_info(prev_ti
);
2387 if (prev_ti
&& prev_ti
->id3_hid
>= 0)
2389 /* Reset the elapsed time to force the progressbar to be empty if
2390 the user skips back to this track */
2391 bufgetid3(prev_ti
->id3_hid
)->elapsed
= 0;
2394 send_event(PLAYBACK_EVENT_TRACK_CHANGE
, &curtrack_id3
);
2396 track_changed
= true;
2397 playlist_update_resume_info(audio_current_track());
2401 * Layout audio buffer as follows - iram buffer depends on target:
2402 * [|SWAP:iram][|TALK]|MALLOC|FILE|GUARD|PCM|[SWAP:dram[|iram]|]
2404 static void audio_reset_buffer(void)
2406 /* see audio_get_recording_buffer if this is modified */
2407 logf("audio_reset_buffer");
2409 /* If the setup of anything allocated before the file buffer is
2410 changed, do check the adjustments after the buffer_alloc call
2411 as it will likely be affected and need sliding over */
2413 /* Initially set up file buffer as all space available */
2414 malloc_buf
= audiobuf
+ talk_get_bufsize();
2415 /* Align the malloc buf to line size. Especially important to cf
2416 targets that do line reads/writes. */
2417 malloc_buf
= (unsigned char *)(((uintptr_t)malloc_buf
+ 15) & ~15);
2418 filebuf
= malloc_buf
+ MALLOC_BUFSIZE
; /* filebuf line align implied */
2419 filebuflen
= audiobufend
- filebuf
;
2423 /* Subtract whatever the pcm buffer says it used plus the guard buffer */
2424 filebuflen
-= pcmbuf_init(filebuf
+ filebuflen
) + GUARD_BUFSIZE
;
2426 /* Make sure filebuflen is a longword multiple after adjustment - filebuf
2427 will already be line aligned */
2430 buffering_reset(filebuf
, filebuflen
);
2432 /* Clear any references to the file buffer */
2433 buffer_state
= BUFFER_STATE_INITIALIZED
;
2435 #if defined(ROCKBOX_HAS_LOGF) && defined(LOGF_ENABLE)
2436 /* Make sure everything adds up - yes, some info is a bit redundant but
2437 aids viewing and the sumation of certain variables should add up to
2438 the location of others. */
2441 unsigned char * pcmbuf
= pcmbuf_get_meminfo(&pcmbufsize
);
2442 logf("mabuf: %08X", (unsigned)malloc_buf
);
2443 logf("mabufe: %08X", (unsigned)(malloc_buf
+ MALLOC_BUFSIZE
));
2444 logf("fbuf: %08X", (unsigned)filebuf
);
2445 logf("fbufe: %08X", (unsigned)(filebuf
+ filebuflen
));
2446 logf("gbuf: %08X", (unsigned)(filebuf
+ filebuflen
));
2447 logf("gbufe: %08X", (unsigned)(filebuf
+ filebuflen
+ GUARD_BUFSIZE
));
2448 logf("pcmb: %08X", (unsigned)pcmbuf
);
2449 logf("pcmbe: %08X", (unsigned)(pcmbuf
+ pcmbufsize
));
2454 static void audio_thread(void)
2456 struct queue_event ev
;
2460 audio_thread_ready
= true;
2465 if (!pcmbuf_queue_scan(&ev
))
2466 queue_wait_w_tmo(&audio_queue
, &ev
, HZ
/2);
2469 case Q_AUDIO_FILL_BUFFER
:
2470 LOGFQUEUE("audio < Q_AUDIO_FILL_BUFFER");
2471 if (!playing
|| playlist_end
|| ci
.stop_codec
)
2473 audio_fill_file_buffer(false, 0);
2477 LOGFQUEUE("audio < Q_AUDIO_PLAY");
2478 if (playing
&& ev
.data
<= 0)
2479 audio_new_playlist();
2482 audio_stop_playback();
2483 audio_play_start((size_t)ev
.data
);
2488 LOGFQUEUE("audio < Q_AUDIO_STOP");
2490 audio_stop_playback();
2492 queue_clear(&audio_queue
);
2496 LOGFQUEUE("audio < Q_AUDIO_PAUSE");
2497 if (!(bool) ev
.data
&& skipped_during_pause
&& !pcmbuf_is_crossfade_active())
2498 pcmbuf_play_stop(); /* Flush old track on resume after skip */
2499 skipped_during_pause
= false;
2502 pcmbuf_pause((bool)ev
.data
);
2503 paused
= (bool)ev
.data
;
2507 LOGFQUEUE("audio < Q_AUDIO_SKIP");
2508 audio_initiate_track_change((long)ev
.data
);
2511 case Q_AUDIO_PRE_FF_REWIND
:
2512 LOGFQUEUE("audio < Q_AUDIO_PRE_FF_REWIND");
2518 case Q_AUDIO_FF_REWIND
:
2519 LOGFQUEUE("audio < Q_AUDIO_FF_REWIND");
2524 /* An automatic track skip is in progress. Finalize it,
2525 then go back to the previous track */
2526 audio_finalise_track_change();
2529 ci
.seek_time
= (long)ev
.data
+1;
2532 case Q_AUDIO_CHECK_NEW_TRACK
:
2533 LOGFQUEUE("audio < Q_AUDIO_CHECK_NEW_TRACK");
2534 queue_reply(&audio_queue
, audio_check_new_track());
2537 case Q_AUDIO_DIR_SKIP
:
2538 LOGFQUEUE("audio < Q_AUDIO_DIR_SKIP");
2539 playlist_end
= false;
2540 audio_initiate_dir_change(ev
.data
);
2544 LOGFQUEUE("audio < Q_AUDIO_FLUSH");
2545 audio_invalidate_tracks();
2548 case Q_AUDIO_TRACK_CHANGED
:
2549 /* PCM track change done */
2550 LOGFQUEUE("audio < Q_AUDIO_TRACK_CHANGED");
2551 audio_finalise_track_change();
2555 case SYS_USB_CONNECTED
:
2556 LOGFQUEUE("audio < SYS_USB_CONNECTED");
2558 audio_stop_playback();
2559 #ifdef PLAYBACK_VOICE
2562 usb_acknowledge(SYS_USB_CONNECTED_ACK
);
2563 usb_wait_for_disconnect(&audio_queue
);
2565 /* Mark all entries null. */
2566 audio_clear_track_entries();
2568 /* release tracks to make sure all handles are closed */
2569 audio_release_tracks();
2574 LOGFQUEUE_SYS_TIMEOUT("audio < SYS_TIMEOUT");
2578 LOGFQUEUE("audio < default");
2584 /* Initialize the audio system - called from init() in main.c.
2585 * Last function because of all the references to internal symbols
2587 void audio_init(void)
2589 struct thread_entry
*audio_thread_p
;
2591 /* Can never do this twice */
2592 if (audio_is_initialized
)
2594 logf("audio: already initialized");
2598 logf("audio: initializing");
2600 /* Initialize queues before giving control elsewhere in case it likes
2601 to send messages. Thread creation will be delayed however so nothing
2602 starts running until ready if something yields such as talk_init. */
2603 queue_init(&audio_queue
, true);
2604 queue_enable_queue_send(&audio_queue
, &audio_queue_sender_list
);
2605 queue_init(&codec_queue
, false);
2606 queue_enable_queue_send(&codec_queue
, &codec_queue_sender_list
);
2607 queue_init(&pcmbuf_queue
, false);
2611 /* Initialize codec api. */
2612 ci
.read_filebuf
= codec_filebuf_callback
;
2613 ci
.pcmbuf_insert
= codec_pcmbuf_insert_callback
;
2614 ci
.get_codec_memory
= codec_get_memory_callback
;
2615 ci
.request_buffer
= codec_request_buffer_callback
;
2616 ci
.advance_buffer
= codec_advance_buffer_callback
;
2617 ci
.advance_buffer_loc
= codec_advance_buffer_loc_callback
;
2618 ci
.request_next_track
= codec_request_next_track_callback
;
2619 ci
.mp3_get_filepos
= codec_mp3_get_filepos_callback
;
2620 ci
.seek_buffer
= codec_seek_buffer_callback
;
2621 ci
.seek_complete
= codec_seek_complete_callback
;
2622 ci
.set_elapsed
= codec_set_elapsed_callback
;
2623 ci
.set_offset
= codec_set_offset_callback
;
2624 ci
.configure
= codec_configure_callback
;
2625 ci
.discard_codec
= codec_discard_codec_callback
;
2626 ci
.dsp
= (struct dsp_config
*)dsp_configure(NULL
, DSP_MYDSP
,
2629 /* initialize the buffer */
2632 /* audio_reset_buffer must to know the size of voice buffer so init
2636 codec_thread_p
= create_thread(
2637 codec_thread
, codec_stack
, sizeof(codec_stack
),
2638 CREATE_THREAD_FROZEN
,
2639 codec_thread_name
IF_PRIO(, PRIORITY_PLAYBACK
)
2642 audio_thread_p
= create_thread(audio_thread
, audio_stack
,
2643 sizeof(audio_stack
), CREATE_THREAD_FROZEN
,
2644 audio_thread_name
IF_PRIO(, PRIORITY_SYSTEM
)
2647 #ifdef PLAYBACK_VOICE
2648 voice_thread_init();
2651 /* Set crossfade setting for next buffer init which should be about... */
2652 pcmbuf_crossfade_enable(global_settings
.crossfade
);
2654 /* initialize the buffering system */
2657 /* ...now! Set up the buffers */
2658 audio_reset_buffer();
2661 for(i
= 0; i
< MAX_TRACK
; i
++)
2663 tracks
[i
].audio_hid
= -1;
2664 tracks
[i
].id3_hid
= -1;
2665 tracks
[i
].codec_hid
= -1;
2666 #ifdef HAVE_ALBUMART
2667 tracks
[i
].aa_hid
= -1;
2671 /* Probably safe to say */
2672 audio_is_initialized
= true;
2674 sound_settings_apply();
2675 #ifndef HAVE_FLASH_STORAGE
2676 audio_set_buffer_margin(global_settings
.buffer_margin
);
2679 /* it's safe to let the threads run now */
2680 #ifdef PLAYBACK_VOICE
2681 voice_thread_resume();
2683 thread_thaw(codec_thread_p
);
2684 thread_thaw(audio_thread_p
);
2688 void audio_wait_for_init(void)
2690 /* audio thread will only set this once after it finished the final
2691 * audio hardware init so this little construct is safe - even
2693 while (!audio_thread_ready
)