Fix issues with file-based bootloader installation:
[Rockbox.git] / firmware / mpeg.c
blobde3b347f77410399018be17258dea6cadcc41dd4
1 /***************************************************************************
2 * __________ __ ___.
3 * Open \______ \ ____ ____ | | _\_ |__ _______ ___
4 * Source | _// _ \_/ ___\| |/ /| __ \ / _ \ \/ /
5 * Jukebox | | ( <_> ) \___| < | \_\ ( <_> > < <
6 * Firmware |____|_ /\____/ \___ >__|_ \|___ /\____/__/\_ \
7 * \/ \/ \/ \/ \/
8 * $Id$
10 * Copyright (C) 2002 by Linus Nielsen Feltzing
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 ****************************************************************************/
19 #include <stdbool.h>
20 #include <stdlib.h>
21 #include "config.h"
23 #if CONFIG_CODEC != SWCODEC
25 #include "debug.h"
26 #include "panic.h"
27 #include "id3.h"
28 #include "mpeg.h"
29 #include "audio.h"
30 #include "ata.h"
31 #include "string.h"
32 #include <kernel.h>
33 #include "thread.h"
34 #include "errno.h"
35 #include "mp3data.h"
36 #include "buffer.h"
37 #include "mp3_playback.h"
38 #include "sound.h"
39 #include "bitswap.h"
40 #ifndef SIMULATOR
41 #include "i2c.h"
42 #include "mas.h"
43 #include "dac.h"
44 #include "system.h"
45 #include "usb.h"
46 #include "file.h"
47 #include "hwcompat.h"
48 #endif /* !SIMULATOR */
49 #ifdef HAVE_LCD_BITMAP
50 #include "lcd.h"
51 #endif
53 #ifndef SIMULATOR
54 extern unsigned long mas_version_code;
55 #endif
57 #if CONFIG_CODEC == MAS3587F
58 extern enum /* from mp3_playback.c */
60 MPEG_DECODER,
61 MPEG_ENCODER
62 } mpeg_mode;
63 #endif /* CONFIG_CODEC == MAS3587F */
65 extern char* playlist_peek(int steps);
66 extern bool playlist_check(int steps);
67 extern int playlist_next(int steps);
68 extern int playlist_amount(void);
69 extern int playlist_update_resume_info(const struct mp3entry* id3);
71 #define MPEG_PLAY 1
72 #define MPEG_STOP 2
73 #define MPEG_PAUSE 3
74 #define MPEG_RESUME 4
75 #define MPEG_NEXT 5
76 #define MPEG_PREV 6
77 #define MPEG_FF_REWIND 7
78 #define MPEG_FLUSH_RELOAD 8
79 #define MPEG_RECORD 9
80 #define MPEG_INIT_RECORDING 10
81 #define MPEG_INIT_PLAYBACK 11
82 #define MPEG_NEW_FILE 12
83 #define MPEG_PAUSE_RECORDING 13
84 #define MPEG_RESUME_RECORDING 14
85 #define MPEG_NEED_DATA 100
86 #define MPEG_TRACK_CHANGE 101
87 #define MPEG_SAVE_DATA 102
88 #define MPEG_STOP_DONE 103
89 #define MPEG_PRERECORDING_TICK 104
91 /* indicator for MPEG_NEED_DATA */
92 #define GENERATE_UNBUFFER_EVENTS 1
94 /* list of tracks in memory */
95 #define MAX_TRACK_ENTRIES (1<<4) /* Must be power of 2 */
96 #define MAX_TRACK_ENTRIES_MASK (MAX_TRACK_ENTRIES - 1)
98 struct trackdata
100 struct mp3entry id3;
101 int mempos;
102 int load_ahead_index;
105 static struct trackdata trackdata[MAX_TRACK_ENTRIES];
107 static unsigned int current_track_counter = 0;
108 static unsigned int last_track_counter = 0;
110 /* Play time of the previous track */
111 unsigned long prev_track_elapsed;
113 #ifndef SIMULATOR
114 static int track_read_idx = 0;
115 static int track_write_idx = 0;
116 #endif /* !SIMULATOR */
118 /* Cuesheet callback */
119 static bool (*cuesheet_callback)(const char *filename) = NULL;
121 static const char mpeg_thread_name[] = "mpeg";
122 static unsigned int mpeg_errno;
124 static bool playing = false; /* We are playing an MP3 stream */
125 static bool is_playing = false; /* We are (attempting to) playing MP3 files */
126 static bool paused; /* playback is paused */
128 #ifdef SIMULATOR
129 static char mpeg_stack[DEFAULT_STACK_SIZE];
130 static struct mp3entry taginfo;
132 #else /* !SIMULATOR */
133 static struct event_queue mpeg_queue;
134 static long mpeg_stack[(DEFAULT_STACK_SIZE + 0x1000)/sizeof(long)];
136 static int audiobuflen;
137 static int audiobuf_write;
138 static int audiobuf_swapwrite;
139 static int audiobuf_read;
141 static int mpeg_file;
143 static bool play_pending; /* We are about to start playing */
144 static bool play_pending_track_change; /* When starting play we're starting a new file */
145 static bool filling; /* We are filling the buffer with data from disk */
146 static bool dma_underrun; /* True when the DMA has stopped because of
147 slow disk reading (read error, shaking) */
148 static bool mpeg_stop_done;
150 static int last_dma_tick = 0;
151 static int last_dma_chunk_size;
153 static long low_watermark; /* Dynamic low watermark level */
154 static long low_watermark_margin = 0; /* Extra time in seconds for watermark */
155 static long lowest_watermark_level; /* Debug value to observe the buffer
156 usage */
157 #if CONFIG_CODEC == MAS3587F
158 static char recording_filename[MAX_PATH]; /* argument to thread */
159 static char delayed_filename[MAX_PATH]; /* internal copy of above */
161 static char xing_buffer[MAX_XING_HEADER_SIZE];
163 static bool init_recording_done;
164 static bool init_playback_done;
165 static bool prerecording; /* True if prerecording is enabled */
166 static bool is_prerecording; /* True if we are prerecording */
167 static bool is_recording; /* We are recording */
169 static enum {
170 NOT_SAVING = 0, /* reasons to save data, sorted by importance */
171 BUFFER_FULL,
172 NEW_FILE,
173 STOP_RECORDING
174 } saving_status;
176 static int rec_frequency_index; /* For create_xing_header() calls */
177 static int rec_version_index; /* For create_xing_header() calls */
179 struct prerecord_info {
180 int mempos;
181 unsigned long framecount;
184 static struct prerecord_info prerecord_buffer[MPEG_MAX_PRERECORD_SECONDS];
185 static int prerecord_index; /* Current index in the prerecord buffer */
186 static int prerecording_max_seconds; /* Max number of seconds to store */
187 static int prerecord_count; /* Number of seconds in the prerecord buffer */
188 static int prerecord_timeout; /* The tick count of the next prerecord data
189 store */
191 unsigned long record_start_time; /* Value of current_tick when recording
192 was started */
193 unsigned long pause_start_time; /* Value of current_tick when pause was
194 started */
195 static unsigned long last_rec_time;
196 static unsigned long num_rec_bytes;
197 static unsigned long last_rec_bytes;
198 static unsigned long frame_count_start;
199 static unsigned long frame_count_end;
200 static unsigned long saved_header = 0;
202 /* Shadow MAS registers */
203 unsigned long shadow_encoder_control = 0;
204 #endif /* CONFIG_CODEC == MAS3587F */
206 #if (CONFIG_CODEC == MAS3587F) || (CONFIG_CODEC == MAS3539F)
207 unsigned long shadow_io_control_main = 0;
208 unsigned long shadow_soft_mute = 0;
209 unsigned shadow_codec_reg0;
210 #endif /* (CONFIG_CODEC == MAS3587F) || (CONFIG_CODEC == MAS3539F) */
212 #ifdef HAVE_RECORDING
213 static const unsigned char empty_id3_header[] =
215 'I', 'D', '3', 0x03, 0x00, 0x00,
216 0x00, 0x00, 0x1f, 0x76 /* Size is 4096 minus 10 bytes for the header */
218 #endif /* HAVE_RECORDING */
221 static int get_unplayed_space(void);
222 static int get_playable_space(void);
223 static int get_unswapped_space(void);
224 #endif /* !SIMULATOR */
226 #if (CONFIG_CODEC == MAS3587F) && !defined(SIMULATOR)
227 static void init_recording(void);
228 static void prepend_header(void);
229 static void update_header(void);
230 static void start_prerecording(void);
231 static void start_recording(void);
232 static void stop_recording(void);
233 static int get_unsaved_space(void);
234 static void pause_recording(void);
235 static void resume_recording(void);
236 #endif /* (CONFIG_CODEC == MAS3587F) && !defined(SIMULATOR) */
239 #ifndef SIMULATOR
240 static int num_tracks_in_memory(void)
242 return (track_write_idx - track_read_idx) & MAX_TRACK_ENTRIES_MASK;
245 #ifdef DEBUG_TAGS
246 static void debug_tags(void)
248 int i;
250 for(i = 0;i < MAX_TRACK_ENTRIES;i++)
252 DEBUGF("%d - %s\n", i, trackdata[i].id3.path);
254 DEBUGF("read: %d, write :%d\n", track_read_idx, track_write_idx);
255 DEBUGF("num_tracks_in_memory: %d\n", num_tracks_in_memory());
257 #else /* !DEBUG_TAGS */
258 #define debug_tags()
259 #endif /* !DEBUG_TAGS */
261 static void remove_current_tag(void)
263 if(num_tracks_in_memory() > 0)
265 /* First move the index, so nobody tries to access the tag */
266 track_read_idx = (track_read_idx+1) & MAX_TRACK_ENTRIES_MASK;
267 debug_tags();
269 else
271 DEBUGF("remove_current_tag: no tracks to remove\n");
275 static void remove_all_non_current_tags(void)
277 track_write_idx = (track_read_idx+1) & MAX_TRACK_ENTRIES_MASK;
278 debug_tags();
281 static void remove_all_tags(void)
283 track_write_idx = track_read_idx;
285 debug_tags();
288 static struct trackdata *get_trackdata(int offset)
290 if(offset >= num_tracks_in_memory())
291 return NULL;
292 else
293 return &trackdata[(track_read_idx + offset) & MAX_TRACK_ENTRIES_MASK];
295 #endif /* !SIMULATOR */
297 /***********************************************************************/
298 /* audio event handling */
300 #define MAX_EVENT_HANDLERS 10
301 struct event_handlers_table
303 AUDIO_EVENT_HANDLER handler;
304 unsigned short mask;
306 static struct event_handlers_table event_handlers[MAX_EVENT_HANDLERS];
307 static int event_handlers_count = 0;
309 void audio_register_event_handler(AUDIO_EVENT_HANDLER handler, unsigned short mask)
311 if (event_handlers_count < MAX_EVENT_HANDLERS)
313 event_handlers[event_handlers_count].handler = handler;
314 event_handlers[event_handlers_count].mask = mask;
315 event_handlers_count++;
319 /* dispatch calls each handler in the order registered and returns after some
320 handler actually handles the event (the event is assumed to no longer be valid
321 after this, due to the handler changing some condition); returns true if someone
322 handled the event, which is expected to cause the caller to skip its own handling
323 of the event */
324 #ifndef SIMULATOR
325 static bool audio_dispatch_event(unsigned short event, unsigned long data)
327 int i = 0;
328 for(i=0; i < event_handlers_count; i++)
330 if ( event_handlers[i].mask & event )
332 int rc = event_handlers[i].handler(event, data);
333 if ( rc == AUDIO_EVENT_RC_HANDLED )
334 return true;
337 return false;
339 #endif
341 /***********************************************************************/
343 static void set_elapsed(struct mp3entry* id3)
345 if ( id3->vbr ) {
346 if ( id3->has_toc ) {
347 /* calculate elapsed time using TOC */
348 int i;
349 unsigned int remainder, plen, relpos, nextpos;
351 /* find wich percent we're at */
352 for (i=0; i<100; i++ )
354 if ( id3->offset < id3->toc[i] * (id3->filesize / 256) )
356 break;
360 i--;
361 if (i < 0)
362 i = 0;
364 relpos = id3->toc[i];
366 if (i < 99)
368 nextpos = id3->toc[i+1];
370 else
372 nextpos = 256;
375 remainder = id3->offset - (relpos * (id3->filesize / 256));
377 /* set time for this percent (divide before multiply to prevent
378 overflow on long files. loss of precision is negligible on
379 short files) */
380 id3->elapsed = i * (id3->length / 100);
382 /* calculate remainder time */
383 plen = (nextpos - relpos) * (id3->filesize / 256);
384 id3->elapsed += (((remainder * 100) / plen) *
385 (id3->length / 10000));
387 else {
388 /* no TOC exists. set a rough estimate using average bitrate */
389 int tpk = id3->length / (id3->filesize / 1024);
390 id3->elapsed = id3->offset / 1024 * tpk;
393 else
394 /* constant bitrate, use exact calculation */
395 id3->elapsed = id3->offset / (id3->bitrate / 8);
398 int audio_get_file_pos(void)
400 int pos = -1;
401 struct mp3entry *id3 = audio_current_track();
403 if (id3->vbr)
405 if (id3->has_toc)
407 /* Use the TOC to find the new position */
408 unsigned int percent, remainder;
409 int curtoc, nexttoc, plen;
411 percent = (id3->elapsed*100)/id3->length;
412 if (percent > 99)
413 percent = 99;
415 curtoc = id3->toc[percent];
417 if (percent < 99)
418 nexttoc = id3->toc[percent+1];
419 else
420 nexttoc = 256;
422 pos = (id3->filesize/256)*curtoc;
424 /* Use the remainder to get a more accurate position */
425 remainder = (id3->elapsed*100)%id3->length;
426 remainder = (remainder*100)/id3->length;
427 plen = (nexttoc - curtoc)*(id3->filesize/256);
428 pos += (plen/100)*remainder;
430 else
432 /* No TOC exists, estimate the new position */
433 pos = (id3->filesize / (id3->length / 1000)) *
434 (id3->elapsed / 1000);
437 else if (id3->bitrate)
438 pos = id3->elapsed * (id3->bitrate / 8);
439 else
441 return -1;
444 if (pos >= (int)(id3->filesize - id3->id3v1len))
446 /* Don't seek right to the end of the file so that we can
447 transition properly to the next song */
448 pos = id3->filesize - id3->id3v1len - 1;
450 else if (pos < (int)id3->first_frame_offset)
452 /* skip past id3v2 tag and other leading garbage */
453 pos = id3->first_frame_offset;
455 return pos;
458 unsigned long mpeg_get_last_header(void)
460 #ifdef SIMULATOR
461 return 0;
462 #else /* !SIMULATOR */
463 unsigned long tmp[2];
465 /* Read the frame data from the MAS and reconstruct it with the
466 frame sync and all */
467 mas_readmem(MAS_BANK_D0, MAS_D0_MPEG_STATUS_1, tmp, 2);
468 return 0xffe00000 | ((tmp[0] & 0x7c00) << 6) | (tmp[1] & 0xffff);
469 #endif /* !SIMULATOR */
472 void audio_set_cuesheet_callback(bool (*handler)(const char *filename))
474 cuesheet_callback = handler;
477 #ifndef SIMULATOR
478 /* Send callback events to notify about removing old tracks. */
479 static void generate_unbuffer_events(void)
481 int i;
482 int numentries = MAX_TRACK_ENTRIES - num_tracks_in_memory();
483 int cur_idx = track_write_idx;
485 for (i = 0; i < numentries; i++)
487 /* Send an event to notify that track has finished. */
488 send_event(PLAYBACK_EVENT_TRACK_FINISH, &trackdata[cur_idx].id3);
489 cur_idx = (cur_idx + 1) & MAX_TRACK_ENTRIES_MASK;
493 /* Send callback events to notify about new tracks. */
494 static void generate_postbuffer_events(void)
496 int i;
497 int numentries = num_tracks_in_memory();
498 int cur_idx = track_read_idx;
500 for (i = 0; i < numentries; i++)
502 send_event(PLAYBACK_EVENT_TRACK_BUFFER, &trackdata[cur_idx].id3);
503 cur_idx = (cur_idx + 1) & MAX_TRACK_ENTRIES_MASK;
507 static void recalculate_watermark(int bitrate)
509 int bytes_per_sec;
510 int time = ata_spinup_time;
512 /* A bitrate of 0 probably means empty VBR header. We play safe
513 and set a high threshold */
514 if(bitrate == 0)
515 bitrate = 320;
517 bytes_per_sec = bitrate * 1000 / 8;
519 if(time)
521 /* No drive spins up faster than 3.5s */
522 if(time < 350)
523 time = 350;
525 time = time * 3;
526 low_watermark = ((low_watermark_margin * HZ + time) *
527 bytes_per_sec) / HZ;
529 else
531 low_watermark = MPEG_LOW_WATER;
535 #ifndef HAVE_FLASH_STORAGE
536 void audio_set_buffer_margin(int seconds)
538 low_watermark_margin = seconds;
540 #endif
542 void audio_get_debugdata(struct audio_debug *dbgdata)
544 dbgdata->audiobuflen = audiobuflen;
545 dbgdata->audiobuf_write = audiobuf_write;
546 dbgdata->audiobuf_swapwrite = audiobuf_swapwrite;
547 dbgdata->audiobuf_read = audiobuf_read;
549 dbgdata->last_dma_chunk_size = last_dma_chunk_size;
551 #if CONFIG_CPU == SH7034
552 dbgdata->dma_on = (SCR0 & 0x80) != 0;
553 #endif
554 dbgdata->playing = playing;
555 dbgdata->play_pending = play_pending;
556 dbgdata->is_playing = is_playing;
557 dbgdata->filling = filling;
558 dbgdata->dma_underrun = dma_underrun;
560 dbgdata->unplayed_space = get_unplayed_space();
561 dbgdata->playable_space = get_playable_space();
562 dbgdata->unswapped_space = get_unswapped_space();
564 dbgdata->low_watermark_level = low_watermark;
565 dbgdata->lowest_watermark_level = lowest_watermark_level;
568 #ifdef DEBUG
569 static void dbg_timer_start(void)
571 /* We are using timer 2 */
573 TSTR &= ~0x04; /* Stop the timer */
574 TSNC &= ~0x04; /* No synchronization */
575 TMDR &= ~0x44; /* Operate normally */
577 TCNT2 = 0; /* Start counting at 0 */
578 TCR2 = 0x03; /* Sysclock/8 */
580 TSTR |= 0x04; /* Start timer 2 */
583 static int dbg_cnt2us(unsigned int cnt)
585 return (cnt * 10000) / (FREQ/800);
587 #endif /* DEBUG */
589 static int get_unplayed_space(void)
591 int space = audiobuf_write - audiobuf_read;
592 if (space < 0)
593 space += audiobuflen;
594 return space;
597 static int get_playable_space(void)
599 int space = audiobuf_swapwrite - audiobuf_read;
600 if (space < 0)
601 space += audiobuflen;
602 return space;
605 static int get_unplayed_space_current_song(void)
607 int space;
609 if (num_tracks_in_memory() > 1)
611 space = get_trackdata(1)->mempos - audiobuf_read;
613 else
615 space = audiobuf_write - audiobuf_read;
618 if (space < 0)
619 space += audiobuflen;
621 return space;
624 static int get_unswapped_space(void)
626 int space = audiobuf_write - audiobuf_swapwrite;
627 if (space < 0)
628 space += audiobuflen;
629 return space;
632 #if CONFIG_CODEC == MAS3587F
633 static int get_unsaved_space(void)
635 int space = audiobuf_write - audiobuf_read;
636 if (space < 0)
637 space += audiobuflen;
638 return space;
641 static void drain_dma_buffer(void)
643 while (PBDRH & 0x40)
645 xor_b(0x08, &PADRH);
647 while (PBDRH & 0x80);
649 xor_b(0x08, &PADRH);
651 while (!(PBDRH & 0x80));
655 #ifdef DEBUG
656 static long timing_info_index = 0;
657 static long timing_info[1024];
658 #endif /* DEBUG */
660 void rec_tick (void) __attribute__ ((section (".icode")));
661 void rec_tick(void)
663 int i;
664 int delay;
665 char data;
667 if(is_recording && (PBDRH & 0x40))
669 #ifdef DEBUG
670 timing_info[timing_info_index++] = current_tick;
671 TCNT2 = 0;
672 #endif /* DEBUG */
673 /* Note: Although this loop is run in interrupt context, further
674 * optimisation will do no good. The MAS would then deliver bad
675 * frames occasionally, as observed in extended experiments. */
676 i = 0;
677 while (PBDRH & 0x40) /* We try to read as long as EOD is high */
679 xor_b(0x08, &PADRH); /* Set PR active, independent of polarity */
681 delay = 100;
682 while (PBDRH & 0x80) /* Wait until /RTW becomes active */
684 if (--delay <= 0) /* Bail out if we have to wait too long */
685 { /* i.e. the MAS doesn't want to talk to us */
686 xor_b(0x08, &PADRH); /* Set PR inactive */
687 goto transfer_end; /* and get out of here */
691 data = *(unsigned char *)0x04000000; /* read data byte */
693 xor_b(0x08, &PADRH); /* Set PR inactive */
695 audiobuf[audiobuf_write++] = data;
697 if (audiobuf_write >= audiobuflen)
698 audiobuf_write = 0;
700 i++;
702 transfer_end:
704 #ifdef DEBUG
705 timing_info[timing_info_index++] = TCNT2 + (i << 16);
706 timing_info_index &= 0x3ff;
707 #endif /* DEBUG */
709 num_rec_bytes += i;
711 if(is_prerecording)
713 if(TIME_AFTER(current_tick, prerecord_timeout))
715 prerecord_timeout = current_tick + HZ;
716 queue_post(&mpeg_queue, MPEG_PRERECORDING_TICK, 0);
719 else
721 /* Signal to save the data if we are running out of buffer
722 space */
723 if (audiobuflen - get_unsaved_space() < MPEG_RECORDING_LOW_WATER
724 && saving_status == NOT_SAVING)
726 saving_status = BUFFER_FULL;
727 queue_post(&mpeg_queue, MPEG_SAVE_DATA, 0);
732 #endif /* CONFIG_CODEC == MAS3587F */
734 void playback_tick(void)
736 struct trackdata *ptd = get_trackdata(0);
737 if(ptd)
739 ptd->id3.elapsed += (current_tick - last_dma_tick) * 1000 / HZ;
740 last_dma_tick = current_tick;
741 audio_dispatch_event(AUDIO_EVENT_POS_REPORT,
742 (unsigned long)ptd->id3.elapsed);
746 static void reset_mp3_buffer(void)
748 audiobuf_read = 0;
749 audiobuf_write = 0;
750 audiobuf_swapwrite = 0;
751 lowest_watermark_level = audiobuflen;
754 /* DMA transfer end interrupt callback */
755 static void transfer_end(unsigned char** ppbuf, size_t* psize)
757 if(playing && !paused)
759 int unplayed_space_left;
760 int space_until_end_of_buffer;
761 int track_offset = 1;
762 struct trackdata *track;
764 audiobuf_read += last_dma_chunk_size;
765 if(audiobuf_read >= audiobuflen)
766 audiobuf_read = 0;
768 /* First, check if we are on a track boundary */
769 if (num_tracks_in_memory() > 1)
771 if (audiobuf_read == get_trackdata(track_offset)->mempos)
773 if ( ! audio_dispatch_event(AUDIO_EVENT_END_OF_TRACK, 0) )
775 queue_post(&mpeg_queue, MPEG_TRACK_CHANGE, 0);
776 track_offset++;
781 unplayed_space_left = get_unplayed_space();
783 space_until_end_of_buffer = audiobuflen - audiobuf_read;
785 if(!filling && unplayed_space_left < low_watermark)
787 filling = true;
788 queue_post(&mpeg_queue, MPEG_NEED_DATA, GENERATE_UNBUFFER_EVENTS);
791 if(unplayed_space_left)
793 last_dma_chunk_size = MIN(0x2000, unplayed_space_left);
794 last_dma_chunk_size = MIN(last_dma_chunk_size,
795 space_until_end_of_buffer);
797 /* several tracks loaded? */
798 track = get_trackdata(track_offset);
799 if(track)
801 /* will we move across the track boundary? */
802 if (( audiobuf_read < track->mempos ) &&
803 ((audiobuf_read+last_dma_chunk_size) >
804 track->mempos ))
806 /* Make sure that we end exactly on the boundary */
807 last_dma_chunk_size = track->mempos - audiobuf_read;
811 *psize = last_dma_chunk_size & 0xffff;
812 *ppbuf = audiobuf + audiobuf_read;
813 track = get_trackdata(0);
814 if(track)
815 track->id3.offset += last_dma_chunk_size;
817 /* Update the watermark debug level */
818 if(unplayed_space_left < lowest_watermark_level)
819 lowest_watermark_level = unplayed_space_left;
821 else
823 /* Check if the end of data is because of a hard disk error.
824 If there is an open file handle, we are still playing music.
825 If not, the last file has been loaded, and the file handle is
826 closed. */
827 if(mpeg_file >= 0)
829 /* Update the watermark debug level */
830 if(unplayed_space_left < lowest_watermark_level)
831 lowest_watermark_level = unplayed_space_left;
833 DEBUGF("DMA underrun.\n");
834 dma_underrun = true;
836 else
838 if ( ! audio_dispatch_event(AUDIO_EVENT_END_OF_TRACK, 0) )
840 DEBUGF("No more MP3 data. Stopping.\n");
841 queue_post(&mpeg_queue, MPEG_TRACK_CHANGE, 0);
842 playing = false;
845 *psize = 0; /* no more transfer */
850 static struct trackdata *add_track_to_tag_list(const char *filename)
852 struct trackdata *track;
854 if(num_tracks_in_memory() >= MAX_TRACK_ENTRIES)
856 DEBUGF("Tag memory is full\n");
857 return NULL;
860 track = &trackdata[track_write_idx];
862 /* grab id3 tag of new file and
863 remember where in memory it starts */
864 if(mp3info(&track->id3, filename))
866 DEBUGF("Bad mp3\n");
867 return NULL;
869 track->mempos = audiobuf_write;
870 track->id3.elapsed = 0;
871 #ifdef HAVE_LCD_BITMAP
872 if (track->id3.title)
873 lcd_getstringsize(track->id3.title, NULL, NULL);
874 if (track->id3.artist)
875 lcd_getstringsize(track->id3.artist, NULL, NULL);
876 if (track->id3.album)
877 lcd_getstringsize(track->id3.album, NULL, NULL);
878 #endif
879 if (cuesheet_callback)
880 if (cuesheet_callback(filename))
881 track->id3.cuesheet_type = 1;
883 track_write_idx = (track_write_idx+1) & MAX_TRACK_ENTRIES_MASK;
884 debug_tags();
885 return track;
888 static int new_file(int steps)
890 int max_steps = playlist_amount();
891 int start = 0;
892 int i;
893 struct trackdata *track;
895 /* Find out how many steps to advance. The load_ahead_index field tells
896 us how many playlist entries it had to skip to get to a valid one.
897 We add those together to find out where to start. */
898 if(steps > 0 && num_tracks_in_memory() > 1)
900 /* Begin with the song after the currently playing one */
901 i = 1;
902 while((track = get_trackdata(i++)))
904 start += track->load_ahead_index;
908 do {
909 char *trackname;
911 trackname = playlist_peek( start + steps );
912 if ( !trackname )
913 return -1;
915 DEBUGF("Loading %s\n", trackname);
917 mpeg_file = open(trackname, O_RDONLY);
918 if(mpeg_file < 0) {
919 DEBUGF("Couldn't open file: %s\n",trackname);
920 if(steps < 0)
921 steps--;
922 else
923 steps++;
925 else
927 struct trackdata *track = add_track_to_tag_list(trackname);
929 if(!track)
931 /* Bad mp3 file */
932 if(steps < 0)
933 steps--;
934 else
935 steps++;
936 close(mpeg_file);
937 mpeg_file = -1;
939 else
941 /* skip past id3v2 tag */
942 lseek(mpeg_file,
943 track->id3.first_frame_offset,
944 SEEK_SET);
945 track->id3.index = steps;
946 track->load_ahead_index = steps;
947 track->id3.offset = 0;
949 if(track->id3.vbr)
950 /* Average bitrate * 1.5 */
951 recalculate_watermark(
952 (track->id3.bitrate * 3) / 2);
953 else
954 recalculate_watermark(
955 track->id3.bitrate);
960 /* Bail out if no file could be opened */
961 if(abs(steps) > max_steps)
962 return -1;
963 } while ( mpeg_file < 0 );
965 return 0;
968 static void stop_playing(void)
970 struct trackdata *track;
972 /* Stop the current stream */
973 mp3_play_stop();
974 playing = false;
975 filling = false;
977 track = get_trackdata(0);
978 if (track != NULL)
979 prev_track_elapsed = track->id3.elapsed;
981 if(mpeg_file >= 0)
982 close(mpeg_file);
983 mpeg_file = -1;
984 remove_all_tags();
985 generate_unbuffer_events();
986 reset_mp3_buffer();
989 static void end_current_track(void) {
990 struct trackdata *track;
992 play_pending = false;
993 playing = false;
994 mp3_play_pause(false);
996 track = get_trackdata(0);
997 if (track != NULL)
998 prev_track_elapsed = track->id3.elapsed;
1000 reset_mp3_buffer();
1001 remove_all_tags();
1002 generate_unbuffer_events();
1004 if(mpeg_file >= 0)
1005 close(mpeg_file);
1008 /* Is this a really the end of playback or is a new playlist starting */
1009 static void check_playlist_end(int direction)
1011 /* Use the largest possible step size to account for skipped tracks */
1012 int steps = playlist_amount();
1014 if (direction < 0)
1015 steps = -steps;
1017 if (playlist_next(steps) < 0)
1018 is_playing = false;
1021 static void update_playlist(void)
1023 if (num_tracks_in_memory() > 0)
1025 struct trackdata *track = get_trackdata(0);
1026 track->id3.index = playlist_next(track->id3.index);
1028 else
1030 /* End of playlist? */
1031 check_playlist_end(1);
1034 playlist_update_resume_info(audio_current_track());
1037 static void track_change(void)
1039 DEBUGF("Track change\n");
1041 struct trackdata *track = get_trackdata(0);
1042 prev_track_elapsed = track->id3.elapsed;
1044 #if (CONFIG_CODEC == MAS3587F) || (CONFIG_CODEC == MAS3539F)
1045 /* Reset the AVC */
1046 sound_set_avc(-1);
1047 #endif /* (CONFIG_CODEC == MAS3587F) || (CONFIG_CODEC == MAS3539F) */
1049 if (num_tracks_in_memory() > 0)
1051 remove_current_tag();
1052 send_event(PLAYBACK_EVENT_TRACK_CHANGE, audio_current_track());
1053 update_playlist();
1056 current_track_counter++;
1059 unsigned long audio_prev_elapsed(void)
1061 return prev_track_elapsed;
1064 #ifdef DEBUG
1065 void hexdump(const unsigned char *buf, int len)
1067 int i;
1069 for(i = 0;i < len;i++)
1071 if(i && (i & 15) == 0)
1073 DEBUGF("\n");
1075 DEBUGF("%02x ", buf[i]);
1077 DEBUGF("\n");
1079 #endif /* DEBUG */
1081 static void start_playback_if_ready(void)
1083 int playable_space;
1085 playable_space = audiobuf_swapwrite - audiobuf_read;
1086 if(playable_space < 0)
1087 playable_space += audiobuflen;
1089 /* See if we have started playing yet. If not, do it. */
1090 if(play_pending || dma_underrun)
1092 /* If the filling has stopped, and we still haven't reached
1093 the watermark, the file must be smaller than the
1094 watermark. We must still play it. */
1095 if((playable_space >= MPEG_PLAY_PENDING_THRESHOLD) ||
1096 !filling || dma_underrun)
1098 DEBUGF("P\n");
1099 if (play_pending) /* don't do this when recovering from DMA underrun */
1101 generate_postbuffer_events(); /* signal first track as buffered */
1102 if (play_pending_track_change)
1104 play_pending_track_change = false;
1105 send_event(PLAYBACK_EVENT_TRACK_CHANGE, audio_current_track());
1107 play_pending = false;
1109 playing = true;
1111 last_dma_chunk_size = MIN(0x2000, get_unplayed_space_current_song());
1112 mp3_play_data(audiobuf + audiobuf_read, last_dma_chunk_size, transfer_end);
1113 dma_underrun = false;
1115 if (!paused)
1117 last_dma_tick = current_tick;
1118 mp3_play_pause(true);
1121 /* Tell ourselves that we need more data */
1122 queue_post(&mpeg_queue, MPEG_NEED_DATA, 0);
1127 static bool swap_one_chunk(void)
1129 int free_space_left;
1130 int amount_to_swap;
1132 free_space_left = get_unswapped_space();
1134 if(free_space_left == 0 && !play_pending)
1135 return false;
1137 /* Swap in larger chunks when the user is waiting for the playback
1138 to start, or when there is dangerously little playable data left */
1139 if(play_pending)
1140 amount_to_swap = MIN(MPEG_PLAY_PENDING_SWAPSIZE, free_space_left);
1141 else
1143 if(get_playable_space() < low_watermark)
1144 amount_to_swap = MIN(MPEG_LOW_WATER_SWAP_CHUNKSIZE,
1145 free_space_left);
1146 else
1147 amount_to_swap = MIN(MPEG_SWAP_CHUNKSIZE, free_space_left);
1150 if(audiobuf_write < audiobuf_swapwrite)
1151 amount_to_swap = MIN(audiobuflen - audiobuf_swapwrite,
1152 amount_to_swap);
1153 else
1154 amount_to_swap = MIN(audiobuf_write - audiobuf_swapwrite,
1155 amount_to_swap);
1157 bitswap(audiobuf + audiobuf_swapwrite, amount_to_swap);
1159 audiobuf_swapwrite += amount_to_swap;
1160 if(audiobuf_swapwrite >= audiobuflen)
1162 audiobuf_swapwrite = 0;
1165 return true;
1168 static void mpeg_thread(void)
1170 static int pause_tick = 0;
1171 static unsigned int pause_track = 0;
1172 struct queue_event ev;
1173 int len;
1174 int free_space_left;
1175 int unplayed_space_left;
1176 int amount_to_read;
1177 int t1, t2;
1178 int start_offset;
1179 #if CONFIG_CODEC == MAS3587F
1180 int amount_to_save;
1181 int save_endpos = 0;
1182 int rc;
1183 int level;
1184 long offset;
1185 #endif /* CONFIG_CODEC == MAS3587F */
1187 is_playing = false;
1188 play_pending = false;
1189 playing = false;
1190 mpeg_file = -1;
1192 while(1)
1194 #if CONFIG_CODEC == MAS3587F
1195 if(mpeg_mode == MPEG_DECODER)
1197 #endif /* CONFIG_CODEC == MAS3587F */
1198 yield();
1200 /* Swap if necessary, and don't block on the queue_wait() */
1201 if(swap_one_chunk())
1203 queue_wait_w_tmo(&mpeg_queue, &ev, 0);
1205 else if (playing)
1207 /* periodically update resume info */
1208 queue_wait_w_tmo(&mpeg_queue, &ev, HZ/2);
1210 else
1212 DEBUGF("S R:%x W:%x SW:%x\n",
1213 audiobuf_read, audiobuf_write, audiobuf_swapwrite);
1214 queue_wait(&mpeg_queue, &ev);
1217 start_playback_if_ready();
1219 switch(ev.id)
1221 case MPEG_PLAY:
1222 DEBUGF("MPEG_PLAY\n");
1224 #if CONFIG_TUNER
1225 /* Silence the A/D input, it may be on because the radio
1226 may be playing */
1227 mas_codec_writereg(6, 0x0000);
1228 #endif /* CONFIG_TUNER */
1230 /* Stop the current stream */
1231 paused = false;
1232 end_current_track();
1234 if ( new_file(0) == -1 )
1236 is_playing = false;
1237 track_change();
1238 break;
1241 start_offset = (int)ev.data;
1243 /* mid-song resume? */
1244 if (start_offset) {
1245 struct mp3entry* id3 = &get_trackdata(0)->id3;
1246 lseek(mpeg_file, start_offset, SEEK_SET);
1247 id3->offset = start_offset;
1248 set_elapsed(id3);
1250 else {
1251 /* skip past id3v2 tag */
1252 lseek(mpeg_file,
1253 get_trackdata(0)->id3.first_frame_offset,
1254 SEEK_SET);
1258 /* Make it read more data */
1259 filling = true;
1260 queue_post(&mpeg_queue, MPEG_NEED_DATA, 0);
1262 /* Tell the file loading code that we want to start playing
1263 as soon as we have some data */
1264 play_pending = true;
1265 play_pending_track_change = true;
1267 update_playlist();
1268 current_track_counter++;
1269 break;
1271 case MPEG_STOP:
1272 DEBUGF("MPEG_STOP\n");
1273 is_playing = false;
1274 paused = false;
1276 if (playing)
1277 playlist_update_resume_info(audio_current_track());
1279 stop_playing();
1280 mpeg_stop_done = true;
1281 break;
1283 case MPEG_PAUSE:
1284 DEBUGF("MPEG_PAUSE\n");
1285 /* Stop the current stream */
1286 if (playing)
1287 playlist_update_resume_info(audio_current_track());
1288 paused = true;
1289 playing = false;
1290 pause_tick = current_tick;
1291 pause_track = current_track_counter;
1292 mp3_play_pause(false);
1293 break;
1295 case MPEG_RESUME:
1296 DEBUGF("MPEG_RESUME\n");
1297 /* Continue the current stream */
1298 paused = false;
1299 if (!play_pending)
1301 playing = true;
1302 if ( current_track_counter == pause_track )
1303 last_dma_tick += current_tick - pause_tick;
1304 else
1305 last_dma_tick = current_tick;
1306 pause_tick = 0;
1307 mp3_play_pause(true);
1309 break;
1311 case MPEG_NEXT:
1312 DEBUGF("MPEG_NEXT\n");
1313 /* is next track in ram? */
1314 if ( num_tracks_in_memory() > 1 ) {
1315 int unplayed_space_left, unswapped_space_left;
1317 /* stop the current stream */
1318 play_pending = false;
1319 playing = false;
1320 mp3_play_pause(false);
1322 track_change();
1323 audiobuf_read = get_trackdata(0)->mempos;
1324 last_dma_chunk_size = MIN(0x2000, get_unplayed_space_current_song());
1325 mp3_play_data(audiobuf + audiobuf_read, last_dma_chunk_size, transfer_end);
1326 dma_underrun = false;
1327 last_dma_tick = current_tick;
1329 unplayed_space_left = get_unplayed_space();
1330 unswapped_space_left = get_unswapped_space();
1332 /* should we start reading more data? */
1333 if(!filling && (unplayed_space_left < low_watermark)) {
1334 filling = true;
1335 queue_post(&mpeg_queue, MPEG_NEED_DATA, GENERATE_UNBUFFER_EVENTS);
1336 play_pending = true;
1337 } else if(unswapped_space_left &&
1338 unswapped_space_left > unplayed_space_left) {
1339 /* Stop swapping the data from the previous file */
1340 audiobuf_swapwrite = audiobuf_read;
1341 play_pending = true;
1342 } else {
1343 playing = true;
1344 if (!paused)
1345 mp3_play_pause(true);
1348 else {
1349 if (!playlist_check(1))
1350 break;
1352 /* stop the current stream */
1353 end_current_track();
1355 if (new_file(1) < 0) {
1356 DEBUGF("No more files to play\n");
1357 filling = false;
1359 check_playlist_end(1);
1360 current_track_counter++;
1361 } else {
1362 /* Make it read more data */
1363 filling = true;
1364 queue_post(&mpeg_queue, MPEG_NEED_DATA, 0);
1366 /* Tell the file loading code that we want
1367 to start playing as soon as we have some data */
1368 play_pending = true;
1369 play_pending_track_change = true;
1371 update_playlist();
1372 current_track_counter++;
1375 break;
1377 case MPEG_PREV: {
1378 DEBUGF("MPEG_PREV\n");
1380 if (!playlist_check(-1))
1381 break;
1383 /* stop the current stream */
1384 end_current_track();
1386 /* Open the next file */
1387 if (new_file(-1) < 0) {
1388 DEBUGF("No more files to play\n");
1389 filling = false;
1391 check_playlist_end(-1);
1392 current_track_counter++;
1393 } else {
1394 /* Make it read more data */
1395 filling = true;
1396 queue_post(&mpeg_queue, MPEG_NEED_DATA, 0);
1398 /* Tell the file loading code that we want to
1399 start playing as soon as we have some data */
1400 play_pending = true;
1401 play_pending_track_change = true;
1403 update_playlist();
1404 current_track_counter++;
1406 break;
1409 case MPEG_FF_REWIND: {
1410 struct mp3entry *id3 = audio_current_track();
1411 unsigned int oldtime = id3->elapsed;
1412 unsigned int newtime = (unsigned int)ev.data;
1413 int curpos, newpos, diffpos;
1414 DEBUGF("MPEG_FF_REWIND\n");
1416 id3->elapsed = newtime;
1418 newpos = audio_get_file_pos();
1419 if(newpos < 0)
1421 id3->elapsed = oldtime;
1422 break;
1425 if (mpeg_file >= 0)
1426 curpos = lseek(mpeg_file, 0, SEEK_CUR);
1427 else
1428 curpos = id3->filesize;
1430 if (num_tracks_in_memory() > 1)
1432 /* We have started loading other tracks that need to be
1433 accounted for */
1434 struct trackdata *track;
1435 int i = 0;
1437 while((track = get_trackdata(i++)))
1439 curpos += track->id3.filesize;
1443 diffpos = curpos - newpos;
1445 if(!filling && diffpos >= 0 && diffpos < audiobuflen)
1447 int unplayed_space_left, unswapped_space_left;
1449 /* We are changing to a position that's already in
1450 memory, so we just move the DMA read pointer. */
1451 audiobuf_read = audiobuf_write - diffpos;
1452 if (audiobuf_read < 0)
1454 audiobuf_read += audiobuflen;
1457 unplayed_space_left = get_unplayed_space();
1458 unswapped_space_left = get_unswapped_space();
1460 /* If unswapped_space_left is larger than
1461 unplayed_space_left, it means that the swapwrite pointer
1462 hasn't yet advanced up to the new location of the read
1463 pointer. We just move it, there is no need to swap
1464 data that won't be played anyway. */
1466 if (unswapped_space_left > unplayed_space_left)
1468 DEBUGF("Moved swapwrite\n");
1469 audiobuf_swapwrite = audiobuf_read;
1470 play_pending = true;
1473 if (mpeg_file>=0 && unplayed_space_left < low_watermark)
1475 /* We need to load more data before starting */
1476 filling = true;
1477 queue_post(&mpeg_queue, MPEG_NEED_DATA, GENERATE_UNBUFFER_EVENTS);
1478 play_pending = true;
1480 else
1482 /* resume will start at new position */
1483 last_dma_chunk_size =
1484 MIN(0x2000, get_unplayed_space_current_song());
1485 mp3_play_data(audiobuf + audiobuf_read,
1486 last_dma_chunk_size, transfer_end);
1487 dma_underrun = false;
1490 else
1492 /* Move to the new position in the file and start
1493 loading data */
1494 reset_mp3_buffer();
1496 if (num_tracks_in_memory() > 1)
1498 /* We have to reload the current track */
1499 close(mpeg_file);
1500 remove_all_non_current_tags();
1501 generate_unbuffer_events();
1502 mpeg_file = -1;
1505 if (mpeg_file < 0)
1507 mpeg_file = open(id3->path, O_RDONLY);
1508 if (mpeg_file < 0)
1510 id3->elapsed = oldtime;
1511 break;
1515 if(-1 == lseek(mpeg_file, newpos, SEEK_SET))
1517 id3->elapsed = oldtime;
1518 break;
1521 filling = true;
1522 queue_post(&mpeg_queue, MPEG_NEED_DATA, 0);
1524 /* Tell the file loading code that we want to start playing
1525 as soon as we have some data */
1526 play_pending = true;
1529 id3->offset = newpos;
1531 break;
1534 case MPEG_FLUSH_RELOAD: {
1535 int numtracks = num_tracks_in_memory();
1536 bool reload_track = false;
1538 if (numtracks > 1)
1540 /* Reset the buffer */
1541 audiobuf_write = get_trackdata(1)->mempos;
1543 /* Reset swapwrite unless we're still swapping current
1544 track */
1545 if (get_unplayed_space() <= get_playable_space())
1546 audiobuf_swapwrite = audiobuf_write;
1548 close(mpeg_file);
1549 remove_all_non_current_tags();
1550 generate_unbuffer_events();
1551 mpeg_file = -1;
1552 reload_track = true;
1554 else if (numtracks == 1 && mpeg_file < 0)
1556 reload_track = true;
1559 if(reload_track && new_file(1) >= 0)
1561 /* Tell ourselves that we want more data */
1562 filling = true;
1563 queue_post(&mpeg_queue, MPEG_NEED_DATA, 0);
1566 break;
1569 case MPEG_NEED_DATA:
1570 free_space_left = audiobuf_read - audiobuf_write;
1572 /* We interpret 0 as "empty buffer" */
1573 if(free_space_left <= 0)
1574 free_space_left += audiobuflen;
1576 unplayed_space_left = audiobuflen - free_space_left;
1578 /* Make sure that we don't fill the entire buffer */
1579 free_space_left -= MPEG_HIGH_WATER;
1581 if (ev.data == GENERATE_UNBUFFER_EVENTS)
1582 generate_unbuffer_events();
1584 /* do we have any more buffer space to fill? */
1585 if(free_space_left <= 0)
1587 DEBUGF("0\n");
1588 filling = false;
1589 generate_postbuffer_events();
1590 ata_sleep();
1591 break;
1594 /* Read small chunks while we are below the low water mark */
1595 if(unplayed_space_left < low_watermark)
1596 amount_to_read = MIN(MPEG_LOW_WATER_CHUNKSIZE,
1597 free_space_left);
1598 else
1599 amount_to_read = free_space_left;
1601 /* Don't read more than until the end of the buffer */
1602 amount_to_read = MIN(audiobuflen - audiobuf_write,
1603 amount_to_read);
1604 #ifdef HAVE_MMC /* MMC is slow, so don't read too large chunks */
1605 amount_to_read = MIN(0x40000, amount_to_read);
1606 #elif MEM == 8
1607 amount_to_read = MIN(0x100000, amount_to_read);
1608 #endif
1610 /* Read as much mpeg data as we can fit in the buffer */
1611 if(mpeg_file >= 0)
1613 DEBUGF("R\n");
1614 t1 = current_tick;
1615 len = read(mpeg_file, audiobuf + audiobuf_write,
1616 amount_to_read);
1617 if(len > 0)
1619 t2 = current_tick;
1620 DEBUGF("time: %d\n", t2 - t1);
1621 DEBUGF("R: %x\n", len);
1623 /* Now make sure that we don't feed the MAS with ID3V1
1624 data */
1625 if (len < amount_to_read)
1627 int i;
1628 static const unsigned char tag[] = "TAG";
1629 int taglen = 128;
1630 int tagptr = audiobuf_write + len - 128;
1632 /* Really rare case: entire potential tag wasn't
1633 read in this call AND audiobuf_write < 128 */
1634 if (tagptr < 0)
1635 tagptr += audiobuflen;
1637 for(i = 0;i < 3;i++)
1639 if(tagptr >= audiobuflen)
1640 tagptr -= audiobuflen;
1642 if(audiobuf[tagptr] != tag[i])
1644 taglen = 0;
1645 break;
1648 tagptr++;
1651 if(taglen)
1653 /* Skip id3v1 tag */
1654 DEBUGF("Skipping ID3v1 tag\n");
1655 len -= taglen;
1657 /* In the very rare case when the entire tag
1658 wasn't read in this read() len will be < 0.
1659 Take care of this when changing the write
1660 pointer. */
1664 audiobuf_write += len;
1666 if (audiobuf_write < 0)
1667 audiobuf_write += audiobuflen;
1669 if(audiobuf_write >= audiobuflen)
1671 audiobuf_write = 0;
1672 DEBUGF("W\n");
1675 /* Tell ourselves that we want more data */
1676 queue_post(&mpeg_queue, MPEG_NEED_DATA, 0);
1678 else
1680 if(len < 0)
1682 DEBUGF("MPEG read error\n");
1685 close(mpeg_file);
1686 mpeg_file = -1;
1688 if(new_file(1) < 0)
1690 /* No more data to play */
1691 DEBUGF("No more files to play\n");
1692 filling = false;
1694 else
1696 /* Tell ourselves that we want more data */
1697 queue_post(&mpeg_queue, MPEG_NEED_DATA, 0);
1701 break;
1703 case MPEG_TRACK_CHANGE:
1704 track_change();
1705 break;
1707 #ifndef USB_NONE
1708 case SYS_USB_CONNECTED:
1709 is_playing = false;
1710 paused = false;
1711 stop_playing();
1713 /* Tell the USB thread that we are safe */
1714 DEBUGF("mpeg_thread got SYS_USB_CONNECTED\n");
1715 usb_acknowledge(SYS_USB_CONNECTED_ACK);
1717 /* Wait until the USB cable is extracted again */
1718 usb_wait_for_disconnect(&mpeg_queue);
1719 break;
1720 #endif /* !USB_NONE */
1722 #if CONFIG_CODEC == MAS3587F
1723 case MPEG_INIT_RECORDING:
1724 init_recording();
1725 init_recording_done = true;
1726 break;
1727 #endif /* CONFIG_CODEC == MAS3587F */
1729 case SYS_TIMEOUT:
1730 if (playing)
1731 playlist_update_resume_info(audio_current_track());
1732 break;
1734 #if CONFIG_CODEC == MAS3587F
1736 else
1738 queue_wait(&mpeg_queue, &ev);
1739 switch(ev.id)
1741 case MPEG_RECORD:
1742 if (is_prerecording)
1744 int startpos;
1746 /* Go back prerecord_count seconds in the buffer */
1747 startpos = prerecord_index - prerecord_count;
1748 if(startpos < 0)
1749 startpos += prerecording_max_seconds;
1751 /* Read the position data from the prerecord buffer */
1752 frame_count_start = prerecord_buffer[startpos].framecount;
1753 startpos = prerecord_buffer[startpos].mempos;
1755 DEBUGF("Start looking at address %x (%x)\n",
1756 audiobuf+startpos, startpos);
1758 saved_header = mpeg_get_last_header();
1760 mem_find_next_frame(startpos, &offset, 1800,
1761 saved_header);
1763 audiobuf_read = startpos + offset;
1764 if(audiobuf_read >= audiobuflen)
1765 audiobuf_read -= audiobuflen;
1767 DEBUGF("New audiobuf_read address: %x (%x)\n",
1768 audiobuf+audiobuf_read, audiobuf_read);
1770 level = disable_irq_save();
1771 num_rec_bytes = get_unsaved_space();
1772 restore_irq(level);
1774 else
1776 frame_count_start = 0;
1777 num_rec_bytes = 0;
1778 audiobuf_read = MPEG_RESERVED_HEADER_SPACE;
1779 audiobuf_write = MPEG_RESERVED_HEADER_SPACE;
1782 prepend_header();
1783 DEBUGF("Recording...\n");
1784 start_recording();
1786 /* Wait until at least one frame is encoded and get the
1787 frame header, for later use by the Xing header
1788 generation */
1789 sleep(HZ/5);
1790 saved_header = mpeg_get_last_header();
1792 /* delayed until buffer is saved, don't open yet */
1793 strcpy(delayed_filename, recording_filename);
1794 mpeg_file = -1;
1796 break;
1798 case MPEG_STOP:
1799 DEBUGF("MPEG_STOP\n");
1801 stop_recording();
1803 /* Save the remaining data in the buffer */
1804 save_endpos = audiobuf_write;
1805 saving_status = STOP_RECORDING;
1806 queue_post(&mpeg_queue, MPEG_SAVE_DATA, 0);
1807 break;
1809 case MPEG_STOP_DONE:
1810 DEBUGF("MPEG_STOP_DONE\n");
1812 if (mpeg_file >= 0)
1813 close(mpeg_file);
1814 mpeg_file = -1;
1816 update_header();
1817 #ifdef DEBUG1
1819 int i;
1820 for(i = 0;i < 512;i++)
1822 DEBUGF("%d - %d us (%d bytes)\n",
1823 timing_info[i*2],
1824 (timing_info[i*2+1] & 0xffff) *
1825 10000 / 13824,
1826 timing_info[i*2+1] >> 16);
1829 #endif /* DEBUG1 */
1831 if (prerecording)
1833 start_prerecording();
1835 mpeg_stop_done = true;
1836 break;
1838 case MPEG_NEW_FILE:
1839 /* Bail out when a more important save is happening */
1840 if (saving_status > NEW_FILE)
1841 break;
1843 /* Make sure we have at least one complete frame
1844 in the buffer. If we haven't recorded a single
1845 frame within 200ms, the MAS is probably not recording
1846 anything, and we bail out. */
1847 amount_to_save = get_unsaved_space();
1848 if (amount_to_save < 1800)
1850 sleep(HZ/5);
1851 amount_to_save = get_unsaved_space();
1854 mas_readmem(MAS_BANK_D0, MAS_D0_MPEG_FRAME_COUNT,
1855 &frame_count_end, 1);
1857 last_rec_time = current_tick - record_start_time;
1858 record_start_time = current_tick;
1859 if (paused)
1860 pause_start_time = record_start_time;
1862 /* capture all values at one point */
1863 level = disable_irq_save();
1864 save_endpos = audiobuf_write;
1865 last_rec_bytes = num_rec_bytes;
1866 num_rec_bytes = 0;
1867 restore_irq(level);
1869 if (amount_to_save >= 1800)
1871 /* Now find a frame boundary to split at */
1872 save_endpos -= 1800;
1873 if (save_endpos < 0)
1874 save_endpos += audiobuflen;
1876 rc = mem_find_next_frame(save_endpos, &offset, 1800,
1877 saved_header);
1878 if (!rc) /* No header found, save whole buffer */
1879 offset = 1800;
1881 save_endpos += offset;
1882 if (save_endpos >= audiobuflen)
1883 save_endpos -= audiobuflen;
1885 last_rec_bytes += offset - 1800;
1886 level = disable_irq_save();
1887 num_rec_bytes += 1800 - offset;
1888 restore_irq(level);
1891 saving_status = NEW_FILE;
1892 queue_post(&mpeg_queue, MPEG_SAVE_DATA, 0);
1893 break;
1895 case MPEG_SAVE_DATA:
1896 if (saving_status == BUFFER_FULL)
1897 save_endpos = audiobuf_write;
1899 if (mpeg_file < 0) /* delayed file open */
1901 mpeg_file = open(delayed_filename, O_WRONLY|O_CREAT);
1903 if (mpeg_file < 0)
1904 panicf("recfile: %d", mpeg_file);
1907 amount_to_save = save_endpos - audiobuf_read;
1908 if (amount_to_save < 0)
1909 amount_to_save += audiobuflen;
1911 amount_to_save = MIN(amount_to_save,
1912 audiobuflen - audiobuf_read);
1913 #ifdef HAVE_MMC /* MMC is slow, so don't save too large chunks at once */
1914 amount_to_save = MIN(0x40000, amount_to_save);
1915 #elif MEM == 8
1916 amount_to_save = MIN(0x100000, amount_to_save);
1917 #endif
1918 rc = write(mpeg_file, audiobuf + audiobuf_read,
1919 amount_to_save);
1920 if (rc < 0)
1922 if (errno == ENOSPC)
1924 mpeg_errno = AUDIOERR_DISK_FULL;
1925 stop_recording();
1926 queue_post(&mpeg_queue, MPEG_STOP_DONE, 0);
1927 /* will close the file */
1928 break;
1930 else
1931 panicf("rec wrt: %d", rc);
1934 audiobuf_read += amount_to_save;
1935 if (audiobuf_read >= audiobuflen)
1936 audiobuf_read = 0;
1938 if (audiobuf_read == save_endpos) /* all saved */
1940 switch (saving_status)
1942 case BUFFER_FULL:
1943 rc = fsync(mpeg_file);
1944 if (rc < 0)
1945 panicf("rec fls: %d", rc);
1946 ata_sleep();
1947 break;
1949 case NEW_FILE:
1950 /* Close the current file */
1951 rc = close(mpeg_file);
1952 if (rc < 0)
1953 panicf("rec cls: %d", rc);
1954 mpeg_file = -1;
1955 update_header();
1956 ata_sleep();
1958 /* copy new filename */
1959 strcpy(delayed_filename, recording_filename);
1960 prepend_header();
1961 frame_count_start = frame_count_end;
1962 break;
1964 case STOP_RECORDING:
1965 queue_post(&mpeg_queue, MPEG_STOP_DONE, 0);
1966 /* will close the file */
1967 break;
1969 default:
1970 break;
1972 saving_status = NOT_SAVING;
1974 else /* tell ourselves to save the next chunk */
1975 queue_post(&mpeg_queue, MPEG_SAVE_DATA, 0);
1977 break;
1979 case MPEG_PRERECORDING_TICK:
1980 if(!is_prerecording)
1981 break;
1983 /* Store the write pointer every second */
1984 prerecord_buffer[prerecord_index].mempos = audiobuf_write;
1985 mas_readmem(MAS_BANK_D0, MAS_D0_MPEG_FRAME_COUNT,
1986 &prerecord_buffer[prerecord_index].framecount, 1);
1988 /* Wrap if necessary */
1989 if(++prerecord_index == prerecording_max_seconds)
1990 prerecord_index = 0;
1992 /* Update the number of seconds recorded */
1993 if(prerecord_count < prerecording_max_seconds)
1994 prerecord_count++;
1995 break;
1997 case MPEG_INIT_PLAYBACK:
1998 /* Stop the prerecording */
1999 stop_recording();
2000 reset_mp3_buffer();
2001 mp3_play_init();
2002 init_playback_done = true;
2003 break;
2005 case MPEG_PAUSE_RECORDING:
2006 pause_recording();
2007 break;
2009 case MPEG_RESUME_RECORDING:
2010 resume_recording();
2011 break;
2013 case SYS_USB_CONNECTED:
2014 /* We can safely go to USB mode if no recording
2015 is taking place */
2016 if((!is_recording || is_prerecording) && mpeg_stop_done)
2018 /* Even if we aren't recording, we still call this
2019 function, to put the MAS in monitoring mode,
2020 to save power. */
2021 stop_recording();
2023 /* Tell the USB thread that we are safe */
2024 DEBUGF("mpeg_thread got SYS_USB_CONNECTED\n");
2025 usb_acknowledge(SYS_USB_CONNECTED_ACK);
2027 /* Wait until the USB cable is extracted again */
2028 usb_wait_for_disconnect(&mpeg_queue);
2030 break;
2033 #endif /* CONFIG_CODEC == MAS3587F */
2036 #endif /* !SIMULATOR */
2038 struct mp3entry* audio_current_track()
2040 #ifdef SIMULATOR
2041 return &taginfo;
2042 #else /* !SIMULATOR */
2043 if(num_tracks_in_memory())
2044 return &get_trackdata(0)->id3;
2045 else
2046 return NULL;
2047 #endif /* !SIMULATOR */
2050 struct mp3entry* audio_next_track()
2052 #ifdef SIMULATOR
2053 return &taginfo;
2054 #else /* !SIMULATOR */
2055 if(num_tracks_in_memory() > 1)
2056 return &get_trackdata(1)->id3;
2057 else
2058 return NULL;
2059 #endif /* !SIMULATOR */
2062 bool audio_has_changed_track(void)
2064 if(last_track_counter != current_track_counter)
2066 last_track_counter = current_track_counter;
2067 return true;
2069 return false;
2072 #if CONFIG_CODEC == MAS3587F
2073 #ifndef SIMULATOR
2074 void audio_init_playback(void)
2076 init_playback_done = false;
2077 queue_post(&mpeg_queue, MPEG_INIT_PLAYBACK, 0);
2079 while(!init_playback_done)
2080 sleep(1);
2084 /****************************************************************************
2085 * Recording functions
2086 ***************************************************************************/
2087 void audio_init_recording(unsigned int buffer_offset)
2089 buffer_offset = buffer_offset;
2090 init_recording_done = false;
2091 queue_post(&mpeg_queue, MPEG_INIT_RECORDING, 0);
2093 while(!init_recording_done)
2094 sleep(1);
2097 static void init_recording(void)
2099 unsigned long val;
2100 int rc;
2102 /* Disable IRQ6 */
2103 IPRB &= 0xff0f;
2105 stop_playing();
2106 is_playing = false;
2107 paused = false;
2109 /* Init the recording variables */
2110 is_recording = false;
2111 is_prerecording = false;
2113 mpeg_stop_done = true;
2115 mas_reset();
2117 /* Enable the audio CODEC and the DSP core, max analog voltage range */
2118 rc = mas_direct_config_write(MAS_CONTROL, 0x8c00);
2119 if(rc < 0)
2120 panicf("mas_ctrl_w: %d", rc);
2122 /* Stop the current application */
2123 val = 0;
2124 mas_writemem(MAS_BANK_D0, MAS_D0_APP_SELECT, &val, 1);
2127 mas_readmem(MAS_BANK_D0, MAS_D0_APP_RUNNING, &val, 1);
2128 } while(val);
2130 /* Perform black magic as described by the data sheet */
2131 if((mas_version_code & 0x0fff) == 0x0102)
2133 DEBUGF("Performing MAS black magic for B2 version\n");
2134 mas_writereg(0xa3, 0x98);
2135 mas_writereg(0x94, 0xfffff);
2136 val = 0;
2137 mas_writemem(MAS_BANK_D1, 0, &val, 1);
2138 mas_writereg(0xa3, 0x90);
2141 /* Enable A/D Converters */
2142 shadow_codec_reg0 = 0xcccd;
2143 mas_codec_writereg(0x0, shadow_codec_reg0);
2145 /* Copy left channel to right (mono mode) */
2146 mas_codec_writereg(8, 0x8000);
2148 /* ADC scale 0%, DSP scale 100%
2149 We use the DSP output for monitoring, because it works with all
2150 sources including S/PDIF */
2151 mas_codec_writereg(6, 0x0000);
2152 mas_codec_writereg(7, 0x4000);
2154 /* No mute */
2155 shadow_soft_mute = 0;
2156 mas_writemem(MAS_BANK_D0, MAS_D0_SOFT_MUTE, &shadow_soft_mute, 1);
2158 #ifdef HAVE_SPDIF_OUT
2159 val = 0x09; /* Disable SDO and SDI, low impedance S/PDIF outputs */
2160 #else
2161 val = 0x2d; /* Disable SDO and SDI, disable S/PDIF output */
2162 #endif
2163 mas_writemem(MAS_BANK_D0, MAS_D0_INTERFACE_CONTROL, &val, 1);
2165 /* Set Demand mode, monitoring OFF and validate all settings */
2166 shadow_io_control_main = 0x125;
2167 mas_writemem(MAS_BANK_D0, MAS_D0_IO_CONTROL_MAIN, &shadow_io_control_main, 1);
2169 /* Start the encoder application */
2170 val = 0x40;
2171 mas_writemem(MAS_BANK_D0, MAS_D0_APP_SELECT, &val, 1);
2174 mas_readmem(MAS_BANK_D0, MAS_D0_APP_RUNNING, &val, 1);
2175 } while(!(val & 0x40));
2177 /* We have started the recording application with monitoring OFF.
2178 This is because we want to record at least one frame to fill the DMA
2179 buffer, because the silly MAS will not negate EOD until at least one
2180 DMA transfer has taken place.
2181 Now let's wait for some data to be encoded. */
2182 sleep(HZ/5);
2184 /* Now set it to Monitoring mode as default, saves power */
2185 shadow_io_control_main = 0x525;
2186 mas_writemem(MAS_BANK_D0, MAS_D0_IO_CONTROL_MAIN, &shadow_io_control_main, 1);
2188 /* Wait until the DSP has accepted the settings */
2191 mas_readmem(MAS_BANK_D0, MAS_D0_IO_CONTROL_MAIN, &val,1);
2192 } while(val & 1);
2194 drain_dma_buffer();
2195 mpeg_mode = MPEG_ENCODER;
2197 DEBUGF("MAS Recording application started\n");
2199 /* At this point, all settings are the reset MAS defaults, next thing is to
2200 call mpeg_set_recording_options(). */
2203 void audio_record(const char *filename)
2205 mpeg_errno = 0;
2207 strncpy(recording_filename, filename, MAX_PATH - 1);
2208 recording_filename[MAX_PATH - 1] = 0;
2210 queue_post(&mpeg_queue, MPEG_RECORD, 0);
2213 void audio_pause_recording(void)
2215 queue_post(&mpeg_queue, MPEG_PAUSE_RECORDING, 0);
2218 void audio_resume_recording(void)
2220 queue_post(&mpeg_queue, MPEG_RESUME_RECORDING, 0);
2223 static void prepend_header(void)
2225 int startpos;
2226 unsigned i;
2228 /* Make room for header */
2229 audiobuf_read -= MPEG_RESERVED_HEADER_SPACE;
2230 if(audiobuf_read < 0)
2232 /* Clear the bottom half */
2233 memset(audiobuf, 0, audiobuf_read + MPEG_RESERVED_HEADER_SPACE);
2235 /* And the top half */
2236 audiobuf_read += audiobuflen;
2237 memset(audiobuf + audiobuf_read, 0, audiobuflen - audiobuf_read);
2239 else
2241 memset(audiobuf + audiobuf_read, 0, MPEG_RESERVED_HEADER_SPACE);
2243 /* Copy the empty ID3 header */
2244 startpos = audiobuf_read;
2245 for(i = 0; i < sizeof(empty_id3_header); i++)
2247 audiobuf[startpos++] = empty_id3_header[i];
2248 if(startpos == audiobuflen)
2249 startpos = 0;
2253 static void update_header(void)
2255 int fd, framelen;
2256 unsigned long frames;
2258 if (last_rec_bytes > 0)
2260 /* Create the Xing header */
2261 fd = open(delayed_filename, O_RDWR);
2262 if (fd < 0)
2263 panicf("rec upd: %d (%s)", fd, recording_filename);
2265 frames = frame_count_end - frame_count_start;
2266 /* If the number of recorded frames has reached 0x7ffff,
2267 we can no longer trust it */
2268 if (frame_count_end == 0x7ffff)
2269 frames = 0;
2271 /* saved_header is saved right before stopping the MAS */
2272 framelen = create_xing_header(fd, 0, last_rec_bytes, xing_buffer,
2273 frames, last_rec_time * (1000/HZ),
2274 saved_header, NULL, false);
2276 lseek(fd, MPEG_RESERVED_HEADER_SPACE - framelen, SEEK_SET);
2277 write(fd, xing_buffer, framelen);
2278 close(fd);
2282 static void start_prerecording(void)
2284 unsigned long val;
2286 DEBUGF("Starting prerecording\n");
2288 prerecord_index = 0;
2289 prerecord_count = 0;
2290 prerecord_timeout = current_tick + HZ;
2291 memset(prerecord_buffer, 0, sizeof(prerecord_buffer));
2292 reset_mp3_buffer();
2294 is_prerecording = true;
2296 /* Stop monitoring and start the encoder */
2297 shadow_io_control_main &= ~(1 << 10);
2298 mas_writemem(MAS_BANK_D0, MAS_D0_IO_CONTROL_MAIN, &shadow_io_control_main, 1);
2299 DEBUGF("mas_writemem(MAS_BANK_D0, IO_CONTROL_MAIN, %x)\n", shadow_io_control_main);
2301 /* Wait until the DSP has accepted the settings */
2304 mas_readmem(MAS_BANK_D0, MAS_D0_IO_CONTROL_MAIN, &val,1);
2305 } while(val & 1);
2307 is_recording = true;
2308 saving_status = NOT_SAVING;
2310 demand_irq_enable(true);
2313 static void start_recording(void)
2315 unsigned long val;
2317 if(is_prerecording)
2319 /* This will make the IRQ handler start recording
2320 for real, i.e send MPEG_SAVE_DATA messages when
2321 the buffer is full */
2322 is_prerecording = false;
2324 else
2326 /* If prerecording is off, we need to stop the monitoring
2327 and start the encoder */
2328 shadow_io_control_main &= ~(1 << 10);
2329 mas_writemem(MAS_BANK_D0, MAS_D0_IO_CONTROL_MAIN, &shadow_io_control_main, 1);
2330 DEBUGF("mas_writemem(MAS_BANK_D0, IO_CONTROL_MAIN, %x)\n", shadow_io_control_main);
2332 /* Wait until the DSP has accepted the settings */
2335 mas_readmem(MAS_BANK_D0, MAS_D0_IO_CONTROL_MAIN, &val,1);
2336 } while(val & 1);
2339 is_recording = true;
2340 saving_status = NOT_SAVING;
2341 paused = false;
2343 /* Store the current time */
2344 if(prerecording)
2345 record_start_time = current_tick - prerecord_count * HZ;
2346 else
2347 record_start_time = current_tick;
2349 pause_start_time = 0;
2351 demand_irq_enable(true);
2354 static void pause_recording(void)
2356 pause_start_time = current_tick;
2358 /* Set the pause bit */
2359 shadow_soft_mute |= 2;
2360 mas_writemem(MAS_BANK_D0, MAS_D0_SOFT_MUTE, &shadow_soft_mute, 1);
2362 paused = true;
2365 static void resume_recording(void)
2367 paused = false;
2369 /* Clear the pause bit */
2370 shadow_soft_mute &= ~2;
2371 mas_writemem(MAS_BANK_D0, MAS_D0_SOFT_MUTE, &shadow_soft_mute, 1);
2373 /* Compensate for the time we have been paused */
2374 if(pause_start_time)
2376 record_start_time =
2377 current_tick - (pause_start_time - record_start_time);
2378 pause_start_time = 0;
2382 static void stop_recording(void)
2384 unsigned long val;
2386 /* Let it finish the last frame */
2387 if(!paused)
2388 pause_recording();
2389 sleep(HZ/5);
2391 demand_irq_enable(false);
2393 is_recording = false;
2394 is_prerecording = false;
2396 last_rec_bytes = num_rec_bytes;
2397 mas_readmem(MAS_BANK_D0, MAS_D0_MPEG_FRAME_COUNT, &frame_count_end, 1);
2398 last_rec_time = current_tick - record_start_time;
2400 /* Start monitoring */
2401 shadow_io_control_main |= (1 << 10);
2402 mas_writemem(MAS_BANK_D0, MAS_D0_IO_CONTROL_MAIN, &shadow_io_control_main, 1);
2403 DEBUGF("mas_writemem(MAS_BANK_D0, IO_CONTROL_MAIN, %x)\n", shadow_io_control_main);
2405 /* Wait until the DSP has accepted the settings */
2408 mas_readmem(MAS_BANK_D0, MAS_D0_IO_CONTROL_MAIN, &val,1);
2409 } while(val & 1);
2411 resume_recording();
2414 void audio_set_recording_options(struct audio_recording_options *options)
2416 bool is_mpeg1;
2418 is_mpeg1 = (options->rec_frequency < 3)?true:false;
2420 rec_version_index = is_mpeg1?3:2;
2421 rec_frequency_index = options->rec_frequency % 3;
2423 shadow_encoder_control = (options->rec_quality << 17) |
2424 (rec_frequency_index << 10) |
2425 ((is_mpeg1?1:0) << 9) |
2426 (((options->rec_channels * 2 + 1) & 3) << 6) |
2427 (1 << 5) /* MS-stereo */ |
2428 (1 << 2) /* Is an original */;
2429 mas_writemem(MAS_BANK_D0, MAS_D0_ENCODER_CONTROL, &shadow_encoder_control,1);
2431 DEBUGF("mas_writemem(MAS_BANK_D0, ENCODER_CONTROL, %x)\n", shadow_encoder_control);
2433 shadow_soft_mute = options->rec_editable?4:0;
2434 mas_writemem(MAS_BANK_D0, MAS_D0_SOFT_MUTE, &shadow_soft_mute,1);
2436 DEBUGF("mas_writemem(MAS_BANK_D0, SOFT_MUTE, %x)\n", shadow_soft_mute);
2438 shadow_io_control_main = ((1 << 10) | /* Monitoring ON */
2439 ((options->rec_source < 2)?1:2) << 8) | /* Input select */
2440 (1 << 5) | /* SDO strobe invert */
2441 ((is_mpeg1?0:1) << 3) |
2442 (1 << 2) | /* Inverted SIBC clock signal */
2443 1; /* Validate */
2444 mas_writemem(MAS_BANK_D0, MAS_D0_IO_CONTROL_MAIN, &shadow_io_control_main,1);
2446 DEBUGF("mas_writemem(MAS_BANK_D0, IO_CONTROL_MAIN, %x)\n", shadow_io_control_main);
2448 if(options->rec_source == AUDIO_SRC_MIC)
2450 /* Copy left channel to right (mono mode) */
2451 mas_codec_writereg(8, 0x8000);
2453 else
2455 /* Stereo input mode */
2456 mas_codec_writereg(8, 0);
2459 prerecording_max_seconds = options->rec_prerecord_time;
2460 if(prerecording_max_seconds)
2462 prerecording = true;
2463 start_prerecording();
2465 else
2467 prerecording = false;
2468 is_prerecording = false;
2469 is_recording = false;
2473 /* If use_mic is true, the left gain is used */
2474 void audio_set_recording_gain(int left, int right, int type)
2476 /* Enable both left and right A/D */
2477 shadow_codec_reg0 = (left << 12) |
2478 (right << 8) |
2479 (left << 4) |
2480 (type==AUDIO_GAIN_MIC?0x0008:0) | /* Connect left A/D to mic */
2481 0x0007;
2482 mas_codec_writereg(0x0, shadow_codec_reg0);
2485 #if CONFIG_TUNER & S1A0903X01
2486 /* Get the (unpitched) MAS PLL frequency, for avoiding FM interference with the
2487 * Samsung tuner. Zero means unknown. Currently handles recording from analog
2488 * input only. */
2489 int mpeg_get_mas_pllfreq(void)
2491 if (mpeg_mode != MPEG_ENCODER)
2492 return 0;
2494 if (rec_frequency_index == 0) /* 44.1 kHz / 22.05 kHz */
2495 return 22579000;
2496 else
2497 return 24576000;
2499 #endif /* CONFIG_TUNER & S1A0903X01 */
2501 /* try to make some kind of beep, also in recording mode */
2502 void audio_beep(int duration)
2504 long starttick = current_tick;
2506 { /* toggle bit 0 of codec register 0, toggling the DAC off & on.
2507 * While this is still audible even without an external signal,
2508 * it doesn't affect the (pre-)recording. */
2509 mas_codec_writereg(0, shadow_codec_reg0 ^ 1);
2510 mas_codec_writereg(0, shadow_codec_reg0);
2511 yield();
2513 while (current_tick - starttick < duration);
2516 void audio_new_file(const char *filename)
2518 mpeg_errno = 0;
2520 strncpy(recording_filename, filename, MAX_PATH - 1);
2521 recording_filename[MAX_PATH - 1] = 0;
2523 queue_post(&mpeg_queue, MPEG_NEW_FILE, 0);
2526 unsigned long audio_recorded_time(void)
2528 if(is_prerecording)
2529 return prerecord_count * HZ;
2531 if(is_recording)
2533 if(paused)
2534 return pause_start_time - record_start_time;
2535 else
2536 return current_tick - record_start_time;
2539 return 0;
2542 unsigned long audio_num_recorded_bytes(void)
2544 int num_bytes;
2545 int index;
2547 if(is_recording)
2549 if(is_prerecording)
2551 index = prerecord_index - prerecord_count;
2552 if(index < 0)
2553 index += prerecording_max_seconds;
2555 num_bytes = audiobuf_write - prerecord_buffer[index].mempos;
2556 if(num_bytes < 0)
2557 num_bytes += audiobuflen;
2559 return num_bytes;;
2561 else
2562 return num_rec_bytes;
2564 else
2565 return 0;
2568 #else /* SIMULATOR */
2570 /* dummies coming up */
2572 void audio_init_playback(void)
2574 /* a dummy */
2576 unsigned long audio_recorded_time(void)
2578 /* a dummy */
2579 return 0;
2581 void audio_beep(int duration)
2583 /* a dummy */
2584 (void)duration;
2586 void audio_pause_recording(void)
2588 /* a dummy */
2590 void audio_resume_recording(void)
2592 /* a dummy */
2594 unsigned long audio_num_recorded_bytes(void)
2596 /* a dummy */
2597 return 0;
2599 void audio_record(const char *filename)
2601 /* a dummy */
2602 (void)filename;
2604 void audio_new_file(const char *filename)
2606 /* a dummy */
2607 (void)filename;
2610 void audio_set_recording_gain(int left, int right, int type)
2612 /* a dummy */
2613 (void)left;
2614 (void)right;
2615 (void)type;
2617 void audio_init_recording(unsigned int buffer_offset)
2619 /* a dummy */
2620 (void)buffer_offset;
2622 void audio_set_recording_options(struct audio_recording_options *options)
2624 /* a dummy */
2625 (void)options;
2627 #endif /* SIMULATOR */
2628 #endif /* CONFIG_CODEC == MAS3587F */
2630 void audio_play(long offset)
2632 #ifdef SIMULATOR
2633 char* trackname;
2634 int steps=0;
2636 is_playing = true;
2638 do {
2639 trackname = playlist_peek( steps );
2640 if (!trackname)
2641 break;
2642 if(mp3info(&taginfo, trackname)) {
2643 /* bad mp3, move on */
2644 if(++steps > playlist_amount())
2645 break;
2646 continue;
2648 #ifdef HAVE_MPEG_PLAY
2649 real_mpeg_play(trackname);
2650 #endif
2651 playlist_next(steps);
2652 taginfo.offset = offset;
2653 set_elapsed(&taginfo);
2654 is_playing = true;
2655 playing = true;
2656 break;
2657 } while(1);
2658 #else /* !SIMULATOR */
2659 is_playing = true;
2661 queue_post(&mpeg_queue, MPEG_PLAY, offset);
2662 #endif /* !SIMULATOR */
2664 mpeg_errno = 0;
2667 void audio_stop(void)
2669 #ifndef SIMULATOR
2670 if (playing)
2672 struct trackdata *track = get_trackdata(0);
2673 prev_track_elapsed = track->id3.elapsed;
2675 mpeg_stop_done = false;
2676 queue_post(&mpeg_queue, MPEG_STOP, 0);
2677 while(!mpeg_stop_done)
2678 yield();
2679 #else /* SIMULATOR */
2680 paused = false;
2681 is_playing = false;
2682 playing = false;
2683 #endif /* SIMULATOR */
2686 /* dummy */
2687 void audio_stop_recording(void)
2689 audio_stop();
2692 void audio_pause(void)
2694 #ifndef SIMULATOR
2695 queue_post(&mpeg_queue, MPEG_PAUSE, 0);
2696 #else /* SIMULATOR */
2697 is_playing = true;
2698 playing = false;
2699 paused = true;
2700 #endif /* SIMULATOR */
2703 void audio_resume(void)
2705 #ifndef SIMULATOR
2706 queue_post(&mpeg_queue, MPEG_RESUME, 0);
2707 #else /* SIMULATOR */
2708 is_playing = true;
2709 playing = true;
2710 paused = false;
2711 #endif /* SIMULATOR */
2714 void audio_next(void)
2716 #ifndef SIMULATOR
2717 queue_remove_from_head(&mpeg_queue, MPEG_NEED_DATA);
2718 queue_post(&mpeg_queue, MPEG_NEXT, 0);
2719 #else /* SIMULATOR */
2720 char* file;
2721 int steps = 1;
2722 int index;
2724 do {
2725 file = playlist_peek(steps);
2726 if(!file)
2727 break;
2728 if(mp3info(&taginfo, file)) {
2729 if(++steps > playlist_amount())
2730 break;
2731 continue;
2733 index = playlist_next(steps);
2734 taginfo.index = index;
2735 current_track_counter++;
2736 is_playing = true;
2737 playing = true;
2738 break;
2739 } while(1);
2740 #endif /* SIMULATOR */
2743 void audio_prev(void)
2745 #ifndef SIMULATOR
2746 queue_remove_from_head(&mpeg_queue, MPEG_NEED_DATA);
2747 queue_post(&mpeg_queue, MPEG_PREV, 0);
2748 #else /* SIMULATOR */
2749 char* file;
2750 int steps = -1;
2751 int index;
2753 do {
2754 file = playlist_peek(steps);
2755 if(!file)
2756 break;
2757 if(mp3info(&taginfo, file)) {
2758 steps--;
2759 continue;
2761 index = playlist_next(steps);
2762 taginfo.index = index;
2763 current_track_counter++;
2764 is_playing = true;
2765 playing = true;
2766 break;
2767 } while(1);
2768 #endif /* SIMULATOR */
2771 void audio_ff_rewind(long newtime)
2773 #ifndef SIMULATOR
2774 queue_post(&mpeg_queue, MPEG_FF_REWIND, newtime);
2775 #else /* SIMULATOR */
2776 (void)newtime;
2777 #endif /* SIMULATOR */
2780 void audio_flush_and_reload_tracks(void)
2782 #ifndef SIMULATOR
2783 queue_post(&mpeg_queue, MPEG_FLUSH_RELOAD, 0);
2784 #endif /* !SIMULATOR*/
2787 int audio_status(void)
2789 int ret = 0;
2791 if(is_playing)
2792 ret |= AUDIO_STATUS_PLAY;
2794 if(paused)
2795 ret |= AUDIO_STATUS_PAUSE;
2797 #if (CONFIG_CODEC == MAS3587F) && !defined(SIMULATOR)
2798 if(is_recording && !is_prerecording)
2799 ret |= AUDIO_STATUS_RECORD;
2801 if(is_prerecording)
2802 ret |= AUDIO_STATUS_PRERECORD;
2803 #endif /* CONFIG_CODEC == MAS3587F */
2805 if(mpeg_errno)
2806 ret |= AUDIO_STATUS_ERROR;
2808 return ret;
2811 unsigned int audio_error(void)
2813 return mpeg_errno;
2816 void audio_error_clear(void)
2818 mpeg_errno = 0;
2821 #ifdef SIMULATOR
2822 static void mpeg_thread(void)
2824 struct mp3entry* id3;
2825 while ( 1 ) {
2826 if (is_playing) {
2827 id3 = audio_current_track();
2828 if (!paused)
2830 id3->elapsed+=1000;
2831 id3->offset+=1000;
2833 if (id3->elapsed>=id3->length)
2834 audio_next();
2836 sleep(HZ);
2839 #endif /* SIMULATOR */
2841 void audio_init(void)
2843 mpeg_errno = 0;
2845 #ifndef SIMULATOR
2846 audiobuflen = audiobufend - audiobuf;
2847 queue_init(&mpeg_queue, true);
2848 #endif /* !SIMULATOR */
2849 create_thread(mpeg_thread, mpeg_stack,
2850 sizeof(mpeg_stack), 0, mpeg_thread_name
2851 IF_PRIO(, PRIORITY_SYSTEM)
2852 IF_COP(, CPU));
2854 memset(trackdata, sizeof(trackdata), 0);
2856 #if (CONFIG_CODEC == MAS3587F) && !defined(SIMULATOR)
2857 if (HW_MASK & PR_ACTIVE_HIGH)
2858 and_b(~0x08, &PADRH);
2859 else
2860 or_b(0x08, &PADRH);
2861 #endif /* CONFIG_CODEC == MAS3587F */
2863 #ifdef DEBUG
2864 dbg_timer_start();
2865 dbg_cnt2us(0);
2866 #endif /* DEBUG */
2869 #endif /* CONFIG_CODEC != SWCODEC */