M:Robe 500: Get the rest of the games except doom working with the touchscreen.
[kugel-rb.git] / apps / mpeg.c
blob5ebf58fcf042f20d3c5333c041fd44670c7540ab
1 /***************************************************************************
2 * __________ __ ___.
3 * Open \______ \ ____ ____ | | _\_ |__ _______ ___
4 * Source | _// _ \_/ ___\| |/ /| __ \ / _ \ \/ /
5 * Jukebox | | ( <_> ) \___| < | \_\ ( <_> > < <
6 * Firmware |____|_ /\____/ \___ >__|_ \|___ /\____/__/\_ \
7 * \/ \/ \/ \/ \/
8 * $Id$
10 * Copyright (C) 2002 by Linus Nielsen Feltzing
12 * This program is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU General Public License
14 * as published by the Free Software Foundation; either version 2
15 * of the License, or (at your option) any later version.
17 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
18 * KIND, either express or implied.
20 ****************************************************************************/
21 #include <stdbool.h>
22 #include <stdlib.h>
23 #include "config.h"
25 #if CONFIG_CODEC != SWCODEC
27 #include "debug.h"
28 #include "panic.h"
29 #include "metadata.h"
30 #include "mpeg.h"
31 #include "audio.h"
32 #include "storage.h"
33 #include "string.h"
34 #include <kernel.h>
35 #include "thread.h"
36 #include "errno.h"
37 #include "mp3data.h"
38 #include "buffer.h"
39 #include "mp3_playback.h"
40 #include "sound.h"
41 #include "bitswap.h"
42 #include "appevents.h"
43 #ifndef SIMULATOR
44 #include "i2c.h"
45 #include "mas.h"
46 #include "system.h"
47 #include "usb.h"
48 #include "file.h"
49 #include "hwcompat.h"
50 #endif /* !SIMULATOR */
51 #ifdef HAVE_LCD_BITMAP
52 #include "lcd.h"
53 #endif
55 #ifndef SIMULATOR
56 extern unsigned long mas_version_code;
57 #endif
59 #if CONFIG_CODEC == MAS3587F
60 extern enum /* from mp3_playback.c */
62 MPEG_DECODER,
63 MPEG_ENCODER
64 } mpeg_mode;
65 #endif /* CONFIG_CODEC == MAS3587F */
67 extern char* playlist_peek(int steps);
68 extern bool playlist_check(int steps);
69 extern int playlist_next(int steps);
70 extern int playlist_amount(void);
71 extern int playlist_update_resume_info(const struct mp3entry* id3);
73 #define MPEG_PLAY 1
74 #define MPEG_STOP 2
75 #define MPEG_PAUSE 3
76 #define MPEG_RESUME 4
77 #define MPEG_NEXT 5
78 #define MPEG_PREV 6
79 #define MPEG_FF_REWIND 7
80 #define MPEG_FLUSH_RELOAD 8
81 #define MPEG_RECORD 9
82 #define MPEG_INIT_RECORDING 10
83 #define MPEG_INIT_PLAYBACK 11
84 #define MPEG_NEW_FILE 12
85 #define MPEG_PAUSE_RECORDING 13
86 #define MPEG_RESUME_RECORDING 14
87 #define MPEG_NEED_DATA 100
88 #define MPEG_TRACK_CHANGE 101
89 #define MPEG_SAVE_DATA 102
90 #define MPEG_STOP_DONE 103
91 #define MPEG_PRERECORDING_TICK 104
93 /* indicator for MPEG_NEED_DATA */
94 #define GENERATE_UNBUFFER_EVENTS 1
96 /* list of tracks in memory */
97 #define MAX_TRACK_ENTRIES (1<<4) /* Must be power of 2 */
98 #define MAX_TRACK_ENTRIES_MASK (MAX_TRACK_ENTRIES - 1)
100 struct trackdata
102 struct mp3entry id3;
103 int mempos;
104 int load_ahead_index;
107 static struct trackdata trackdata[MAX_TRACK_ENTRIES];
109 static unsigned int current_track_counter = 0;
110 static unsigned int last_track_counter = 0;
112 /* Play time of the previous track */
113 unsigned long prev_track_elapsed;
115 #ifndef SIMULATOR
116 static int track_read_idx = 0;
117 static int track_write_idx = 0;
118 #endif /* !SIMULATOR */
120 /* Cuesheet callback */
121 static bool (*cuesheet_callback)(const char *filename) = NULL;
123 static const char mpeg_thread_name[] = "mpeg";
124 static unsigned int mpeg_errno;
126 static bool playing = false; /* We are playing an MP3 stream */
127 static bool is_playing = false; /* We are (attempting to) playing MP3 files */
128 static bool paused; /* playback is paused */
130 #ifdef SIMULATOR
131 static char mpeg_stack[DEFAULT_STACK_SIZE];
132 static struct mp3entry taginfo;
134 #else /* !SIMULATOR */
135 static struct event_queue mpeg_queue;
136 static long mpeg_stack[(DEFAULT_STACK_SIZE + 0x1000)/sizeof(long)];
138 static int audiobuflen;
139 static int audiobuf_write;
140 static int audiobuf_swapwrite;
141 static int audiobuf_read;
143 static int mpeg_file;
145 static bool play_pending; /* We are about to start playing */
146 static bool play_pending_track_change; /* When starting play we're starting a new file */
147 static bool filling; /* We are filling the buffer with data from disk */
148 static bool dma_underrun; /* True when the DMA has stopped because of
149 slow disk reading (read error, shaking) */
150 static bool mpeg_stop_done;
152 static int last_dma_tick = 0;
153 static int last_dma_chunk_size;
155 static long low_watermark; /* Dynamic low watermark level */
156 static long low_watermark_margin = 0; /* Extra time in seconds for watermark */
157 static long lowest_watermark_level; /* Debug value to observe the buffer
158 usage */
159 #if CONFIG_CODEC == MAS3587F
160 static char recording_filename[MAX_PATH]; /* argument to thread */
161 static char delayed_filename[MAX_PATH]; /* internal copy of above */
163 static char xing_buffer[MAX_XING_HEADER_SIZE];
165 static bool init_recording_done;
166 static bool init_playback_done;
167 static bool prerecording; /* True if prerecording is enabled */
168 static bool is_prerecording; /* True if we are prerecording */
169 static bool is_recording; /* We are recording */
171 static enum {
172 NOT_SAVING = 0, /* reasons to save data, sorted by importance */
173 BUFFER_FULL,
174 NEW_FILE,
175 STOP_RECORDING
176 } saving_status;
178 static int rec_frequency_index; /* For create_xing_header() calls */
179 static int rec_version_index; /* For create_xing_header() calls */
181 struct prerecord_info {
182 int mempos;
183 unsigned long framecount;
186 static struct prerecord_info prerecord_buffer[MPEG_MAX_PRERECORD_SECONDS];
187 static int prerecord_index; /* Current index in the prerecord buffer */
188 static int prerecording_max_seconds; /* Max number of seconds to store */
189 static int prerecord_count; /* Number of seconds in the prerecord buffer */
190 static int prerecord_timeout; /* The tick count of the next prerecord data
191 store */
193 unsigned long record_start_time; /* Value of current_tick when recording
194 was started */
195 unsigned long pause_start_time; /* Value of current_tick when pause was
196 started */
197 static unsigned long last_rec_time;
198 static unsigned long num_rec_bytes;
199 static unsigned long last_rec_bytes;
200 static unsigned long frame_count_start;
201 static unsigned long frame_count_end;
202 static unsigned long saved_header = 0;
204 /* Shadow MAS registers */
205 unsigned long shadow_encoder_control = 0;
206 #endif /* CONFIG_CODEC == MAS3587F */
208 #if (CONFIG_CODEC == MAS3587F) || (CONFIG_CODEC == MAS3539F)
209 unsigned long shadow_io_control_main = 0;
210 unsigned long shadow_soft_mute = 0;
211 unsigned shadow_codec_reg0;
212 #endif /* (CONFIG_CODEC == MAS3587F) || (CONFIG_CODEC == MAS3539F) */
214 #ifdef HAVE_RECORDING
215 static const unsigned char empty_id3_header[] =
217 'I', 'D', '3', 0x03, 0x00, 0x00,
218 0x00, 0x00, 0x1f, 0x76 /* Size is 4096 minus 10 bytes for the header */
220 #endif /* HAVE_RECORDING */
223 static int get_unplayed_space(void);
224 static int get_playable_space(void);
225 static int get_unswapped_space(void);
226 #endif /* !SIMULATOR */
228 #if (CONFIG_CODEC == MAS3587F) && !defined(SIMULATOR)
229 static void init_recording(void);
230 static void prepend_header(void);
231 static void update_header(void);
232 static void start_prerecording(void);
233 static void start_recording(void);
234 static void stop_recording(void);
235 static int get_unsaved_space(void);
236 static void pause_recording(void);
237 static void resume_recording(void);
238 #endif /* (CONFIG_CODEC == MAS3587F) && !defined(SIMULATOR) */
241 #ifndef SIMULATOR
242 static int num_tracks_in_memory(void)
244 return (track_write_idx - track_read_idx) & MAX_TRACK_ENTRIES_MASK;
247 #ifdef DEBUG_TAGS
248 static void debug_tags(void)
250 int i;
252 for(i = 0;i < MAX_TRACK_ENTRIES;i++)
254 DEBUGF("%d - %s\n", i, trackdata[i].id3.path);
256 DEBUGF("read: %d, write :%d\n", track_read_idx, track_write_idx);
257 DEBUGF("num_tracks_in_memory: %d\n", num_tracks_in_memory());
259 #else /* !DEBUG_TAGS */
260 #define debug_tags()
261 #endif /* !DEBUG_TAGS */
263 static void remove_current_tag(void)
265 if(num_tracks_in_memory() > 0)
267 /* First move the index, so nobody tries to access the tag */
268 track_read_idx = (track_read_idx+1) & MAX_TRACK_ENTRIES_MASK;
269 debug_tags();
271 else
273 DEBUGF("remove_current_tag: no tracks to remove\n");
277 static void remove_all_non_current_tags(void)
279 track_write_idx = (track_read_idx+1) & MAX_TRACK_ENTRIES_MASK;
280 debug_tags();
283 static void remove_all_tags(void)
285 track_write_idx = track_read_idx;
287 debug_tags();
290 static struct trackdata *get_trackdata(int offset)
292 if(offset >= num_tracks_in_memory())
293 return NULL;
294 else
295 return &trackdata[(track_read_idx + offset) & MAX_TRACK_ENTRIES_MASK];
297 #endif /* !SIMULATOR */
299 /***********************************************************************/
300 /* audio event handling */
302 #define MAX_EVENT_HANDLERS 10
303 struct event_handlers_table
305 AUDIO_EVENT_HANDLER handler;
306 unsigned short mask;
308 static struct event_handlers_table event_handlers[MAX_EVENT_HANDLERS];
309 static int event_handlers_count = 0;
311 void audio_register_event_handler(AUDIO_EVENT_HANDLER handler, unsigned short mask)
313 if (event_handlers_count < MAX_EVENT_HANDLERS)
315 event_handlers[event_handlers_count].handler = handler;
316 event_handlers[event_handlers_count].mask = mask;
317 event_handlers_count++;
321 /* dispatch calls each handler in the order registered and returns after some
322 handler actually handles the event (the event is assumed to no longer be valid
323 after this, due to the handler changing some condition); returns true if someone
324 handled the event, which is expected to cause the caller to skip its own handling
325 of the event */
326 #ifndef SIMULATOR
327 static bool audio_dispatch_event(unsigned short event, unsigned long data)
329 int i = 0;
330 for(i=0; i < event_handlers_count; i++)
332 if ( event_handlers[i].mask & event )
334 int rc = event_handlers[i].handler(event, data);
335 if ( rc == AUDIO_EVENT_RC_HANDLED )
336 return true;
339 return false;
341 #endif
343 /***********************************************************************/
345 static void set_elapsed(struct mp3entry* id3)
347 if ( id3->vbr ) {
348 if ( id3->has_toc ) {
349 /* calculate elapsed time using TOC */
350 int i;
351 unsigned int remainder, plen, relpos, nextpos;
353 /* find wich percent we're at */
354 for (i=0; i<100; i++ )
356 if ( id3->offset < id3->toc[i] * (id3->filesize / 256) )
358 break;
362 i--;
363 if (i < 0)
364 i = 0;
366 relpos = id3->toc[i];
368 if (i < 99)
370 nextpos = id3->toc[i+1];
372 else
374 nextpos = 256;
377 remainder = id3->offset - (relpos * (id3->filesize / 256));
379 /* set time for this percent (divide before multiply to prevent
380 overflow on long files. loss of precision is negligible on
381 short files) */
382 id3->elapsed = i * (id3->length / 100);
384 /* calculate remainder time */
385 plen = (nextpos - relpos) * (id3->filesize / 256);
386 id3->elapsed += (((remainder * 100) / plen) *
387 (id3->length / 10000));
389 else {
390 /* no TOC exists. set a rough estimate using average bitrate */
391 int tpk = id3->length / (id3->filesize / 1024);
392 id3->elapsed = id3->offset / 1024 * tpk;
395 else
396 /* constant bitrate, use exact calculation */
397 id3->elapsed = id3->offset / (id3->bitrate / 8);
400 int audio_get_file_pos(void)
402 int pos = -1;
403 struct mp3entry *id3 = audio_current_track();
405 if (id3->vbr)
407 if (id3->has_toc)
409 /* Use the TOC to find the new position */
410 unsigned int percent, remainder;
411 int curtoc, nexttoc, plen;
413 percent = (id3->elapsed*100)/id3->length;
414 if (percent > 99)
415 percent = 99;
417 curtoc = id3->toc[percent];
419 if (percent < 99)
420 nexttoc = id3->toc[percent+1];
421 else
422 nexttoc = 256;
424 pos = (id3->filesize/256)*curtoc;
426 /* Use the remainder to get a more accurate position */
427 remainder = (id3->elapsed*100)%id3->length;
428 remainder = (remainder*100)/id3->length;
429 plen = (nexttoc - curtoc)*(id3->filesize/256);
430 pos += (plen/100)*remainder;
432 else
434 /* No TOC exists, estimate the new position */
435 pos = (id3->filesize / (id3->length / 1000)) *
436 (id3->elapsed / 1000);
439 else if (id3->bitrate)
440 pos = id3->elapsed * (id3->bitrate / 8);
441 else
443 return -1;
446 if (pos >= (int)(id3->filesize - id3->id3v1len))
448 /* Don't seek right to the end of the file so that we can
449 transition properly to the next song */
450 pos = id3->filesize - id3->id3v1len - 1;
452 else if (pos < (int)id3->first_frame_offset)
454 /* skip past id3v2 tag and other leading garbage */
455 pos = id3->first_frame_offset;
457 return pos;
460 unsigned long mpeg_get_last_header(void)
462 #ifdef SIMULATOR
463 return 0;
464 #else /* !SIMULATOR */
465 unsigned long tmp[2];
467 /* Read the frame data from the MAS and reconstruct it with the
468 frame sync and all */
469 mas_readmem(MAS_BANK_D0, MAS_D0_MPEG_STATUS_1, tmp, 2);
470 return 0xffe00000 | ((tmp[0] & 0x7c00) << 6) | (tmp[1] & 0xffff);
471 #endif /* !SIMULATOR */
474 void audio_set_cuesheet_callback(bool (*handler)(const char *filename))
476 cuesheet_callback = handler;
479 #ifndef SIMULATOR
480 /* Send callback events to notify about removing old tracks. */
481 static void generate_unbuffer_events(void)
483 int i;
484 int numentries = MAX_TRACK_ENTRIES - num_tracks_in_memory();
485 int cur_idx = track_write_idx;
487 for (i = 0; i < numentries; i++)
489 /* Send an event to notify that track has finished. */
490 send_event(PLAYBACK_EVENT_TRACK_FINISH, &trackdata[cur_idx].id3);
491 cur_idx = (cur_idx + 1) & MAX_TRACK_ENTRIES_MASK;
495 /* Send callback events to notify about new tracks. */
496 static void generate_postbuffer_events(void)
498 int i;
499 int numentries = num_tracks_in_memory();
500 int cur_idx = track_read_idx;
502 for (i = 0; i < numentries; i++)
504 send_event(PLAYBACK_EVENT_TRACK_BUFFER, &trackdata[cur_idx].id3);
505 cur_idx = (cur_idx + 1) & MAX_TRACK_ENTRIES_MASK;
509 static void recalculate_watermark(int bitrate)
511 int bytes_per_sec;
512 int time = storage_spinup_time();
514 /* A bitrate of 0 probably means empty VBR header. We play safe
515 and set a high threshold */
516 if(bitrate == 0)
517 bitrate = 320;
519 bytes_per_sec = bitrate * 1000 / 8;
521 if(time)
523 /* No drive spins up faster than 3.5s */
524 if(time < 350)
525 time = 350;
527 time = time * 3;
528 low_watermark = ((low_watermark_margin * HZ + time) *
529 bytes_per_sec) / HZ;
531 else
533 low_watermark = MPEG_LOW_WATER;
537 #ifdef HAVE_DISK_STORAGE
538 void audio_set_buffer_margin(int seconds)
540 low_watermark_margin = seconds;
542 #endif
544 void audio_get_debugdata(struct audio_debug *dbgdata)
546 dbgdata->audiobuflen = audiobuflen;
547 dbgdata->audiobuf_write = audiobuf_write;
548 dbgdata->audiobuf_swapwrite = audiobuf_swapwrite;
549 dbgdata->audiobuf_read = audiobuf_read;
551 dbgdata->last_dma_chunk_size = last_dma_chunk_size;
553 #if CONFIG_CPU == SH7034
554 dbgdata->dma_on = (SCR0 & 0x80) != 0;
555 #endif
556 dbgdata->playing = playing;
557 dbgdata->play_pending = play_pending;
558 dbgdata->is_playing = is_playing;
559 dbgdata->filling = filling;
560 dbgdata->dma_underrun = dma_underrun;
562 dbgdata->unplayed_space = get_unplayed_space();
563 dbgdata->playable_space = get_playable_space();
564 dbgdata->unswapped_space = get_unswapped_space();
566 dbgdata->low_watermark_level = low_watermark;
567 dbgdata->lowest_watermark_level = lowest_watermark_level;
570 #ifdef DEBUG
571 static void dbg_timer_start(void)
573 /* We are using timer 2 */
575 TSTR &= ~0x04; /* Stop the timer */
576 TSNC &= ~0x04; /* No synchronization */
577 TMDR &= ~0x44; /* Operate normally */
579 TCNT2 = 0; /* Start counting at 0 */
580 TCR2 = 0x03; /* Sysclock/8 */
582 TSTR |= 0x04; /* Start timer 2 */
585 static int dbg_cnt2us(unsigned int cnt)
587 return (cnt * 10000) / (FREQ/800);
589 #endif /* DEBUG */
591 static int get_unplayed_space(void)
593 int space = audiobuf_write - audiobuf_read;
594 if (space < 0)
595 space += audiobuflen;
596 return space;
599 static int get_playable_space(void)
601 int space = audiobuf_swapwrite - audiobuf_read;
602 if (space < 0)
603 space += audiobuflen;
604 return space;
607 static int get_unplayed_space_current_song(void)
609 int space;
611 if (num_tracks_in_memory() > 1)
613 space = get_trackdata(1)->mempos - audiobuf_read;
615 else
617 space = audiobuf_write - audiobuf_read;
620 if (space < 0)
621 space += audiobuflen;
623 return space;
626 static int get_unswapped_space(void)
628 int space = audiobuf_write - audiobuf_swapwrite;
629 if (space < 0)
630 space += audiobuflen;
631 return space;
634 #if CONFIG_CODEC == MAS3587F
635 static int get_unsaved_space(void)
637 int space = audiobuf_write - audiobuf_read;
638 if (space < 0)
639 space += audiobuflen;
640 return space;
643 static void drain_dma_buffer(void)
645 while (PBDRH & 0x40)
647 xor_b(0x08, &PADRH);
649 while (PBDRH & 0x80);
651 xor_b(0x08, &PADRH);
653 while (!(PBDRH & 0x80));
657 #ifdef DEBUG
658 static long timing_info_index = 0;
659 static long timing_info[1024];
660 #endif /* DEBUG */
662 void rec_tick (void) __attribute__ ((section (".icode")));
663 void rec_tick(void)
665 int i;
666 int delay;
667 char data;
669 if(is_recording && (PBDRH & 0x40))
671 #ifdef DEBUG
672 timing_info[timing_info_index++] = current_tick;
673 TCNT2 = 0;
674 #endif /* DEBUG */
675 /* Note: Although this loop is run in interrupt context, further
676 * optimisation will do no good. The MAS would then deliver bad
677 * frames occasionally, as observed in extended experiments. */
678 i = 0;
679 while (PBDRH & 0x40) /* We try to read as long as EOD is high */
681 xor_b(0x08, &PADRH); /* Set PR active, independent of polarity */
683 delay = 100;
684 while (PBDRH & 0x80) /* Wait until /RTW becomes active */
686 if (--delay <= 0) /* Bail out if we have to wait too long */
687 { /* i.e. the MAS doesn't want to talk to us */
688 xor_b(0x08, &PADRH); /* Set PR inactive */
689 goto transfer_end; /* and get out of here */
693 data = *(unsigned char *)0x04000000; /* read data byte */
695 xor_b(0x08, &PADRH); /* Set PR inactive */
697 audiobuf[audiobuf_write++] = data;
699 if (audiobuf_write >= audiobuflen)
700 audiobuf_write = 0;
702 i++;
704 transfer_end:
706 #ifdef DEBUG
707 timing_info[timing_info_index++] = TCNT2 + (i << 16);
708 timing_info_index &= 0x3ff;
709 #endif /* DEBUG */
711 num_rec_bytes += i;
713 if(is_prerecording)
715 if(TIME_AFTER(current_tick, prerecord_timeout))
717 prerecord_timeout = current_tick + HZ;
718 queue_post(&mpeg_queue, MPEG_PRERECORDING_TICK, 0);
721 else
723 /* Signal to save the data if we are running out of buffer
724 space */
725 if (audiobuflen - get_unsaved_space() < MPEG_RECORDING_LOW_WATER
726 && saving_status == NOT_SAVING)
728 saving_status = BUFFER_FULL;
729 queue_post(&mpeg_queue, MPEG_SAVE_DATA, 0);
734 #endif /* CONFIG_CODEC == MAS3587F */
736 void playback_tick(void)
738 struct trackdata *ptd = get_trackdata(0);
739 if(ptd)
741 ptd->id3.elapsed += (current_tick - last_dma_tick) * 1000 / HZ;
742 last_dma_tick = current_tick;
743 audio_dispatch_event(AUDIO_EVENT_POS_REPORT,
744 (unsigned long)ptd->id3.elapsed);
748 static void reset_mp3_buffer(void)
750 audiobuf_read = 0;
751 audiobuf_write = 0;
752 audiobuf_swapwrite = 0;
753 lowest_watermark_level = audiobuflen;
756 /* DMA transfer end interrupt callback */
757 static void transfer_end(unsigned char** ppbuf, size_t* psize)
759 if(playing && !paused)
761 int unplayed_space_left;
762 int space_until_end_of_buffer;
763 int track_offset = 1;
764 struct trackdata *track;
766 audiobuf_read += last_dma_chunk_size;
767 if(audiobuf_read >= audiobuflen)
768 audiobuf_read = 0;
770 /* First, check if we are on a track boundary */
771 if (num_tracks_in_memory() > 1)
773 if (audiobuf_read == get_trackdata(track_offset)->mempos)
775 if ( ! audio_dispatch_event(AUDIO_EVENT_END_OF_TRACK, 0) )
777 queue_post(&mpeg_queue, MPEG_TRACK_CHANGE, 0);
778 track_offset++;
783 unplayed_space_left = get_unplayed_space();
785 space_until_end_of_buffer = audiobuflen - audiobuf_read;
787 if(!filling && unplayed_space_left < low_watermark)
789 filling = true;
790 queue_post(&mpeg_queue, MPEG_NEED_DATA, GENERATE_UNBUFFER_EVENTS);
793 if(unplayed_space_left)
795 last_dma_chunk_size = MIN(0x2000, unplayed_space_left);
796 last_dma_chunk_size = MIN(last_dma_chunk_size,
797 space_until_end_of_buffer);
799 /* several tracks loaded? */
800 track = get_trackdata(track_offset);
801 if(track)
803 /* will we move across the track boundary? */
804 if (( audiobuf_read < track->mempos ) &&
805 ((audiobuf_read+last_dma_chunk_size) >
806 track->mempos ))
808 /* Make sure that we end exactly on the boundary */
809 last_dma_chunk_size = track->mempos - audiobuf_read;
813 *psize = last_dma_chunk_size & 0xffff;
814 *ppbuf = audiobuf + audiobuf_read;
815 track = get_trackdata(0);
816 if(track)
817 track->id3.offset += last_dma_chunk_size;
819 /* Update the watermark debug level */
820 if(unplayed_space_left < lowest_watermark_level)
821 lowest_watermark_level = unplayed_space_left;
823 else
825 /* Check if the end of data is because of a hard disk error.
826 If there is an open file handle, we are still playing music.
827 If not, the last file has been loaded, and the file handle is
828 closed. */
829 if(mpeg_file >= 0)
831 /* Update the watermark debug level */
832 if(unplayed_space_left < lowest_watermark_level)
833 lowest_watermark_level = unplayed_space_left;
835 DEBUGF("DMA underrun.\n");
836 dma_underrun = true;
838 else
840 if ( ! audio_dispatch_event(AUDIO_EVENT_END_OF_TRACK, 0) )
842 DEBUGF("No more MP3 data. Stopping.\n");
843 queue_post(&mpeg_queue, MPEG_TRACK_CHANGE, 0);
844 playing = false;
847 *psize = 0; /* no more transfer */
852 static struct trackdata *add_track_to_tag_list(const char *filename)
854 struct trackdata *track;
855 bool send_nid3_event;
857 if(num_tracks_in_memory() >= MAX_TRACK_ENTRIES)
859 DEBUGF("Tag memory is full\n");
860 return NULL;
863 track = &trackdata[track_write_idx];
865 /* grab id3 tag of new file and
866 remember where in memory it starts */
867 if(mp3info(&track->id3, filename))
869 DEBUGF("Bad mp3\n");
870 return NULL;
872 track->mempos = audiobuf_write;
873 track->id3.elapsed = 0;
874 #ifdef HAVE_LCD_BITMAP
875 if (track->id3.title)
876 lcd_getstringsize(track->id3.title, NULL, NULL);
877 if (track->id3.artist)
878 lcd_getstringsize(track->id3.artist, NULL, NULL);
879 if (track->id3.album)
880 lcd_getstringsize(track->id3.album, NULL, NULL);
881 #endif
882 if (cuesheet_callback)
883 if (cuesheet_callback(filename))
884 track->id3.cuesheet_type = 1;
886 /* if this track is the next track then let the UI know it can get it */
887 send_nid3_event = (track_write_idx == track_read_idx + 1);
888 track_write_idx = (track_write_idx+1) & MAX_TRACK_ENTRIES_MASK;
889 if (send_nid3_event)
890 send_event(PLAYBACK_EVENT_NEXTTRACKID3_AVAILABLE, NULL);
891 debug_tags();
892 return track;
895 static int new_file(int steps)
897 int max_steps = playlist_amount();
898 int start = 0;
899 int i;
900 struct trackdata *track;
902 /* Find out how many steps to advance. The load_ahead_index field tells
903 us how many playlist entries it had to skip to get to a valid one.
904 We add those together to find out where to start. */
905 if(steps > 0 && num_tracks_in_memory() > 1)
907 /* Begin with the song after the currently playing one */
908 i = 1;
909 while((track = get_trackdata(i++)))
911 start += track->load_ahead_index;
915 do {
916 char *trackname;
918 trackname = playlist_peek( start + steps );
919 if ( !trackname )
920 return -1;
922 DEBUGF("Loading %s\n", trackname);
924 mpeg_file = open(trackname, O_RDONLY);
925 if(mpeg_file < 0) {
926 DEBUGF("Couldn't open file: %s\n",trackname);
927 if(steps < 0)
928 steps--;
929 else
930 steps++;
932 else
934 struct trackdata *track = add_track_to_tag_list(trackname);
936 if(!track)
938 /* Bad mp3 file */
939 if(steps < 0)
940 steps--;
941 else
942 steps++;
943 close(mpeg_file);
944 mpeg_file = -1;
946 else
948 /* skip past id3v2 tag */
949 lseek(mpeg_file,
950 track->id3.first_frame_offset,
951 SEEK_SET);
952 track->id3.index = steps;
953 track->load_ahead_index = steps;
954 track->id3.offset = 0;
956 if(track->id3.vbr)
957 /* Average bitrate * 1.5 */
958 recalculate_watermark(
959 (track->id3.bitrate * 3) / 2);
960 else
961 recalculate_watermark(
962 track->id3.bitrate);
967 /* Bail out if no file could be opened */
968 if(abs(steps) > max_steps)
969 return -1;
970 } while ( mpeg_file < 0 );
972 return 0;
975 static void stop_playing(void)
977 struct trackdata *track;
979 /* Stop the current stream */
980 mp3_play_stop();
981 playing = false;
982 filling = false;
984 track = get_trackdata(0);
985 if (track != NULL)
986 prev_track_elapsed = track->id3.elapsed;
988 if(mpeg_file >= 0)
989 close(mpeg_file);
990 mpeg_file = -1;
991 remove_all_tags();
992 generate_unbuffer_events();
993 reset_mp3_buffer();
996 static void end_current_track(void) {
997 struct trackdata *track;
999 play_pending = false;
1000 playing = false;
1001 mp3_play_pause(false);
1003 track = get_trackdata(0);
1004 if (track != NULL)
1005 prev_track_elapsed = track->id3.elapsed;
1007 reset_mp3_buffer();
1008 remove_all_tags();
1009 generate_unbuffer_events();
1011 if(mpeg_file >= 0)
1012 close(mpeg_file);
1015 /* Is this a really the end of playback or is a new playlist starting */
1016 static void check_playlist_end(int direction)
1018 /* Use the largest possible step size to account for skipped tracks */
1019 int steps = playlist_amount();
1021 if (direction < 0)
1022 steps = -steps;
1024 if (playlist_next(steps) < 0)
1025 is_playing = false;
1028 static void update_playlist(void)
1030 if (num_tracks_in_memory() > 0)
1032 struct trackdata *track = get_trackdata(0);
1033 track->id3.index = playlist_next(track->id3.index);
1035 else
1037 /* End of playlist? */
1038 check_playlist_end(1);
1041 playlist_update_resume_info(audio_current_track());
1044 static void track_change(void)
1046 DEBUGF("Track change\n");
1048 struct trackdata *track = get_trackdata(0);
1049 prev_track_elapsed = track->id3.elapsed;
1051 #if (CONFIG_CODEC == MAS3587F) || (CONFIG_CODEC == MAS3539F)
1052 /* Reset the AVC */
1053 sound_set_avc(-1);
1054 #endif /* (CONFIG_CODEC == MAS3587F) || (CONFIG_CODEC == MAS3539F) */
1056 if (num_tracks_in_memory() > 0)
1058 remove_current_tag();
1059 update_playlist();
1060 if (is_playing)
1061 send_event(PLAYBACK_EVENT_TRACK_CHANGE, audio_current_track());
1064 current_track_counter++;
1067 unsigned long audio_prev_elapsed(void)
1069 return prev_track_elapsed;
1072 #ifdef DEBUG
1073 void hexdump(const unsigned char *buf, int len)
1075 int i;
1077 for(i = 0;i < len;i++)
1079 if(i && (i & 15) == 0)
1081 DEBUGF("\n");
1083 DEBUGF("%02x ", buf[i]);
1085 DEBUGF("\n");
1087 #endif /* DEBUG */
1089 static void start_playback_if_ready(void)
1091 int playable_space;
1093 playable_space = audiobuf_swapwrite - audiobuf_read;
1094 if(playable_space < 0)
1095 playable_space += audiobuflen;
1097 /* See if we have started playing yet. If not, do it. */
1098 if(play_pending || dma_underrun)
1100 /* If the filling has stopped, and we still haven't reached
1101 the watermark, the file must be smaller than the
1102 watermark. We must still play it. */
1103 if((playable_space >= MPEG_PLAY_PENDING_THRESHOLD) ||
1104 !filling || dma_underrun)
1106 DEBUGF("P\n");
1107 if (play_pending) /* don't do this when recovering from DMA underrun */
1109 generate_postbuffer_events(); /* signal first track as buffered */
1110 if (play_pending_track_change)
1112 play_pending_track_change = false;
1113 send_event(PLAYBACK_EVENT_TRACK_CHANGE, audio_current_track());
1115 play_pending = false;
1117 playing = true;
1119 last_dma_chunk_size = MIN(0x2000, get_unplayed_space_current_song());
1120 mp3_play_data(audiobuf + audiobuf_read, last_dma_chunk_size, transfer_end);
1121 dma_underrun = false;
1123 if (!paused)
1125 last_dma_tick = current_tick;
1126 mp3_play_pause(true);
1129 /* Tell ourselves that we need more data */
1130 queue_post(&mpeg_queue, MPEG_NEED_DATA, 0);
1135 static bool swap_one_chunk(void)
1137 int free_space_left;
1138 int amount_to_swap;
1140 free_space_left = get_unswapped_space();
1142 if(free_space_left == 0 && !play_pending)
1143 return false;
1145 /* Swap in larger chunks when the user is waiting for the playback
1146 to start, or when there is dangerously little playable data left */
1147 if(play_pending)
1148 amount_to_swap = MIN(MPEG_PLAY_PENDING_SWAPSIZE, free_space_left);
1149 else
1151 if(get_playable_space() < low_watermark)
1152 amount_to_swap = MIN(MPEG_LOW_WATER_SWAP_CHUNKSIZE,
1153 free_space_left);
1154 else
1155 amount_to_swap = MIN(MPEG_SWAP_CHUNKSIZE, free_space_left);
1158 if(audiobuf_write < audiobuf_swapwrite)
1159 amount_to_swap = MIN(audiobuflen - audiobuf_swapwrite,
1160 amount_to_swap);
1161 else
1162 amount_to_swap = MIN(audiobuf_write - audiobuf_swapwrite,
1163 amount_to_swap);
1165 bitswap(audiobuf + audiobuf_swapwrite, amount_to_swap);
1167 audiobuf_swapwrite += amount_to_swap;
1168 if(audiobuf_swapwrite >= audiobuflen)
1170 audiobuf_swapwrite = 0;
1173 return true;
1176 static void mpeg_thread(void)
1178 static int pause_tick = 0;
1179 static unsigned int pause_track = 0;
1180 struct queue_event ev;
1181 int len;
1182 int free_space_left;
1183 int unplayed_space_left;
1184 int amount_to_read;
1185 int t1, t2;
1186 int start_offset;
1187 #if CONFIG_CODEC == MAS3587F
1188 int amount_to_save;
1189 int save_endpos = 0;
1190 int rc;
1191 int level;
1192 long offset;
1193 #endif /* CONFIG_CODEC == MAS3587F */
1195 is_playing = false;
1196 play_pending = false;
1197 playing = false;
1198 mpeg_file = -1;
1200 while(1)
1202 #if CONFIG_CODEC == MAS3587F
1203 if(mpeg_mode == MPEG_DECODER)
1205 #endif /* CONFIG_CODEC == MAS3587F */
1206 yield();
1208 /* Swap if necessary, and don't block on the queue_wait() */
1209 if(swap_one_chunk())
1211 queue_wait_w_tmo(&mpeg_queue, &ev, 0);
1213 else if (playing)
1215 /* periodically update resume info */
1216 queue_wait_w_tmo(&mpeg_queue, &ev, HZ/2);
1218 else
1220 DEBUGF("S R:%x W:%x SW:%x\n",
1221 audiobuf_read, audiobuf_write, audiobuf_swapwrite);
1222 queue_wait(&mpeg_queue, &ev);
1225 start_playback_if_ready();
1227 switch(ev.id)
1229 case MPEG_PLAY:
1230 DEBUGF("MPEG_PLAY\n");
1232 #if CONFIG_TUNER
1233 /* Silence the A/D input, it may be on because the radio
1234 may be playing */
1235 mas_codec_writereg(6, 0x0000);
1236 #endif /* CONFIG_TUNER */
1238 /* Stop the current stream */
1239 paused = false;
1240 end_current_track();
1242 if ( new_file(0) == -1 )
1244 is_playing = false;
1245 track_change();
1246 break;
1249 start_offset = (int)ev.data;
1251 /* mid-song resume? */
1252 if (start_offset) {
1253 struct mp3entry* id3 = &get_trackdata(0)->id3;
1254 lseek(mpeg_file, start_offset, SEEK_SET);
1255 id3->offset = start_offset;
1256 set_elapsed(id3);
1258 else {
1259 /* skip past id3v2 tag */
1260 lseek(mpeg_file,
1261 get_trackdata(0)->id3.first_frame_offset,
1262 SEEK_SET);
1266 /* Make it read more data */
1267 filling = true;
1268 queue_post(&mpeg_queue, MPEG_NEED_DATA, 0);
1270 /* Tell the file loading code that we want to start playing
1271 as soon as we have some data */
1272 play_pending = true;
1273 play_pending_track_change = true;
1275 update_playlist();
1276 current_track_counter++;
1277 break;
1279 case MPEG_STOP:
1280 DEBUGF("MPEG_STOP\n");
1281 is_playing = false;
1282 paused = false;
1284 if (playing)
1285 playlist_update_resume_info(audio_current_track());
1287 stop_playing();
1288 mpeg_stop_done = true;
1289 break;
1291 case MPEG_PAUSE:
1292 DEBUGF("MPEG_PAUSE\n");
1293 /* Stop the current stream */
1294 if (playing)
1295 playlist_update_resume_info(audio_current_track());
1296 paused = true;
1297 playing = false;
1298 pause_tick = current_tick;
1299 pause_track = current_track_counter;
1300 mp3_play_pause(false);
1301 break;
1303 case MPEG_RESUME:
1304 DEBUGF("MPEG_RESUME\n");
1305 /* Continue the current stream */
1306 paused = false;
1307 if (!play_pending)
1309 playing = true;
1310 if ( current_track_counter == pause_track )
1311 last_dma_tick += current_tick - pause_tick;
1312 else
1313 last_dma_tick = current_tick;
1314 pause_tick = 0;
1315 mp3_play_pause(true);
1317 break;
1319 case MPEG_NEXT:
1320 DEBUGF("MPEG_NEXT\n");
1321 /* is next track in ram? */
1322 if ( num_tracks_in_memory() > 1 ) {
1323 int unplayed_space_left, unswapped_space_left;
1325 /* stop the current stream */
1326 play_pending = false;
1327 playing = false;
1328 mp3_play_pause(false);
1330 track_change();
1331 audiobuf_read = get_trackdata(0)->mempos;
1332 last_dma_chunk_size = MIN(0x2000, get_unplayed_space_current_song());
1333 mp3_play_data(audiobuf + audiobuf_read, last_dma_chunk_size, transfer_end);
1334 dma_underrun = false;
1335 last_dma_tick = current_tick;
1337 unplayed_space_left = get_unplayed_space();
1338 unswapped_space_left = get_unswapped_space();
1340 /* should we start reading more data? */
1341 if(!filling && (unplayed_space_left < low_watermark)) {
1342 filling = true;
1343 queue_post(&mpeg_queue, MPEG_NEED_DATA, GENERATE_UNBUFFER_EVENTS);
1344 play_pending = true;
1345 } else if(unswapped_space_left &&
1346 unswapped_space_left > unplayed_space_left) {
1347 /* Stop swapping the data from the previous file */
1348 audiobuf_swapwrite = audiobuf_read;
1349 play_pending = true;
1350 } else {
1351 playing = true;
1352 if (!paused)
1353 mp3_play_pause(true);
1356 else {
1357 if (!playlist_check(1))
1358 break;
1360 /* stop the current stream */
1361 end_current_track();
1363 if (new_file(1) < 0) {
1364 DEBUGF("No more files to play\n");
1365 filling = false;
1367 check_playlist_end(1);
1368 current_track_counter++;
1369 } else {
1370 /* Make it read more data */
1371 filling = true;
1372 queue_post(&mpeg_queue, MPEG_NEED_DATA, 0);
1374 /* Tell the file loading code that we want
1375 to start playing as soon as we have some data */
1376 play_pending = true;
1377 play_pending_track_change = true;
1379 update_playlist();
1380 current_track_counter++;
1383 break;
1385 case MPEG_PREV: {
1386 DEBUGF("MPEG_PREV\n");
1388 if (!playlist_check(-1))
1389 break;
1391 /* stop the current stream */
1392 end_current_track();
1394 /* Open the next file */
1395 if (new_file(-1) < 0) {
1396 DEBUGF("No more files to play\n");
1397 filling = false;
1399 check_playlist_end(-1);
1400 current_track_counter++;
1401 } else {
1402 /* Make it read more data */
1403 filling = true;
1404 queue_post(&mpeg_queue, MPEG_NEED_DATA, 0);
1406 /* Tell the file loading code that we want to
1407 start playing as soon as we have some data */
1408 play_pending = true;
1409 play_pending_track_change = true;
1411 update_playlist();
1412 current_track_counter++;
1414 break;
1417 case MPEG_FF_REWIND: {
1418 struct mp3entry *id3 = audio_current_track();
1419 unsigned int oldtime = id3->elapsed;
1420 unsigned int newtime = (unsigned int)ev.data;
1421 int curpos, newpos, diffpos;
1422 DEBUGF("MPEG_FF_REWIND\n");
1424 id3->elapsed = newtime;
1426 newpos = audio_get_file_pos();
1427 if(newpos < 0)
1429 id3->elapsed = oldtime;
1430 break;
1433 if (mpeg_file >= 0)
1434 curpos = lseek(mpeg_file, 0, SEEK_CUR);
1435 else
1436 curpos = id3->filesize;
1438 if (num_tracks_in_memory() > 1)
1440 /* We have started loading other tracks that need to be
1441 accounted for */
1442 struct trackdata *track;
1443 int i = 0;
1445 while((track = get_trackdata(i++)))
1447 curpos += track->id3.filesize;
1451 diffpos = curpos - newpos;
1453 if(!filling && diffpos >= 0 && diffpos < audiobuflen)
1455 int unplayed_space_left, unswapped_space_left;
1457 /* We are changing to a position that's already in
1458 memory, so we just move the DMA read pointer. */
1459 audiobuf_read = audiobuf_write - diffpos;
1460 if (audiobuf_read < 0)
1462 audiobuf_read += audiobuflen;
1465 unplayed_space_left = get_unplayed_space();
1466 unswapped_space_left = get_unswapped_space();
1468 /* If unswapped_space_left is larger than
1469 unplayed_space_left, it means that the swapwrite pointer
1470 hasn't yet advanced up to the new location of the read
1471 pointer. We just move it, there is no need to swap
1472 data that won't be played anyway. */
1474 if (unswapped_space_left > unplayed_space_left)
1476 DEBUGF("Moved swapwrite\n");
1477 audiobuf_swapwrite = audiobuf_read;
1478 play_pending = true;
1481 if (mpeg_file>=0 && unplayed_space_left < low_watermark)
1483 /* We need to load more data before starting */
1484 filling = true;
1485 queue_post(&mpeg_queue, MPEG_NEED_DATA, GENERATE_UNBUFFER_EVENTS);
1486 play_pending = true;
1488 else
1490 /* resume will start at new position */
1491 last_dma_chunk_size =
1492 MIN(0x2000, get_unplayed_space_current_song());
1493 mp3_play_data(audiobuf + audiobuf_read,
1494 last_dma_chunk_size, transfer_end);
1495 dma_underrun = false;
1498 else
1500 /* Move to the new position in the file and start
1501 loading data */
1502 reset_mp3_buffer();
1504 if (num_tracks_in_memory() > 1)
1506 /* We have to reload the current track */
1507 close(mpeg_file);
1508 remove_all_non_current_tags();
1509 generate_unbuffer_events();
1510 mpeg_file = -1;
1513 if (mpeg_file < 0)
1515 mpeg_file = open(id3->path, O_RDONLY);
1516 if (mpeg_file < 0)
1518 id3->elapsed = oldtime;
1519 break;
1523 if(-1 == lseek(mpeg_file, newpos, SEEK_SET))
1525 id3->elapsed = oldtime;
1526 break;
1529 filling = true;
1530 queue_post(&mpeg_queue, MPEG_NEED_DATA, 0);
1532 /* Tell the file loading code that we want to start playing
1533 as soon as we have some data */
1534 play_pending = true;
1537 id3->offset = newpos;
1539 break;
1542 case MPEG_FLUSH_RELOAD: {
1543 int numtracks = num_tracks_in_memory();
1544 bool reload_track = false;
1546 if (numtracks > 1)
1548 /* Reset the buffer */
1549 audiobuf_write = get_trackdata(1)->mempos;
1551 /* Reset swapwrite unless we're still swapping current
1552 track */
1553 if (get_unplayed_space() <= get_playable_space())
1554 audiobuf_swapwrite = audiobuf_write;
1556 close(mpeg_file);
1557 remove_all_non_current_tags();
1558 generate_unbuffer_events();
1559 mpeg_file = -1;
1560 reload_track = true;
1562 else if (numtracks == 1 && mpeg_file < 0)
1564 reload_track = true;
1567 if(reload_track && new_file(1) >= 0)
1569 /* Tell ourselves that we want more data */
1570 filling = true;
1571 queue_post(&mpeg_queue, MPEG_NEED_DATA, 0);
1574 break;
1577 case MPEG_NEED_DATA:
1578 free_space_left = audiobuf_read - audiobuf_write;
1580 /* We interpret 0 as "empty buffer" */
1581 if(free_space_left <= 0)
1582 free_space_left += audiobuflen;
1584 unplayed_space_left = audiobuflen - free_space_left;
1586 /* Make sure that we don't fill the entire buffer */
1587 free_space_left -= MPEG_HIGH_WATER;
1589 if (ev.data == GENERATE_UNBUFFER_EVENTS)
1590 generate_unbuffer_events();
1592 /* do we have any more buffer space to fill? */
1593 if(free_space_left <= 0)
1595 DEBUGF("0\n");
1596 filling = false;
1597 generate_postbuffer_events();
1598 storage_sleep();
1599 break;
1602 /* Read small chunks while we are below the low water mark */
1603 if(unplayed_space_left < low_watermark)
1604 amount_to_read = MIN(MPEG_LOW_WATER_CHUNKSIZE,
1605 free_space_left);
1606 else
1607 amount_to_read = free_space_left;
1609 /* Don't read more than until the end of the buffer */
1610 amount_to_read = MIN(audiobuflen - audiobuf_write,
1611 amount_to_read);
1612 #if (CONFIG_STORAGE & STORAGE_MMC)
1613 /* MMC is slow, so don't read too large chunks */
1614 amount_to_read = MIN(0x40000, amount_to_read);
1615 #elif MEM == 8
1616 amount_to_read = MIN(0x100000, amount_to_read);
1617 #endif
1619 /* Read as much mpeg data as we can fit in the buffer */
1620 if(mpeg_file >= 0)
1622 DEBUGF("R\n");
1623 t1 = current_tick;
1624 len = read(mpeg_file, audiobuf + audiobuf_write,
1625 amount_to_read);
1626 if(len > 0)
1628 t2 = current_tick;
1629 DEBUGF("time: %d\n", t2 - t1);
1630 DEBUGF("R: %x\n", len);
1632 /* Now make sure that we don't feed the MAS with ID3V1
1633 data */
1634 if (len < amount_to_read)
1636 int i;
1637 static const unsigned char tag[] = "TAG";
1638 int taglen = 128;
1639 int tagptr = audiobuf_write + len - 128;
1641 /* Really rare case: entire potential tag wasn't
1642 read in this call AND audiobuf_write < 128 */
1643 if (tagptr < 0)
1644 tagptr += audiobuflen;
1646 for(i = 0;i < 3;i++)
1648 if(tagptr >= audiobuflen)
1649 tagptr -= audiobuflen;
1651 if(audiobuf[tagptr] != tag[i])
1653 taglen = 0;
1654 break;
1657 tagptr++;
1660 if(taglen)
1662 /* Skip id3v1 tag */
1663 DEBUGF("Skipping ID3v1 tag\n");
1664 len -= taglen;
1666 /* In the very rare case when the entire tag
1667 wasn't read in this read() len will be < 0.
1668 Take care of this when changing the write
1669 pointer. */
1673 audiobuf_write += len;
1675 if (audiobuf_write < 0)
1676 audiobuf_write += audiobuflen;
1678 if(audiobuf_write >= audiobuflen)
1680 audiobuf_write = 0;
1681 DEBUGF("W\n");
1684 /* Tell ourselves that we want more data */
1685 queue_post(&mpeg_queue, MPEG_NEED_DATA, 0);
1687 else
1689 if(len < 0)
1691 DEBUGF("MPEG read error\n");
1694 close(mpeg_file);
1695 mpeg_file = -1;
1697 if(new_file(1) < 0)
1699 /* No more data to play */
1700 DEBUGF("No more files to play\n");
1701 filling = false;
1703 else
1705 /* Tell ourselves that we want more data */
1706 queue_post(&mpeg_queue, MPEG_NEED_DATA, 0);
1710 break;
1712 case MPEG_TRACK_CHANGE:
1713 track_change();
1714 break;
1716 #ifndef USB_NONE
1717 case SYS_USB_CONNECTED:
1718 is_playing = false;
1719 paused = false;
1720 stop_playing();
1722 /* Tell the USB thread that we are safe */
1723 DEBUGF("mpeg_thread got SYS_USB_CONNECTED\n");
1724 usb_acknowledge(SYS_USB_CONNECTED_ACK);
1726 /* Wait until the USB cable is extracted again */
1727 usb_wait_for_disconnect(&mpeg_queue);
1728 break;
1729 #endif /* !USB_NONE */
1731 #if CONFIG_CODEC == MAS3587F
1732 case MPEG_INIT_RECORDING:
1733 init_recording();
1734 init_recording_done = true;
1735 break;
1736 #endif /* CONFIG_CODEC == MAS3587F */
1738 case SYS_TIMEOUT:
1739 if (playing)
1740 playlist_update_resume_info(audio_current_track());
1741 break;
1743 #if CONFIG_CODEC == MAS3587F
1745 else
1747 queue_wait(&mpeg_queue, &ev);
1748 switch(ev.id)
1750 case MPEG_RECORD:
1751 if (is_prerecording)
1753 int startpos;
1755 /* Go back prerecord_count seconds in the buffer */
1756 startpos = prerecord_index - prerecord_count;
1757 if(startpos < 0)
1758 startpos += prerecording_max_seconds;
1760 /* Read the position data from the prerecord buffer */
1761 frame_count_start = prerecord_buffer[startpos].framecount;
1762 startpos = prerecord_buffer[startpos].mempos;
1764 DEBUGF("Start looking at address %x (%x)\n",
1765 audiobuf+startpos, startpos);
1767 saved_header = mpeg_get_last_header();
1769 mem_find_next_frame(startpos, &offset, 1800,
1770 saved_header);
1772 audiobuf_read = startpos + offset;
1773 if(audiobuf_read >= audiobuflen)
1774 audiobuf_read -= audiobuflen;
1776 DEBUGF("New audiobuf_read address: %x (%x)\n",
1777 audiobuf+audiobuf_read, audiobuf_read);
1779 level = disable_irq_save();
1780 num_rec_bytes = get_unsaved_space();
1781 restore_irq(level);
1783 else
1785 frame_count_start = 0;
1786 num_rec_bytes = 0;
1787 audiobuf_read = MPEG_RESERVED_HEADER_SPACE;
1788 audiobuf_write = MPEG_RESERVED_HEADER_SPACE;
1791 prepend_header();
1792 DEBUGF("Recording...\n");
1793 start_recording();
1795 /* Wait until at least one frame is encoded and get the
1796 frame header, for later use by the Xing header
1797 generation */
1798 sleep(HZ/5);
1799 saved_header = mpeg_get_last_header();
1801 /* delayed until buffer is saved, don't open yet */
1802 strcpy(delayed_filename, recording_filename);
1803 mpeg_file = -1;
1805 break;
1807 case MPEG_STOP:
1808 DEBUGF("MPEG_STOP\n");
1810 stop_recording();
1812 /* Save the remaining data in the buffer */
1813 save_endpos = audiobuf_write;
1814 saving_status = STOP_RECORDING;
1815 queue_post(&mpeg_queue, MPEG_SAVE_DATA, 0);
1816 break;
1818 case MPEG_STOP_DONE:
1819 DEBUGF("MPEG_STOP_DONE\n");
1821 if (mpeg_file >= 0)
1822 close(mpeg_file);
1823 mpeg_file = -1;
1825 update_header();
1826 #ifdef DEBUG1
1828 int i;
1829 for(i = 0;i < 512;i++)
1831 DEBUGF("%d - %d us (%d bytes)\n",
1832 timing_info[i*2],
1833 (timing_info[i*2+1] & 0xffff) *
1834 10000 / 13824,
1835 timing_info[i*2+1] >> 16);
1838 #endif /* DEBUG1 */
1840 if (prerecording)
1842 start_prerecording();
1844 mpeg_stop_done = true;
1845 break;
1847 case MPEG_NEW_FILE:
1848 /* Bail out when a more important save is happening */
1849 if (saving_status > NEW_FILE)
1850 break;
1852 /* Make sure we have at least one complete frame
1853 in the buffer. If we haven't recorded a single
1854 frame within 200ms, the MAS is probably not recording
1855 anything, and we bail out. */
1856 amount_to_save = get_unsaved_space();
1857 if (amount_to_save < 1800)
1859 sleep(HZ/5);
1860 amount_to_save = get_unsaved_space();
1863 mas_readmem(MAS_BANK_D0, MAS_D0_MPEG_FRAME_COUNT,
1864 &frame_count_end, 1);
1866 last_rec_time = current_tick - record_start_time;
1867 record_start_time = current_tick;
1868 if (paused)
1869 pause_start_time = record_start_time;
1871 /* capture all values at one point */
1872 level = disable_irq_save();
1873 save_endpos = audiobuf_write;
1874 last_rec_bytes = num_rec_bytes;
1875 num_rec_bytes = 0;
1876 restore_irq(level);
1878 if (amount_to_save >= 1800)
1880 /* Now find a frame boundary to split at */
1881 save_endpos -= 1800;
1882 if (save_endpos < 0)
1883 save_endpos += audiobuflen;
1885 rc = mem_find_next_frame(save_endpos, &offset, 1800,
1886 saved_header);
1887 if (!rc) /* No header found, save whole buffer */
1888 offset = 1800;
1890 save_endpos += offset;
1891 if (save_endpos >= audiobuflen)
1892 save_endpos -= audiobuflen;
1894 last_rec_bytes += offset - 1800;
1895 level = disable_irq_save();
1896 num_rec_bytes += 1800 - offset;
1897 restore_irq(level);
1900 saving_status = NEW_FILE;
1901 queue_post(&mpeg_queue, MPEG_SAVE_DATA, 0);
1902 break;
1904 case MPEG_SAVE_DATA:
1905 if (saving_status == BUFFER_FULL)
1906 save_endpos = audiobuf_write;
1908 if (mpeg_file < 0) /* delayed file open */
1910 mpeg_file = open(delayed_filename, O_WRONLY|O_CREAT);
1912 if (mpeg_file < 0)
1913 panicf("recfile: %d", mpeg_file);
1916 amount_to_save = save_endpos - audiobuf_read;
1917 if (amount_to_save < 0)
1918 amount_to_save += audiobuflen;
1920 amount_to_save = MIN(amount_to_save,
1921 audiobuflen - audiobuf_read);
1922 #if (CONFIG_STORAGE & STORAGE_MMC)
1923 /* MMC is slow, so don't save too large chunks at once */
1924 amount_to_save = MIN(0x40000, amount_to_save);
1925 #elif MEM == 8
1926 amount_to_save = MIN(0x100000, amount_to_save);
1927 #endif
1928 rc = write(mpeg_file, audiobuf + audiobuf_read,
1929 amount_to_save);
1930 if (rc < 0)
1932 if (errno == ENOSPC)
1934 mpeg_errno = AUDIOERR_DISK_FULL;
1935 stop_recording();
1936 queue_post(&mpeg_queue, MPEG_STOP_DONE, 0);
1937 /* will close the file */
1938 break;
1940 else
1941 panicf("rec wrt: %d", rc);
1944 audiobuf_read += amount_to_save;
1945 if (audiobuf_read >= audiobuflen)
1946 audiobuf_read = 0;
1948 if (audiobuf_read == save_endpos) /* all saved */
1950 switch (saving_status)
1952 case BUFFER_FULL:
1953 rc = fsync(mpeg_file);
1954 if (rc < 0)
1955 panicf("rec fls: %d", rc);
1956 storage_sleep();
1957 break;
1959 case NEW_FILE:
1960 /* Close the current file */
1961 rc = close(mpeg_file);
1962 if (rc < 0)
1963 panicf("rec cls: %d", rc);
1964 mpeg_file = -1;
1965 update_header();
1966 storage_sleep();
1968 /* copy new filename */
1969 strcpy(delayed_filename, recording_filename);
1970 prepend_header();
1971 frame_count_start = frame_count_end;
1972 break;
1974 case STOP_RECORDING:
1975 queue_post(&mpeg_queue, MPEG_STOP_DONE, 0);
1976 /* will close the file */
1977 break;
1979 default:
1980 break;
1982 saving_status = NOT_SAVING;
1984 else /* tell ourselves to save the next chunk */
1985 queue_post(&mpeg_queue, MPEG_SAVE_DATA, 0);
1987 break;
1989 case MPEG_PRERECORDING_TICK:
1990 if(!is_prerecording)
1991 break;
1993 /* Store the write pointer every second */
1994 prerecord_buffer[prerecord_index].mempos = audiobuf_write;
1995 mas_readmem(MAS_BANK_D0, MAS_D0_MPEG_FRAME_COUNT,
1996 &prerecord_buffer[prerecord_index].framecount, 1);
1998 /* Wrap if necessary */
1999 if(++prerecord_index == prerecording_max_seconds)
2000 prerecord_index = 0;
2002 /* Update the number of seconds recorded */
2003 if(prerecord_count < prerecording_max_seconds)
2004 prerecord_count++;
2005 break;
2007 case MPEG_INIT_PLAYBACK:
2008 /* Stop the prerecording */
2009 stop_recording();
2010 reset_mp3_buffer();
2011 mp3_play_init();
2012 init_playback_done = true;
2013 break;
2015 case MPEG_PAUSE_RECORDING:
2016 pause_recording();
2017 break;
2019 case MPEG_RESUME_RECORDING:
2020 resume_recording();
2021 break;
2023 case SYS_USB_CONNECTED:
2024 /* We can safely go to USB mode if no recording
2025 is taking place */
2026 if((!is_recording || is_prerecording) && mpeg_stop_done)
2028 /* Even if we aren't recording, we still call this
2029 function, to put the MAS in monitoring mode,
2030 to save power. */
2031 stop_recording();
2033 /* Tell the USB thread that we are safe */
2034 DEBUGF("mpeg_thread got SYS_USB_CONNECTED\n");
2035 usb_acknowledge(SYS_USB_CONNECTED_ACK);
2037 /* Wait until the USB cable is extracted again */
2038 usb_wait_for_disconnect(&mpeg_queue);
2040 break;
2043 #endif /* CONFIG_CODEC == MAS3587F */
2046 #endif /* !SIMULATOR */
2048 struct mp3entry* audio_current_track()
2050 #ifdef SIMULATOR
2051 return &taginfo;
2052 #else /* !SIMULATOR */
2053 if(num_tracks_in_memory())
2054 return &get_trackdata(0)->id3;
2055 else
2056 return NULL;
2057 #endif /* !SIMULATOR */
2060 struct mp3entry* audio_next_track()
2062 #ifdef SIMULATOR
2063 return &taginfo;
2064 #else /* !SIMULATOR */
2065 if(num_tracks_in_memory() > 1)
2066 return &get_trackdata(1)->id3;
2067 else
2068 return NULL;
2069 #endif /* !SIMULATOR */
2072 bool audio_has_changed_track(void)
2074 if(last_track_counter != current_track_counter)
2076 last_track_counter = current_track_counter;
2077 return true;
2079 return false;
2082 #if CONFIG_CODEC == MAS3587F
2083 #ifndef SIMULATOR
2084 void audio_init_playback(void)
2086 init_playback_done = false;
2087 queue_post(&mpeg_queue, MPEG_INIT_PLAYBACK, 0);
2089 while(!init_playback_done)
2090 sleep(1);
2094 /****************************************************************************
2095 * Recording functions
2096 ***************************************************************************/
2097 void audio_init_recording(unsigned int buffer_offset)
2099 buffer_offset = buffer_offset;
2100 init_recording_done = false;
2101 queue_post(&mpeg_queue, MPEG_INIT_RECORDING, 0);
2103 while(!init_recording_done)
2104 sleep(1);
2107 static void init_recording(void)
2109 unsigned long val;
2110 int rc;
2112 /* Disable IRQ6 */
2113 IPRB &= 0xff0f;
2115 stop_playing();
2116 is_playing = false;
2117 paused = false;
2119 /* Init the recording variables */
2120 is_recording = false;
2121 is_prerecording = false;
2123 mpeg_stop_done = true;
2125 mas_reset();
2127 /* Enable the audio CODEC and the DSP core, max analog voltage range */
2128 rc = mas_direct_config_write(MAS_CONTROL, 0x8c00);
2129 if(rc < 0)
2130 panicf("mas_ctrl_w: %d", rc);
2132 /* Stop the current application */
2133 val = 0;
2134 mas_writemem(MAS_BANK_D0, MAS_D0_APP_SELECT, &val, 1);
2137 mas_readmem(MAS_BANK_D0, MAS_D0_APP_RUNNING, &val, 1);
2138 } while(val);
2140 /* Perform black magic as described by the data sheet */
2141 if((mas_version_code & 0x0fff) == 0x0102)
2143 DEBUGF("Performing MAS black magic for B2 version\n");
2144 mas_writereg(0xa3, 0x98);
2145 mas_writereg(0x94, 0xfffff);
2146 val = 0;
2147 mas_writemem(MAS_BANK_D1, 0, &val, 1);
2148 mas_writereg(0xa3, 0x90);
2151 /* Enable A/D Converters */
2152 shadow_codec_reg0 = 0xcccd;
2153 mas_codec_writereg(0x0, shadow_codec_reg0);
2155 /* Copy left channel to right (mono mode) */
2156 mas_codec_writereg(8, 0x8000);
2158 /* ADC scale 0%, DSP scale 100%
2159 We use the DSP output for monitoring, because it works with all
2160 sources including S/PDIF */
2161 mas_codec_writereg(6, 0x0000);
2162 mas_codec_writereg(7, 0x4000);
2164 /* No mute */
2165 shadow_soft_mute = 0;
2166 mas_writemem(MAS_BANK_D0, MAS_D0_SOFT_MUTE, &shadow_soft_mute, 1);
2168 #ifdef HAVE_SPDIF_OUT
2169 val = 0x09; /* Disable SDO and SDI, low impedance S/PDIF outputs */
2170 #else
2171 val = 0x2d; /* Disable SDO and SDI, disable S/PDIF output */
2172 #endif
2173 mas_writemem(MAS_BANK_D0, MAS_D0_INTERFACE_CONTROL, &val, 1);
2175 /* Set Demand mode, monitoring OFF and validate all settings */
2176 shadow_io_control_main = 0x125;
2177 mas_writemem(MAS_BANK_D0, MAS_D0_IO_CONTROL_MAIN, &shadow_io_control_main, 1);
2179 /* Start the encoder application */
2180 val = 0x40;
2181 mas_writemem(MAS_BANK_D0, MAS_D0_APP_SELECT, &val, 1);
2184 mas_readmem(MAS_BANK_D0, MAS_D0_APP_RUNNING, &val, 1);
2185 } while(!(val & 0x40));
2187 /* We have started the recording application with monitoring OFF.
2188 This is because we want to record at least one frame to fill the DMA
2189 buffer, because the silly MAS will not negate EOD until at least one
2190 DMA transfer has taken place.
2191 Now let's wait for some data to be encoded. */
2192 sleep(HZ/5);
2194 /* Now set it to Monitoring mode as default, saves power */
2195 shadow_io_control_main = 0x525;
2196 mas_writemem(MAS_BANK_D0, MAS_D0_IO_CONTROL_MAIN, &shadow_io_control_main, 1);
2198 /* Wait until the DSP has accepted the settings */
2201 mas_readmem(MAS_BANK_D0, MAS_D0_IO_CONTROL_MAIN, &val,1);
2202 } while(val & 1);
2204 drain_dma_buffer();
2205 mpeg_mode = MPEG_ENCODER;
2207 DEBUGF("MAS Recording application started\n");
2209 /* At this point, all settings are the reset MAS defaults, next thing is to
2210 call mpeg_set_recording_options(). */
2213 void audio_record(const char *filename)
2215 mpeg_errno = 0;
2217 strncpy(recording_filename, filename, MAX_PATH - 1);
2218 recording_filename[MAX_PATH - 1] = 0;
2220 queue_post(&mpeg_queue, MPEG_RECORD, 0);
2223 void audio_pause_recording(void)
2225 queue_post(&mpeg_queue, MPEG_PAUSE_RECORDING, 0);
2228 void audio_resume_recording(void)
2230 queue_post(&mpeg_queue, MPEG_RESUME_RECORDING, 0);
2233 static void prepend_header(void)
2235 int startpos;
2236 unsigned i;
2238 /* Make room for header */
2239 audiobuf_read -= MPEG_RESERVED_HEADER_SPACE;
2240 if(audiobuf_read < 0)
2242 /* Clear the bottom half */
2243 memset(audiobuf, 0, audiobuf_read + MPEG_RESERVED_HEADER_SPACE);
2245 /* And the top half */
2246 audiobuf_read += audiobuflen;
2247 memset(audiobuf + audiobuf_read, 0, audiobuflen - audiobuf_read);
2249 else
2251 memset(audiobuf + audiobuf_read, 0, MPEG_RESERVED_HEADER_SPACE);
2253 /* Copy the empty ID3 header */
2254 startpos = audiobuf_read;
2255 for(i = 0; i < sizeof(empty_id3_header); i++)
2257 audiobuf[startpos++] = empty_id3_header[i];
2258 if(startpos == audiobuflen)
2259 startpos = 0;
2263 static void update_header(void)
2265 int fd, framelen;
2266 unsigned long frames;
2268 if (last_rec_bytes > 0)
2270 /* Create the Xing header */
2271 fd = open(delayed_filename, O_RDWR);
2272 if (fd < 0)
2273 panicf("rec upd: %d (%s)", fd, recording_filename);
2275 frames = frame_count_end - frame_count_start;
2276 /* If the number of recorded frames has reached 0x7ffff,
2277 we can no longer trust it */
2278 if (frame_count_end == 0x7ffff)
2279 frames = 0;
2281 /* saved_header is saved right before stopping the MAS */
2282 framelen = create_xing_header(fd, 0, last_rec_bytes, xing_buffer,
2283 frames, last_rec_time * (1000/HZ),
2284 saved_header, NULL, false);
2286 lseek(fd, MPEG_RESERVED_HEADER_SPACE - framelen, SEEK_SET);
2287 write(fd, xing_buffer, framelen);
2288 close(fd);
2292 static void start_prerecording(void)
2294 unsigned long val;
2296 DEBUGF("Starting prerecording\n");
2298 prerecord_index = 0;
2299 prerecord_count = 0;
2300 prerecord_timeout = current_tick + HZ;
2301 memset(prerecord_buffer, 0, sizeof(prerecord_buffer));
2302 reset_mp3_buffer();
2304 is_prerecording = true;
2306 /* Stop monitoring and start the encoder */
2307 shadow_io_control_main &= ~(1 << 10);
2308 mas_writemem(MAS_BANK_D0, MAS_D0_IO_CONTROL_MAIN, &shadow_io_control_main, 1);
2309 DEBUGF("mas_writemem(MAS_BANK_D0, IO_CONTROL_MAIN, %x)\n", shadow_io_control_main);
2311 /* Wait until the DSP has accepted the settings */
2314 mas_readmem(MAS_BANK_D0, MAS_D0_IO_CONTROL_MAIN, &val,1);
2315 } while(val & 1);
2317 is_recording = true;
2318 saving_status = NOT_SAVING;
2320 demand_irq_enable(true);
2323 static void start_recording(void)
2325 unsigned long val;
2327 if(is_prerecording)
2329 /* This will make the IRQ handler start recording
2330 for real, i.e send MPEG_SAVE_DATA messages when
2331 the buffer is full */
2332 is_prerecording = false;
2334 else
2336 /* If prerecording is off, we need to stop the monitoring
2337 and start the encoder */
2338 shadow_io_control_main &= ~(1 << 10);
2339 mas_writemem(MAS_BANK_D0, MAS_D0_IO_CONTROL_MAIN, &shadow_io_control_main, 1);
2340 DEBUGF("mas_writemem(MAS_BANK_D0, IO_CONTROL_MAIN, %x)\n", shadow_io_control_main);
2342 /* Wait until the DSP has accepted the settings */
2345 mas_readmem(MAS_BANK_D0, MAS_D0_IO_CONTROL_MAIN, &val,1);
2346 } while(val & 1);
2349 is_recording = true;
2350 saving_status = NOT_SAVING;
2351 paused = false;
2353 /* Store the current time */
2354 if(prerecording)
2355 record_start_time = current_tick - prerecord_count * HZ;
2356 else
2357 record_start_time = current_tick;
2359 pause_start_time = 0;
2361 demand_irq_enable(true);
2364 static void pause_recording(void)
2366 pause_start_time = current_tick;
2368 /* Set the pause bit */
2369 shadow_soft_mute |= 2;
2370 mas_writemem(MAS_BANK_D0, MAS_D0_SOFT_MUTE, &shadow_soft_mute, 1);
2372 paused = true;
2375 static void resume_recording(void)
2377 paused = false;
2379 /* Clear the pause bit */
2380 shadow_soft_mute &= ~2;
2381 mas_writemem(MAS_BANK_D0, MAS_D0_SOFT_MUTE, &shadow_soft_mute, 1);
2383 /* Compensate for the time we have been paused */
2384 if(pause_start_time)
2386 record_start_time =
2387 current_tick - (pause_start_time - record_start_time);
2388 pause_start_time = 0;
2392 static void stop_recording(void)
2394 unsigned long val;
2396 /* Let it finish the last frame */
2397 if(!paused)
2398 pause_recording();
2399 sleep(HZ/5);
2401 demand_irq_enable(false);
2403 is_recording = false;
2404 is_prerecording = false;
2406 last_rec_bytes = num_rec_bytes;
2407 mas_readmem(MAS_BANK_D0, MAS_D0_MPEG_FRAME_COUNT, &frame_count_end, 1);
2408 last_rec_time = current_tick - record_start_time;
2410 /* Start monitoring */
2411 shadow_io_control_main |= (1 << 10);
2412 mas_writemem(MAS_BANK_D0, MAS_D0_IO_CONTROL_MAIN, &shadow_io_control_main, 1);
2413 DEBUGF("mas_writemem(MAS_BANK_D0, IO_CONTROL_MAIN, %x)\n", shadow_io_control_main);
2415 /* Wait until the DSP has accepted the settings */
2418 mas_readmem(MAS_BANK_D0, MAS_D0_IO_CONTROL_MAIN, &val,1);
2419 } while(val & 1);
2421 resume_recording();
2424 void audio_set_recording_options(struct audio_recording_options *options)
2426 bool is_mpeg1;
2428 is_mpeg1 = (options->rec_frequency < 3)?true:false;
2430 rec_version_index = is_mpeg1?3:2;
2431 rec_frequency_index = options->rec_frequency % 3;
2433 shadow_encoder_control = (options->rec_quality << 17) |
2434 (rec_frequency_index << 10) |
2435 ((is_mpeg1?1:0) << 9) |
2436 (((options->rec_channels * 2 + 1) & 3) << 6) |
2437 (1 << 5) /* MS-stereo */ |
2438 (1 << 2) /* Is an original */;
2439 mas_writemem(MAS_BANK_D0, MAS_D0_ENCODER_CONTROL, &shadow_encoder_control,1);
2441 DEBUGF("mas_writemem(MAS_BANK_D0, ENCODER_CONTROL, %x)\n", shadow_encoder_control);
2443 #if CONFIG_TUNER & S1A0903X01
2444 /* Store the (unpitched) MAS PLL frequency. Used for avoiding FM
2445 interference with the Samsung tuner. */
2446 if (rec_frequency_index)
2447 mas_store_pllfreq(24576000);
2448 else
2449 mas_store_pllfreq(22579000);
2450 #endif
2452 shadow_soft_mute = options->rec_editable?4:0;
2453 mas_writemem(MAS_BANK_D0, MAS_D0_SOFT_MUTE, &shadow_soft_mute,1);
2455 DEBUGF("mas_writemem(MAS_BANK_D0, SOFT_MUTE, %x)\n", shadow_soft_mute);
2457 shadow_io_control_main = ((1 << 10) | /* Monitoring ON */
2458 ((options->rec_source < 2)?1:2) << 8) | /* Input select */
2459 (1 << 5) | /* SDO strobe invert */
2460 ((is_mpeg1?0:1) << 3) |
2461 (1 << 2) | /* Inverted SIBC clock signal */
2462 1; /* Validate */
2463 mas_writemem(MAS_BANK_D0, MAS_D0_IO_CONTROL_MAIN, &shadow_io_control_main,1);
2465 DEBUGF("mas_writemem(MAS_BANK_D0, IO_CONTROL_MAIN, %x)\n", shadow_io_control_main);
2467 if(options->rec_source == AUDIO_SRC_MIC)
2469 /* Copy left channel to right (mono mode) */
2470 mas_codec_writereg(8, 0x8000);
2472 else
2474 /* Stereo input mode */
2475 mas_codec_writereg(8, 0);
2478 prerecording_max_seconds = options->rec_prerecord_time;
2479 if(prerecording_max_seconds)
2481 prerecording = true;
2482 start_prerecording();
2484 else
2486 prerecording = false;
2487 is_prerecording = false;
2488 is_recording = false;
2492 /* If use_mic is true, the left gain is used */
2493 void audio_set_recording_gain(int left, int right, int type)
2495 /* Enable both left and right A/D */
2496 shadow_codec_reg0 = (left << 12) |
2497 (right << 8) |
2498 (left << 4) |
2499 (type==AUDIO_GAIN_MIC?0x0008:0) | /* Connect left A/D to mic */
2500 0x0007;
2501 mas_codec_writereg(0x0, shadow_codec_reg0);
2504 /* try to make some kind of beep, also in recording mode */
2505 void audio_beep(int duration)
2507 long starttick = current_tick;
2509 { /* toggle bit 0 of codec register 0, toggling the DAC off & on.
2510 * While this is still audible even without an external signal,
2511 * it doesn't affect the (pre-)recording. */
2512 mas_codec_writereg(0, shadow_codec_reg0 ^ 1);
2513 mas_codec_writereg(0, shadow_codec_reg0);
2514 yield();
2516 while (current_tick - starttick < duration);
2519 void audio_new_file(const char *filename)
2521 mpeg_errno = 0;
2523 strncpy(recording_filename, filename, MAX_PATH - 1);
2524 recording_filename[MAX_PATH - 1] = 0;
2526 queue_post(&mpeg_queue, MPEG_NEW_FILE, 0);
2529 unsigned long audio_recorded_time(void)
2531 if(is_prerecording)
2532 return prerecord_count * HZ;
2534 if(is_recording)
2536 if(paused)
2537 return pause_start_time - record_start_time;
2538 else
2539 return current_tick - record_start_time;
2542 return 0;
2545 unsigned long audio_num_recorded_bytes(void)
2547 int num_bytes;
2548 int index;
2550 if(is_recording)
2552 if(is_prerecording)
2554 index = prerecord_index - prerecord_count;
2555 if(index < 0)
2556 index += prerecording_max_seconds;
2558 num_bytes = audiobuf_write - prerecord_buffer[index].mempos;
2559 if(num_bytes < 0)
2560 num_bytes += audiobuflen;
2562 return num_bytes;
2564 else
2565 return num_rec_bytes;
2567 else
2568 return 0;
2571 #else /* SIMULATOR */
2573 /* dummies coming up */
2575 void audio_init_playback(void)
2577 /* a dummy */
2579 unsigned long audio_recorded_time(void)
2581 /* a dummy */
2582 return 0;
2584 void audio_beep(int duration)
2586 /* a dummy */
2587 (void)duration;
2589 void audio_pause_recording(void)
2591 /* a dummy */
2593 void audio_resume_recording(void)
2595 /* a dummy */
2597 unsigned long audio_num_recorded_bytes(void)
2599 /* a dummy */
2600 return 0;
2602 void audio_record(const char *filename)
2604 /* a dummy */
2605 (void)filename;
2607 void audio_new_file(const char *filename)
2609 /* a dummy */
2610 (void)filename;
2613 void audio_set_recording_gain(int left, int right, int type)
2615 /* a dummy */
2616 (void)left;
2617 (void)right;
2618 (void)type;
2620 void audio_init_recording(unsigned int buffer_offset)
2622 /* a dummy */
2623 (void)buffer_offset;
2625 void audio_set_recording_options(struct audio_recording_options *options)
2627 /* a dummy */
2628 (void)options;
2630 #endif /* SIMULATOR */
2631 #endif /* CONFIG_CODEC == MAS3587F */
2633 void audio_play(long offset)
2635 #ifdef SIMULATOR
2636 char* trackname;
2637 int steps=0;
2639 is_playing = true;
2641 do {
2642 trackname = playlist_peek( steps );
2643 if (!trackname)
2644 break;
2645 if(mp3info(&taginfo, trackname)) {
2646 /* bad mp3, move on */
2647 if(++steps > playlist_amount())
2648 break;
2649 continue;
2651 #ifdef HAVE_MPEG_PLAY
2652 real_mpeg_play(trackname);
2653 #endif
2654 playlist_next(steps);
2655 taginfo.offset = offset;
2656 set_elapsed(&taginfo);
2657 is_playing = true;
2658 playing = true;
2659 break;
2660 } while(1);
2661 #else /* !SIMULATOR */
2662 is_playing = true;
2664 queue_post(&mpeg_queue, MPEG_PLAY, offset);
2665 #endif /* !SIMULATOR */
2667 mpeg_errno = 0;
2670 void audio_stop(void)
2672 #ifndef SIMULATOR
2673 if (playing)
2675 struct trackdata *track = get_trackdata(0);
2676 prev_track_elapsed = track->id3.elapsed;
2678 mpeg_stop_done = false;
2679 queue_post(&mpeg_queue, MPEG_STOP, 0);
2680 while(!mpeg_stop_done)
2681 yield();
2682 #else /* SIMULATOR */
2683 paused = false;
2684 is_playing = false;
2685 playing = false;
2686 #endif /* SIMULATOR */
2689 /* dummy */
2690 void audio_stop_recording(void)
2692 audio_stop();
2695 void audio_pause(void)
2697 #ifndef SIMULATOR
2698 queue_post(&mpeg_queue, MPEG_PAUSE, 0);
2699 #else /* SIMULATOR */
2700 is_playing = true;
2701 playing = false;
2702 paused = true;
2703 #endif /* SIMULATOR */
2706 void audio_resume(void)
2708 #ifndef SIMULATOR
2709 queue_post(&mpeg_queue, MPEG_RESUME, 0);
2710 #else /* SIMULATOR */
2711 is_playing = true;
2712 playing = true;
2713 paused = false;
2714 #endif /* SIMULATOR */
2717 void audio_next(void)
2719 #ifndef SIMULATOR
2720 queue_remove_from_head(&mpeg_queue, MPEG_NEED_DATA);
2721 queue_post(&mpeg_queue, MPEG_NEXT, 0);
2722 #else /* SIMULATOR */
2723 char* file;
2724 int steps = 1;
2725 int index;
2727 do {
2728 file = playlist_peek(steps);
2729 if(!file)
2730 break;
2731 if(mp3info(&taginfo, file)) {
2732 if(++steps > playlist_amount())
2733 break;
2734 continue;
2736 index = playlist_next(steps);
2737 taginfo.index = index;
2738 current_track_counter++;
2739 is_playing = true;
2740 playing = true;
2741 break;
2742 } while(1);
2743 #endif /* SIMULATOR */
2746 void audio_prev(void)
2748 #ifndef SIMULATOR
2749 queue_remove_from_head(&mpeg_queue, MPEG_NEED_DATA);
2750 queue_post(&mpeg_queue, MPEG_PREV, 0);
2751 #else /* SIMULATOR */
2752 char* file;
2753 int steps = -1;
2754 int index;
2756 do {
2757 file = playlist_peek(steps);
2758 if(!file)
2759 break;
2760 if(mp3info(&taginfo, file)) {
2761 steps--;
2762 continue;
2764 index = playlist_next(steps);
2765 taginfo.index = index;
2766 current_track_counter++;
2767 is_playing = true;
2768 playing = true;
2769 break;
2770 } while(1);
2771 #endif /* SIMULATOR */
2774 void audio_ff_rewind(long newtime)
2776 #ifndef SIMULATOR
2777 queue_post(&mpeg_queue, MPEG_FF_REWIND, newtime);
2778 #else /* SIMULATOR */
2779 (void)newtime;
2780 #endif /* SIMULATOR */
2783 void audio_flush_and_reload_tracks(void)
2785 #ifndef SIMULATOR
2786 queue_post(&mpeg_queue, MPEG_FLUSH_RELOAD, 0);
2787 #endif /* !SIMULATOR*/
2790 int audio_status(void)
2792 int ret = 0;
2794 if(is_playing)
2795 ret |= AUDIO_STATUS_PLAY;
2797 if(paused)
2798 ret |= AUDIO_STATUS_PAUSE;
2800 #if (CONFIG_CODEC == MAS3587F) && !defined(SIMULATOR)
2801 if(is_recording && !is_prerecording)
2802 ret |= AUDIO_STATUS_RECORD;
2804 if(is_prerecording)
2805 ret |= AUDIO_STATUS_PRERECORD;
2806 #endif /* CONFIG_CODEC == MAS3587F */
2808 if(mpeg_errno)
2809 ret |= AUDIO_STATUS_ERROR;
2811 return ret;
2814 unsigned int audio_error(void)
2816 return mpeg_errno;
2819 void audio_error_clear(void)
2821 mpeg_errno = 0;
2824 #ifdef SIMULATOR
2825 static void mpeg_thread(void)
2827 struct mp3entry* id3;
2828 while ( 1 ) {
2829 if (is_playing) {
2830 id3 = audio_current_track();
2831 if (!paused)
2833 id3->elapsed+=1000;
2834 id3->offset+=1000;
2836 if (id3->elapsed>=id3->length)
2837 audio_next();
2839 sleep(HZ);
2842 #endif /* SIMULATOR */
2844 void audio_init(void)
2846 mpeg_errno = 0;
2848 #ifndef SIMULATOR
2849 audiobuflen = audiobufend - audiobuf;
2850 queue_init(&mpeg_queue, true);
2851 #endif /* !SIMULATOR */
2852 create_thread(mpeg_thread, mpeg_stack,
2853 sizeof(mpeg_stack), 0, mpeg_thread_name
2854 IF_PRIO(, PRIORITY_SYSTEM)
2855 IF_COP(, CPU));
2857 memset(trackdata, 0, sizeof(trackdata));
2859 #if (CONFIG_CODEC == MAS3587F) && !defined(SIMULATOR)
2860 if (HW_MASK & PR_ACTIVE_HIGH)
2861 and_b(~0x08, &PADRH);
2862 else
2863 or_b(0x08, &PADRH);
2864 #endif /* CONFIG_CODEC == MAS3587F */
2866 #ifdef DEBUG
2867 #ifndef SIMULATOR
2868 dbg_timer_start();
2869 dbg_cnt2us(0);
2870 #endif /* !SIMULATOR */
2871 #endif /* DEBUG */
2874 #endif /* CONFIG_CODEC != SWCODEC */