Update the manual for the new file extension setting
[maemo-rb.git] / firmware / mpeg.c
blob278eea475829cf7d50ce9f00f2594796abd8a81b
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;
103 bool event_sent;
106 static struct trackdata trackdata[MAX_TRACK_ENTRIES];
108 static unsigned int current_track_counter = 0;
109 static unsigned int last_track_counter = 0;
111 /* Play time of the previous track */
112 unsigned long prev_track_elapsed;
114 #ifndef SIMULATOR
115 static int track_read_idx = 0;
116 static int track_write_idx = 0;
117 #endif /* !SIMULATOR */
119 /* Callback function to call when current track has really changed. */
120 void (*track_changed_callback)(struct mp3entry *id3);
121 void (*track_buffer_callback)(struct mp3entry *id3, bool last_track);
122 void (*track_unbuffer_callback)(struct mp3entry *id3, bool last_track);
124 /* Cuesheet callback */
125 static bool (*cuesheet_callback)(const char *filename) = NULL;
127 static const char mpeg_thread_name[] = "mpeg";
128 static unsigned int mpeg_errno;
130 static bool v1first = false;
132 static bool playing = false; /* We are playing an MP3 stream */
133 static bool is_playing = false; /* We are (attempting to) playing MP3 files */
134 static bool paused; /* playback is paused */
136 #ifdef SIMULATOR
137 static char mpeg_stack[DEFAULT_STACK_SIZE];
138 static struct mp3entry taginfo;
140 #else /* !SIMULATOR */
141 static struct event_queue mpeg_queue;
142 static long mpeg_stack[(DEFAULT_STACK_SIZE + 0x1000)/sizeof(long)];
144 static int audiobuflen;
145 static int audiobuf_write;
146 static int audiobuf_swapwrite;
147 static int audiobuf_read;
149 static int mpeg_file;
151 static bool play_pending; /* We are about to start playing */
152 static bool filling; /* We are filling the buffer with data from disk */
153 static bool dma_underrun; /* True when the DMA has stopped because of
154 slow disk reading (read error, shaking) */
155 static bool mpeg_stop_done;
157 static int last_dma_tick = 0;
158 static int last_dma_chunk_size;
160 static long low_watermark; /* Dynamic low watermark level */
161 static long low_watermark_margin = 0; /* Extra time in seconds for watermark */
162 static long lowest_watermark_level; /* Debug value to observe the buffer
163 usage */
164 #if CONFIG_CODEC == MAS3587F
165 static char recording_filename[MAX_PATH]; /* argument to thread */
166 static char delayed_filename[MAX_PATH]; /* internal copy of above */
168 static char xing_buffer[MAX_XING_HEADER_SIZE];
170 static bool init_recording_done;
171 static bool init_playback_done;
172 static bool prerecording; /* True if prerecording is enabled */
173 static bool is_prerecording; /* True if we are prerecording */
174 static bool is_recording; /* We are recording */
176 static enum {
177 NOT_SAVING = 0, /* reasons to save data, sorted by importance */
178 BUFFER_FULL,
179 NEW_FILE,
180 STOP_RECORDING
181 } saving_status;
183 static int rec_frequency_index; /* For create_xing_header() calls */
184 static int rec_version_index; /* For create_xing_header() calls */
186 struct prerecord_info {
187 int mempos;
188 unsigned long framecount;
191 static struct prerecord_info prerecord_buffer[MPEG_MAX_PRERECORD_SECONDS];
192 static int prerecord_index; /* Current index in the prerecord buffer */
193 static int prerecording_max_seconds; /* Max number of seconds to store */
194 static int prerecord_count; /* Number of seconds in the prerecord buffer */
195 static int prerecord_timeout; /* The tick count of the next prerecord data
196 store */
198 unsigned long record_start_time; /* Value of current_tick when recording
199 was started */
200 unsigned long pause_start_time; /* Value of current_tick when pause was
201 started */
202 static unsigned long last_rec_time;
203 static unsigned long num_rec_bytes;
204 static unsigned long last_rec_bytes;
205 static unsigned long frame_count_start;
206 static unsigned long frame_count_end;
207 static unsigned long saved_header = 0;
209 /* Shadow MAS registers */
210 unsigned long shadow_encoder_control = 0;
211 #endif /* CONFIG_CODEC == MAS3587F */
213 #if (CONFIG_CODEC == MAS3587F) || (CONFIG_CODEC == MAS3539F)
214 unsigned long shadow_io_control_main = 0;
215 unsigned long shadow_soft_mute = 0;
216 unsigned shadow_codec_reg0;
217 #endif /* (CONFIG_CODEC == MAS3587F) || (CONFIG_CODEC == MAS3539F) */
219 #ifdef HAVE_RECORDING
220 const unsigned char empty_id3_header[] =
222 'I', 'D', '3', 0x03, 0x00, 0x00,
223 0x00, 0x00, 0x1f, 0x76 /* Size is 4096 minus 10 bytes for the header */
225 #endif /* HAVE_RECORDING */
228 static int get_unplayed_space(void);
229 static int get_playable_space(void);
230 static int get_unswapped_space(void);
231 #endif /* !SIMULATOR */
233 #if (CONFIG_CODEC == MAS3587F) && !defined(SIMULATOR)
234 static void init_recording(void);
235 static void prepend_header(void);
236 static void update_header(void);
237 static void start_prerecording(void);
238 static void start_recording(void);
239 static void stop_recording(void);
240 static int get_unsaved_space(void);
241 static void pause_recording(void);
242 static void resume_recording(void);
243 #endif /* (CONFIG_CODEC == MAS3587F) && !defined(SIMULATOR) */
246 #ifndef SIMULATOR
247 static int num_tracks_in_memory(void)
249 return (track_write_idx - track_read_idx) & MAX_TRACK_ENTRIES_MASK;
252 #ifdef DEBUG_TAGS
253 static void debug_tags(void)
255 int i;
257 for(i = 0;i < MAX_TRACK_ENTRIES;i++)
259 DEBUGF("%d - %s\n", i, trackdata[i].id3.path);
261 DEBUGF("read: %d, write :%d\n", track_read_idx, track_write_idx);
262 DEBUGF("num_tracks_in_memory: %d\n", num_tracks_in_memory());
264 #else /* !DEBUG_TAGS */
265 #define debug_tags()
266 #endif /* !DEBUG_TAGS */
268 static void remove_current_tag(void)
270 if(num_tracks_in_memory() > 0)
272 /* First move the index, so nobody tries to access the tag */
273 track_read_idx = (track_read_idx+1) & MAX_TRACK_ENTRIES_MASK;
274 debug_tags();
276 else
278 DEBUGF("remove_current_tag: no tracks to remove\n");
282 static void remove_all_non_current_tags(void)
284 track_write_idx = (track_read_idx+1) & MAX_TRACK_ENTRIES_MASK;
285 debug_tags();
288 static void remove_all_tags(void)
290 track_write_idx = track_read_idx;
292 debug_tags();
295 static struct trackdata *get_trackdata(int offset)
297 if(offset >= num_tracks_in_memory())
298 return NULL;
299 else
300 return &trackdata[(track_read_idx + offset) & MAX_TRACK_ENTRIES_MASK];
302 #endif /* !SIMULATOR */
304 /***********************************************************************/
305 /* audio event handling */
307 #define MAX_EVENT_HANDLERS 10
308 struct event_handlers_table
310 AUDIO_EVENT_HANDLER handler;
311 unsigned short mask;
313 static struct event_handlers_table event_handlers[MAX_EVENT_HANDLERS];
314 static int event_handlers_count = 0;
316 void audio_register_event_handler(AUDIO_EVENT_HANDLER handler, unsigned short mask)
318 if (event_handlers_count < MAX_EVENT_HANDLERS)
320 event_handlers[event_handlers_count].handler = handler;
321 event_handlers[event_handlers_count].mask = mask;
322 event_handlers_count++;
326 /* dispatch calls each handler in the order registered and returns after some
327 handler actually handles the event (the event is assumed to no longer be valid
328 after this, due to the handler changing some condition); returns true if someone
329 handled the event, which is expected to cause the caller to skip its own handling
330 of the event */
331 #ifndef SIMULATOR
332 static bool audio_dispatch_event(unsigned short event, unsigned long data)
334 int i = 0;
335 for(i=0; i < event_handlers_count; i++)
337 if ( event_handlers[i].mask & event )
339 int rc = event_handlers[i].handler(event, data);
340 if ( rc == AUDIO_EVENT_RC_HANDLED )
341 return true;
344 return false;
346 #endif
348 /***********************************************************************/
350 static void set_elapsed(struct mp3entry* id3)
352 if ( id3->vbr ) {
353 if ( id3->has_toc ) {
354 /* calculate elapsed time using TOC */
355 int i;
356 unsigned int remainder, plen, relpos, nextpos;
358 /* find wich percent we're at */
359 for (i=0; i<100; i++ )
361 if ( id3->offset < id3->toc[i] * (id3->filesize / 256) )
363 break;
367 i--;
368 if (i < 0)
369 i = 0;
371 relpos = id3->toc[i];
373 if (i < 99)
375 nextpos = id3->toc[i+1];
377 else
379 nextpos = 256;
382 remainder = id3->offset - (relpos * (id3->filesize / 256));
384 /* set time for this percent (divide before multiply to prevent
385 overflow on long files. loss of precision is negligible on
386 short files) */
387 id3->elapsed = i * (id3->length / 100);
389 /* calculate remainder time */
390 plen = (nextpos - relpos) * (id3->filesize / 256);
391 id3->elapsed += (((remainder * 100) / plen) *
392 (id3->length / 10000));
394 else {
395 /* no TOC exists. set a rough estimate using average bitrate */
396 int tpk = id3->length / (id3->filesize / 1024);
397 id3->elapsed = id3->offset / 1024 * tpk;
400 else
401 /* constant bitrate, use exact calculation */
402 id3->elapsed = id3->offset / (id3->bitrate / 8);
405 int audio_get_file_pos(void)
407 int pos = -1;
408 struct mp3entry *id3 = audio_current_track();
410 if (id3->vbr)
412 if (id3->has_toc)
414 /* Use the TOC to find the new position */
415 unsigned int percent, remainder;
416 int curtoc, nexttoc, plen;
418 percent = (id3->elapsed*100)/id3->length;
419 if (percent > 99)
420 percent = 99;
422 curtoc = id3->toc[percent];
424 if (percent < 99)
425 nexttoc = id3->toc[percent+1];
426 else
427 nexttoc = 256;
429 pos = (id3->filesize/256)*curtoc;
431 /* Use the remainder to get a more accurate position */
432 remainder = (id3->elapsed*100)%id3->length;
433 remainder = (remainder*100)/id3->length;
434 plen = (nexttoc - curtoc)*(id3->filesize/256);
435 pos += (plen/100)*remainder;
437 else
439 /* No TOC exists, estimate the new position */
440 pos = (id3->filesize / (id3->length / 1000)) *
441 (id3->elapsed / 1000);
444 else if (id3->bitrate)
445 pos = id3->elapsed * (id3->bitrate / 8);
446 else
448 return -1;
451 if (pos >= (int)(id3->filesize - id3->id3v1len))
453 /* Don't seek right to the end of the file so that we can
454 transition properly to the next song */
455 pos = id3->filesize - id3->id3v1len - 1;
457 else if (pos < (int)id3->first_frame_offset)
459 /* skip past id3v2 tag and other leading garbage */
460 pos = id3->first_frame_offset;
462 return pos;
465 unsigned long mpeg_get_last_header(void)
467 #ifdef SIMULATOR
468 return 0;
469 #else /* !SIMULATOR */
470 unsigned long tmp[2];
472 /* Read the frame data from the MAS and reconstruct it with the
473 frame sync and all */
474 mas_readmem(MAS_BANK_D0, MAS_D0_MPEG_STATUS_1, tmp, 2);
475 return 0xffe00000 | ((tmp[0] & 0x7c00) << 6) | (tmp[1] & 0xffff);
476 #endif /* !SIMULATOR */
479 void audio_set_track_buffer_event(void (*handler)(struct mp3entry *id3,
480 bool last_track))
482 track_buffer_callback = handler;
485 void audio_set_track_unbuffer_event(void (*handler)(struct mp3entry *id3,
486 bool last_track))
488 track_unbuffer_callback = handler;
491 void audio_set_track_changed_event(void (*handler)(struct mp3entry *id3))
493 track_changed_callback = handler;
496 void audio_set_cuesheet_callback(bool (*handler)(const char *filename))
498 cuesheet_callback = handler;
501 #ifndef SIMULATOR
502 /* Send callback events to notify about removing old tracks. */
503 static void generate_unbuffer_events(void)
505 int i;
506 int event_count = 0;
507 int numentries = MAX_TRACK_ENTRIES - num_tracks_in_memory();
508 int cur_idx = track_write_idx;
510 for (i = 0; i < numentries; i++)
512 if (trackdata[cur_idx].event_sent)
513 event_count++;
515 cur_idx = (cur_idx + 1) & MAX_TRACK_ENTRIES_MASK;
518 cur_idx = track_write_idx;
520 for (i = 0; i < numentries; i++)
522 /* Send an event to notify that track has finished. */
523 if (trackdata[cur_idx].event_sent)
525 event_count--;
526 if (track_unbuffer_callback)
527 track_unbuffer_callback(&trackdata[cur_idx].id3,
528 event_count == 0);
529 trackdata[cur_idx].event_sent = false;
531 cur_idx = (cur_idx + 1) & MAX_TRACK_ENTRIES_MASK;
535 /* Send callback events to notify about new tracks. */
536 static void generate_postbuffer_events(void)
538 int i;
539 int event_count = 0;
540 int numentries = num_tracks_in_memory();
541 int cur_idx = track_read_idx;
543 for (i = 0; i < numentries; i++)
545 if (!trackdata[cur_idx].event_sent)
546 event_count++;
548 cur_idx = (cur_idx + 1) & MAX_TRACK_ENTRIES_MASK;
551 cur_idx = track_read_idx;
553 for (i = 0; i < numentries; i++)
555 if (!trackdata[cur_idx].event_sent)
557 event_count--;
558 if (track_buffer_callback)
559 track_buffer_callback(&trackdata[cur_idx].id3,
560 event_count == 0);
561 trackdata[cur_idx].event_sent = true;
563 cur_idx = (cur_idx + 1) & MAX_TRACK_ENTRIES_MASK;
567 static void recalculate_watermark(int bitrate)
569 int bytes_per_sec;
570 int time = ata_spinup_time;
572 /* A bitrate of 0 probably means empty VBR header. We play safe
573 and set a high threshold */
574 if(bitrate == 0)
575 bitrate = 320;
577 bytes_per_sec = bitrate * 1000 / 8;
579 if(time)
581 /* No drive spins up faster than 3.5s */
582 if(time < 350)
583 time = 350;
585 time = time * 3;
586 low_watermark = ((low_watermark_margin * HZ + time) *
587 bytes_per_sec) / HZ;
589 else
591 low_watermark = MPEG_LOW_WATER;
595 #ifndef HAVE_FLASH_STORAGE
596 void audio_set_buffer_margin(int seconds)
598 low_watermark_margin = seconds;
600 #endif
602 void audio_get_debugdata(struct audio_debug *dbgdata)
604 dbgdata->audiobuflen = audiobuflen;
605 dbgdata->audiobuf_write = audiobuf_write;
606 dbgdata->audiobuf_swapwrite = audiobuf_swapwrite;
607 dbgdata->audiobuf_read = audiobuf_read;
609 dbgdata->last_dma_chunk_size = last_dma_chunk_size;
611 #if CONFIG_CPU == SH7034
612 dbgdata->dma_on = (SCR0 & 0x80) != 0;
613 #endif
614 dbgdata->playing = playing;
615 dbgdata->play_pending = play_pending;
616 dbgdata->is_playing = is_playing;
617 dbgdata->filling = filling;
618 dbgdata->dma_underrun = dma_underrun;
620 dbgdata->unplayed_space = get_unplayed_space();
621 dbgdata->playable_space = get_playable_space();
622 dbgdata->unswapped_space = get_unswapped_space();
624 dbgdata->low_watermark_level = low_watermark;
625 dbgdata->lowest_watermark_level = lowest_watermark_level;
628 #ifdef DEBUG
629 static void dbg_timer_start(void)
631 /* We are using timer 2 */
633 TSTR &= ~0x04; /* Stop the timer */
634 TSNC &= ~0x04; /* No synchronization */
635 TMDR &= ~0x44; /* Operate normally */
637 TCNT2 = 0; /* Start counting at 0 */
638 TCR2 = 0x03; /* Sysclock/8 */
640 TSTR |= 0x04; /* Start timer 2 */
643 static int dbg_cnt2us(unsigned int cnt)
645 return (cnt * 10000) / (FREQ/800);
647 #endif /* DEBUG */
649 static int get_unplayed_space(void)
651 int space = audiobuf_write - audiobuf_read;
652 if (space < 0)
653 space += audiobuflen;
654 return space;
657 static int get_playable_space(void)
659 int space = audiobuf_swapwrite - audiobuf_read;
660 if (space < 0)
661 space += audiobuflen;
662 return space;
665 static int get_unplayed_space_current_song(void)
667 int space;
669 if (num_tracks_in_memory() > 1)
671 space = get_trackdata(1)->mempos - audiobuf_read;
673 else
675 space = audiobuf_write - audiobuf_read;
678 if (space < 0)
679 space += audiobuflen;
681 return space;
684 static int get_unswapped_space(void)
686 int space = audiobuf_write - audiobuf_swapwrite;
687 if (space < 0)
688 space += audiobuflen;
689 return space;
692 #if CONFIG_CODEC == MAS3587F
693 static int get_unsaved_space(void)
695 int space = audiobuf_write - audiobuf_read;
696 if (space < 0)
697 space += audiobuflen;
698 return space;
701 static void drain_dma_buffer(void)
703 while (PBDRH & 0x40)
705 xor_b(0x08, &PADRH);
707 while (PBDRH & 0x80);
709 xor_b(0x08, &PADRH);
711 while (!(PBDRH & 0x80));
715 #ifdef DEBUG
716 static long timing_info_index = 0;
717 static long timing_info[1024];
718 #endif /* DEBUG */
720 void rec_tick (void) __attribute__ ((section (".icode")));
721 void rec_tick(void)
723 int i;
724 int delay;
725 char data;
727 if(is_recording && (PBDRH & 0x40))
729 #ifdef DEBUG
730 timing_info[timing_info_index++] = current_tick;
731 TCNT2 = 0;
732 #endif /* DEBUG */
733 /* Note: Although this loop is run in interrupt context, further
734 * optimisation will do no good. The MAS would then deliver bad
735 * frames occasionally, as observed in extended experiments. */
736 i = 0;
737 while (PBDRH & 0x40) /* We try to read as long as EOD is high */
739 xor_b(0x08, &PADRH); /* Set PR active, independent of polarity */
741 delay = 100;
742 while (PBDRH & 0x80) /* Wait until /RTW becomes active */
744 if (--delay <= 0) /* Bail out if we have to wait too long */
745 { /* i.e. the MAS doesn't want to talk to us */
746 xor_b(0x08, &PADRH); /* Set PR inactive */
747 goto transfer_end; /* and get out of here */
751 data = *(unsigned char *)0x04000000; /* read data byte */
753 xor_b(0x08, &PADRH); /* Set PR inactive */
755 audiobuf[audiobuf_write++] = data;
757 if (audiobuf_write >= audiobuflen)
758 audiobuf_write = 0;
760 i++;
762 transfer_end:
764 #ifdef DEBUG
765 timing_info[timing_info_index++] = TCNT2 + (i << 16);
766 timing_info_index &= 0x3ff;
767 #endif /* DEBUG */
769 num_rec_bytes += i;
771 if(is_prerecording)
773 if(TIME_AFTER(current_tick, prerecord_timeout))
775 prerecord_timeout = current_tick + HZ;
776 queue_post(&mpeg_queue, MPEG_PRERECORDING_TICK, 0);
779 else
781 /* Signal to save the data if we are running out of buffer
782 space */
783 if (audiobuflen - get_unsaved_space() < MPEG_RECORDING_LOW_WATER
784 && saving_status == NOT_SAVING)
786 saving_status = BUFFER_FULL;
787 queue_post(&mpeg_queue, MPEG_SAVE_DATA, 0);
792 #endif /* CONFIG_CODEC == MAS3587F */
794 void playback_tick(void)
796 struct trackdata *ptd = get_trackdata(0);
797 if(ptd)
799 ptd->id3.elapsed += (current_tick - last_dma_tick) * 1000 / HZ;
800 last_dma_tick = current_tick;
801 audio_dispatch_event(AUDIO_EVENT_POS_REPORT,
802 (unsigned long)ptd->id3.elapsed);
806 static void reset_mp3_buffer(void)
808 audiobuf_read = 0;
809 audiobuf_write = 0;
810 audiobuf_swapwrite = 0;
811 lowest_watermark_level = audiobuflen;
814 /* DMA transfer end interrupt callback */
815 static void transfer_end(unsigned char** ppbuf, size_t* psize)
817 if(playing && !paused)
819 int unplayed_space_left;
820 int space_until_end_of_buffer;
821 int track_offset = 1;
822 struct trackdata *track;
824 audiobuf_read += last_dma_chunk_size;
825 if(audiobuf_read >= audiobuflen)
826 audiobuf_read = 0;
828 /* First, check if we are on a track boundary */
829 if (num_tracks_in_memory() > 1)
831 if (audiobuf_read == get_trackdata(track_offset)->mempos)
833 if ( ! audio_dispatch_event(AUDIO_EVENT_END_OF_TRACK, 0) )
835 queue_post(&mpeg_queue, MPEG_TRACK_CHANGE, 0);
836 track_offset++;
841 unplayed_space_left = get_unplayed_space();
843 space_until_end_of_buffer = audiobuflen - audiobuf_read;
845 if(!filling && unplayed_space_left < low_watermark)
847 filling = true;
848 queue_post(&mpeg_queue, MPEG_NEED_DATA, GENERATE_UNBUFFER_EVENTS);
851 if(unplayed_space_left)
853 last_dma_chunk_size = MIN(0x2000, unplayed_space_left);
854 last_dma_chunk_size = MIN(last_dma_chunk_size,
855 space_until_end_of_buffer);
857 /* several tracks loaded? */
858 track = get_trackdata(track_offset);
859 if(track)
861 /* will we move across the track boundary? */
862 if (( audiobuf_read < track->mempos ) &&
863 ((audiobuf_read+last_dma_chunk_size) >
864 track->mempos ))
866 /* Make sure that we end exactly on the boundary */
867 last_dma_chunk_size = track->mempos - audiobuf_read;
871 *psize = last_dma_chunk_size & 0xffff;
872 *ppbuf = audiobuf + audiobuf_read;
873 track = get_trackdata(0);
874 if(track)
875 track->id3.offset += last_dma_chunk_size;
877 /* Update the watermark debug level */
878 if(unplayed_space_left < lowest_watermark_level)
879 lowest_watermark_level = unplayed_space_left;
881 else
883 /* Check if the end of data is because of a hard disk error.
884 If there is an open file handle, we are still playing music.
885 If not, the last file has been loaded, and the file handle is
886 closed. */
887 if(mpeg_file >= 0)
889 /* Update the watermark debug level */
890 if(unplayed_space_left < lowest_watermark_level)
891 lowest_watermark_level = unplayed_space_left;
893 DEBUGF("DMA underrun.\n");
894 dma_underrun = true;
896 else
898 if ( ! audio_dispatch_event(AUDIO_EVENT_END_OF_TRACK, 0) )
900 DEBUGF("No more MP3 data. Stopping.\n");
901 queue_post(&mpeg_queue, MPEG_TRACK_CHANGE, 0);
902 playing = false;
905 *psize = 0; /* no more transfer */
910 static struct trackdata *add_track_to_tag_list(const char *filename)
912 struct trackdata *track;
914 if(num_tracks_in_memory() >= MAX_TRACK_ENTRIES)
916 DEBUGF("Tag memory is full\n");
917 return NULL;
920 track = &trackdata[track_write_idx];
922 /* grab id3 tag of new file and
923 remember where in memory it starts */
924 if(mp3info(&track->id3, filename, v1first))
926 DEBUGF("Bad mp3\n");
927 return NULL;
929 track->mempos = audiobuf_write;
930 track->id3.elapsed = 0;
931 #ifdef HAVE_LCD_BITMAP
932 if (track->id3.title)
933 lcd_getstringsize(track->id3.title, NULL, NULL);
934 if (track->id3.artist)
935 lcd_getstringsize(track->id3.artist, NULL, NULL);
936 if (track->id3.album)
937 lcd_getstringsize(track->id3.album, NULL, NULL);
938 #endif
939 if (cuesheet_callback)
940 if (cuesheet_callback(filename))
941 track->id3.cuesheet_type = 1;
943 track_write_idx = (track_write_idx+1) & MAX_TRACK_ENTRIES_MASK;
944 debug_tags();
945 return track;
948 static int new_file(int steps)
950 int max_steps = playlist_amount();
951 int start = 0;
952 int i;
953 struct trackdata *track;
955 /* Find out how many steps to advance. The load_ahead_index field tells
956 us how many playlist entries it had to skip to get to a valid one.
957 We add those together to find out where to start. */
958 if(steps > 0 && num_tracks_in_memory() > 1)
960 /* Begin with the song after the currently playing one */
961 i = 1;
962 while((track = get_trackdata(i++)))
964 start += track->load_ahead_index;
968 do {
969 char *trackname;
971 trackname = playlist_peek( start + steps );
972 if ( !trackname )
973 return -1;
975 DEBUGF("Loading %s\n", trackname);
977 mpeg_file = open(trackname, O_RDONLY);
978 if(mpeg_file < 0) {
979 DEBUGF("Couldn't open file: %s\n",trackname);
980 if(steps < 0)
981 steps--;
982 else
983 steps++;
985 else
987 struct trackdata *track = add_track_to_tag_list(trackname);
989 if(!track)
991 /* Bad mp3 file */
992 if(steps < 0)
993 steps--;
994 else
995 steps++;
996 close(mpeg_file);
997 mpeg_file = -1;
999 else
1001 /* skip past id3v2 tag */
1002 lseek(mpeg_file,
1003 track->id3.first_frame_offset,
1004 SEEK_SET);
1005 track->id3.index = steps;
1006 track->load_ahead_index = steps;
1007 track->id3.offset = 0;
1009 if(track->id3.vbr)
1010 /* Average bitrate * 1.5 */
1011 recalculate_watermark(
1012 (track->id3.bitrate * 3) / 2);
1013 else
1014 recalculate_watermark(
1015 track->id3.bitrate);
1020 /* Bail out if no file could be opened */
1021 if(abs(steps) > max_steps)
1022 return -1;
1023 } while ( mpeg_file < 0 );
1025 return 0;
1028 static void stop_playing(void)
1030 /* Stop the current stream */
1031 mp3_play_stop();
1032 playing = false;
1033 filling = false;
1034 if(mpeg_file >= 0)
1035 close(mpeg_file);
1036 mpeg_file = -1;
1037 remove_all_tags();
1038 generate_unbuffer_events();
1039 reset_mp3_buffer();
1042 /* Is this a really the end of playback or is a new playlist starting */
1043 static void check_playlist_end(int direction)
1045 /* Use the largest possible step size to account for skipped tracks */
1046 int steps = playlist_amount();
1048 if (direction < 0)
1049 steps = -steps;
1051 if (playlist_next(steps) < 0)
1052 is_playing = false;
1055 static void update_playlist(void)
1057 if (num_tracks_in_memory() > 0)
1059 struct trackdata *track = get_trackdata(0);
1060 track->id3.index = playlist_next(track->id3.index);
1062 else
1064 /* End of playlist? */
1065 check_playlist_end(1);
1068 playlist_update_resume_info(audio_current_track());
1071 static void track_change(void)
1073 DEBUGF("Track change\n");
1075 struct trackdata *track = get_trackdata(0);
1076 prev_track_elapsed = track->id3.elapsed;
1078 #if (CONFIG_CODEC == MAS3587F) || (CONFIG_CODEC == MAS3539F)
1079 /* Reset the AVC */
1080 sound_set_avc(-1);
1081 #endif /* (CONFIG_CODEC == MAS3587F) || (CONFIG_CODEC == MAS3539F) */
1083 if (num_tracks_in_memory() > 0)
1085 remove_current_tag();
1086 if (track_changed_callback)
1087 track_changed_callback(audio_current_track());
1088 update_playlist();
1091 current_track_counter++;
1094 unsigned long audio_prev_elapsed(void)
1096 return prev_track_elapsed;
1099 #ifdef DEBUG
1100 void hexdump(const unsigned char *buf, int len)
1102 int i;
1104 for(i = 0;i < len;i++)
1106 if(i && (i & 15) == 0)
1108 DEBUGF("\n");
1110 DEBUGF("%02x ", buf[i]);
1112 DEBUGF("\n");
1114 #endif /* DEBUG */
1116 static void start_playback_if_ready(void)
1118 int playable_space;
1120 playable_space = audiobuf_swapwrite - audiobuf_read;
1121 if(playable_space < 0)
1122 playable_space += audiobuflen;
1124 /* See if we have started playing yet. If not, do it. */
1125 if(play_pending || dma_underrun)
1127 /* If the filling has stopped, and we still haven't reached
1128 the watermark, the file must be smaller than the
1129 watermark. We must still play it. */
1130 if((playable_space >= MPEG_PLAY_PENDING_THRESHOLD) ||
1131 !filling || dma_underrun)
1133 DEBUGF("P\n");
1134 if (play_pending) /* don't do this when recovering from DMA underrun */
1136 generate_postbuffer_events(); /* signal first track as buffered */
1137 if (track_changed_callback)
1138 track_changed_callback(audio_current_track());
1139 play_pending = false;
1141 playing = true;
1143 last_dma_chunk_size = MIN(0x2000, get_unplayed_space_current_song());
1144 mp3_play_data(audiobuf + audiobuf_read, last_dma_chunk_size, transfer_end);
1145 dma_underrun = false;
1147 if (!paused)
1149 last_dma_tick = current_tick;
1150 mp3_play_pause(true);
1153 /* Tell ourselves that we need more data */
1154 queue_post(&mpeg_queue, MPEG_NEED_DATA, 0);
1159 static bool swap_one_chunk(void)
1161 int free_space_left;
1162 int amount_to_swap;
1164 free_space_left = get_unswapped_space();
1166 if(free_space_left == 0 && !play_pending)
1167 return false;
1169 /* Swap in larger chunks when the user is waiting for the playback
1170 to start, or when there is dangerously little playable data left */
1171 if(play_pending)
1172 amount_to_swap = MIN(MPEG_PLAY_PENDING_SWAPSIZE, free_space_left);
1173 else
1175 if(get_playable_space() < low_watermark)
1176 amount_to_swap = MIN(MPEG_LOW_WATER_SWAP_CHUNKSIZE,
1177 free_space_left);
1178 else
1179 amount_to_swap = MIN(MPEG_SWAP_CHUNKSIZE, free_space_left);
1182 if(audiobuf_write < audiobuf_swapwrite)
1183 amount_to_swap = MIN(audiobuflen - audiobuf_swapwrite,
1184 amount_to_swap);
1185 else
1186 amount_to_swap = MIN(audiobuf_write - audiobuf_swapwrite,
1187 amount_to_swap);
1189 bitswap(audiobuf + audiobuf_swapwrite, amount_to_swap);
1191 audiobuf_swapwrite += amount_to_swap;
1192 if(audiobuf_swapwrite >= audiobuflen)
1194 audiobuf_swapwrite = 0;
1197 return true;
1200 static void mpeg_thread(void)
1202 static int pause_tick = 0;
1203 static unsigned int pause_track = 0;
1204 struct event ev;
1205 int len;
1206 int free_space_left;
1207 int unplayed_space_left;
1208 int amount_to_read;
1209 int t1, t2;
1210 int start_offset;
1211 #if CONFIG_CODEC == MAS3587F
1212 int amount_to_save;
1213 int save_endpos = 0;
1214 int rc;
1215 int level;
1216 long offset;
1217 #endif /* CONFIG_CODEC == MAS3587F */
1219 is_playing = false;
1220 play_pending = false;
1221 playing = false;
1222 mpeg_file = -1;
1224 while(1)
1226 #if CONFIG_CODEC == MAS3587F
1227 if(mpeg_mode == MPEG_DECODER)
1229 #endif /* CONFIG_CODEC == MAS3587F */
1230 yield();
1232 /* Swap if necessary, and don't block on the queue_wait() */
1233 if(swap_one_chunk())
1235 queue_wait_w_tmo(&mpeg_queue, &ev, 0);
1237 else if (playing)
1239 /* periodically update resume info */
1240 queue_wait_w_tmo(&mpeg_queue, &ev, HZ/2);
1242 else
1244 DEBUGF("S R:%x W:%x SW:%x\n",
1245 audiobuf_read, audiobuf_write, audiobuf_swapwrite);
1246 queue_wait(&mpeg_queue, &ev);
1249 start_playback_if_ready();
1251 switch(ev.id)
1253 case MPEG_PLAY:
1254 DEBUGF("MPEG_PLAY\n");
1256 #if CONFIG_TUNER
1257 /* Silence the A/D input, it may be on because the radio
1258 may be playing */
1259 mas_codec_writereg(6, 0x0000);
1260 #endif /* CONFIG_TUNER */
1262 /* Stop the current stream */
1263 play_pending = false;
1264 playing = false;
1265 paused = false;
1266 mp3_play_pause(false);
1268 reset_mp3_buffer();
1269 remove_all_tags();
1270 generate_unbuffer_events();
1272 if(mpeg_file >= 0)
1273 close(mpeg_file);
1275 if ( new_file(0) == -1 )
1277 is_playing = false;
1278 track_change();
1279 break;
1282 start_offset = (int)ev.data;
1284 /* mid-song resume? */
1285 if (start_offset) {
1286 struct mp3entry* id3 = &get_trackdata(0)->id3;
1287 lseek(mpeg_file, start_offset, SEEK_SET);
1288 id3->offset = start_offset;
1289 set_elapsed(id3);
1291 else {
1292 /* skip past id3v2 tag */
1293 lseek(mpeg_file,
1294 get_trackdata(0)->id3.first_frame_offset,
1295 SEEK_SET);
1299 /* Make it read more data */
1300 filling = true;
1301 queue_post(&mpeg_queue, MPEG_NEED_DATA, 0);
1303 /* Tell the file loading code that we want to start playing
1304 as soon as we have some data */
1305 play_pending = true;
1307 update_playlist();
1308 current_track_counter++;
1309 break;
1311 case MPEG_STOP:
1312 DEBUGF("MPEG_STOP\n");
1313 is_playing = false;
1314 paused = false;
1316 if (playing)
1317 playlist_update_resume_info(audio_current_track());
1319 stop_playing();
1320 mpeg_stop_done = true;
1321 break;
1323 case MPEG_PAUSE:
1324 DEBUGF("MPEG_PAUSE\n");
1325 /* Stop the current stream */
1326 if (playing)
1327 playlist_update_resume_info(audio_current_track());
1328 paused = true;
1329 playing = false;
1330 pause_tick = current_tick;
1331 pause_track = current_track_counter;
1332 mp3_play_pause(false);
1333 break;
1335 case MPEG_RESUME:
1336 DEBUGF("MPEG_RESUME\n");
1337 /* Continue the current stream */
1338 paused = false;
1339 if (!play_pending)
1341 playing = true;
1342 if ( current_track_counter == pause_track )
1343 last_dma_tick += current_tick - pause_tick;
1344 else
1345 last_dma_tick = current_tick;
1346 pause_tick = 0;
1347 mp3_play_pause(true);
1349 break;
1351 case MPEG_NEXT:
1352 DEBUGF("MPEG_NEXT\n");
1353 /* is next track in ram? */
1354 if ( num_tracks_in_memory() > 1 ) {
1355 int unplayed_space_left, unswapped_space_left;
1357 /* stop the current stream */
1358 play_pending = false;
1359 playing = false;
1360 mp3_play_pause(false);
1362 track_change();
1363 audiobuf_read = get_trackdata(0)->mempos;
1364 last_dma_chunk_size = MIN(0x2000, get_unplayed_space_current_song());
1365 mp3_play_data(audiobuf + audiobuf_read, last_dma_chunk_size, transfer_end);
1366 dma_underrun = false;
1367 last_dma_tick = current_tick;
1369 unplayed_space_left = get_unplayed_space();
1370 unswapped_space_left = get_unswapped_space();
1372 /* should we start reading more data? */
1373 if(!filling && (unplayed_space_left < low_watermark)) {
1374 filling = true;
1375 queue_post(&mpeg_queue, MPEG_NEED_DATA, GENERATE_UNBUFFER_EVENTS);
1376 play_pending = true;
1377 } else if(unswapped_space_left &&
1378 unswapped_space_left > unplayed_space_left) {
1379 /* Stop swapping the data from the previous file */
1380 audiobuf_swapwrite = audiobuf_read;
1381 play_pending = true;
1382 } else {
1383 playing = true;
1384 if (!paused)
1385 mp3_play_pause(true);
1388 else {
1389 if (!playlist_check(1))
1390 break;
1392 /* stop the current stream */
1393 play_pending = false;
1394 playing = false;
1395 mp3_play_pause(false);
1397 reset_mp3_buffer();
1398 remove_all_tags();
1399 generate_unbuffer_events();
1401 /* Open the next file */
1402 if (mpeg_file >= 0)
1403 close(mpeg_file);
1405 if (new_file(1) < 0) {
1406 DEBUGF("No more files to play\n");
1407 filling = false;
1409 check_playlist_end(1);
1410 current_track_counter++;
1411 } else {
1412 /* Make it read more data */
1413 filling = true;
1414 queue_post(&mpeg_queue, MPEG_NEED_DATA, 0);
1416 /* Tell the file loading code that we want
1417 to start playing as soon as we have some data */
1418 play_pending = true;
1420 update_playlist();
1421 current_track_counter++;
1424 break;
1426 case MPEG_PREV: {
1427 DEBUGF("MPEG_PREV\n");
1429 if (!playlist_check(-1))
1430 break;
1432 /* stop the current stream */
1433 play_pending = false;
1434 playing = false;
1435 mp3_play_pause(false);
1437 reset_mp3_buffer();
1438 remove_all_tags();
1439 generate_unbuffer_events();
1441 /* Open the next file */
1442 if (mpeg_file >= 0)
1443 close(mpeg_file);
1445 if (new_file(-1) < 0) {
1446 DEBUGF("No more files to play\n");
1447 filling = false;
1449 check_playlist_end(-1);
1450 current_track_counter++;
1451 } else {
1452 /* Make it read more data */
1453 filling = true;
1454 queue_post(&mpeg_queue, MPEG_NEED_DATA, 0);
1456 /* Tell the file loading code that we want to
1457 start playing as soon as we have some data */
1458 play_pending = true;
1460 update_playlist();
1461 current_track_counter++;
1463 break;
1466 case MPEG_FF_REWIND: {
1467 struct mp3entry *id3 = audio_current_track();
1468 unsigned int oldtime = id3->elapsed;
1469 unsigned int newtime = (unsigned int)ev.data;
1470 int curpos, newpos, diffpos;
1471 DEBUGF("MPEG_FF_REWIND\n");
1473 id3->elapsed = newtime;
1475 newpos = audio_get_file_pos();
1476 if(newpos < 0)
1478 id3->elapsed = oldtime;
1479 break;
1482 if (mpeg_file >= 0)
1483 curpos = lseek(mpeg_file, 0, SEEK_CUR);
1484 else
1485 curpos = id3->filesize;
1487 if (num_tracks_in_memory() > 1)
1489 /* We have started loading other tracks that need to be
1490 accounted for */
1491 struct trackdata *track;
1492 int i = 0;
1494 while((track = get_trackdata(i++)))
1496 curpos += track->id3.filesize;
1500 diffpos = curpos - newpos;
1502 if(!filling && diffpos >= 0 && diffpos < audiobuflen)
1504 int unplayed_space_left, unswapped_space_left;
1506 /* We are changing to a position that's already in
1507 memory, so we just move the DMA read pointer. */
1508 audiobuf_read = audiobuf_write - diffpos;
1509 if (audiobuf_read < 0)
1511 audiobuf_read += audiobuflen;
1514 unplayed_space_left = get_unplayed_space();
1515 unswapped_space_left = get_unswapped_space();
1517 /* If unswapped_space_left is larger than
1518 unplayed_space_left, it means that the swapwrite pointer
1519 hasn't yet advanced up to the new location of the read
1520 pointer. We just move it, there is no need to swap
1521 data that won't be played anyway. */
1523 if (unswapped_space_left > unplayed_space_left)
1525 DEBUGF("Moved swapwrite\n");
1526 audiobuf_swapwrite = audiobuf_read;
1527 play_pending = true;
1530 if (mpeg_file>=0 && unplayed_space_left < low_watermark)
1532 /* We need to load more data before starting */
1533 filling = true;
1534 queue_post(&mpeg_queue, MPEG_NEED_DATA, GENERATE_UNBUFFER_EVENTS);
1535 play_pending = true;
1537 else
1539 /* resume will start at new position */
1540 last_dma_chunk_size =
1541 MIN(0x2000, get_unplayed_space_current_song());
1542 mp3_play_data(audiobuf + audiobuf_read,
1543 last_dma_chunk_size, transfer_end);
1544 dma_underrun = false;
1547 else
1549 /* Move to the new position in the file and start
1550 loading data */
1551 reset_mp3_buffer();
1553 if (num_tracks_in_memory() > 1)
1555 /* We have to reload the current track */
1556 close(mpeg_file);
1557 remove_all_non_current_tags();
1558 generate_unbuffer_events();
1559 mpeg_file = -1;
1562 if (mpeg_file < 0)
1564 mpeg_file = open(id3->path, O_RDONLY);
1565 if (mpeg_file < 0)
1567 id3->elapsed = oldtime;
1568 break;
1572 if(-1 == lseek(mpeg_file, newpos, SEEK_SET))
1574 id3->elapsed = oldtime;
1575 break;
1578 filling = true;
1579 queue_post(&mpeg_queue, MPEG_NEED_DATA, 0);
1581 /* Tell the file loading code that we want to start playing
1582 as soon as we have some data */
1583 play_pending = true;
1586 id3->offset = newpos;
1588 break;
1591 case MPEG_FLUSH_RELOAD: {
1592 int numtracks = num_tracks_in_memory();
1593 bool reload_track = false;
1595 if (numtracks > 1)
1597 /* Reset the buffer */
1598 audiobuf_write = get_trackdata(1)->mempos;
1600 /* Reset swapwrite unless we're still swapping current
1601 track */
1602 if (get_unplayed_space() <= get_playable_space())
1603 audiobuf_swapwrite = audiobuf_write;
1605 close(mpeg_file);
1606 remove_all_non_current_tags();
1607 generate_unbuffer_events();
1608 mpeg_file = -1;
1609 reload_track = true;
1611 else if (numtracks == 1 && mpeg_file < 0)
1613 reload_track = true;
1616 if(reload_track && new_file(1) >= 0)
1618 /* Tell ourselves that we want more data */
1619 filling = true;
1620 queue_post(&mpeg_queue, MPEG_NEED_DATA, 0);
1623 break;
1626 case MPEG_NEED_DATA:
1627 free_space_left = audiobuf_read - audiobuf_write;
1629 /* We interpret 0 as "empty buffer" */
1630 if(free_space_left <= 0)
1631 free_space_left += audiobuflen;
1633 unplayed_space_left = audiobuflen - free_space_left;
1635 /* Make sure that we don't fill the entire buffer */
1636 free_space_left -= MPEG_HIGH_WATER;
1638 if (ev.data == GENERATE_UNBUFFER_EVENTS)
1639 generate_unbuffer_events();
1641 /* do we have any more buffer space to fill? */
1642 if(free_space_left <= 0)
1644 DEBUGF("0\n");
1645 filling = false;
1646 generate_postbuffer_events();
1647 ata_sleep();
1648 break;
1651 /* Read small chunks while we are below the low water mark */
1652 if(unplayed_space_left < low_watermark)
1653 amount_to_read = MIN(MPEG_LOW_WATER_CHUNKSIZE,
1654 free_space_left);
1655 else
1656 amount_to_read = free_space_left;
1658 /* Don't read more than until the end of the buffer */
1659 amount_to_read = MIN(audiobuflen - audiobuf_write,
1660 amount_to_read);
1661 #ifdef HAVE_MMC /* MMC is slow, so don't read too large chunks */
1662 amount_to_read = MIN(0x40000, amount_to_read);
1663 #elif MEM == 8
1664 amount_to_read = MIN(0x100000, amount_to_read);
1665 #endif
1667 /* Read as much mpeg data as we can fit in the buffer */
1668 if(mpeg_file >= 0)
1670 DEBUGF("R\n");
1671 t1 = current_tick;
1672 len = read(mpeg_file, audiobuf + audiobuf_write,
1673 amount_to_read);
1674 if(len > 0)
1676 t2 = current_tick;
1677 DEBUGF("time: %d\n", t2 - t1);
1678 DEBUGF("R: %x\n", len);
1680 /* Now make sure that we don't feed the MAS with ID3V1
1681 data */
1682 if (len < amount_to_read)
1684 int i;
1685 static const unsigned char tag[] = "TAG";
1686 int taglen = 128;
1687 int tagptr = audiobuf_write + len - 128;
1689 /* Really rare case: entire potential tag wasn't
1690 read in this call AND audiobuf_write < 128 */
1691 if (tagptr < 0)
1692 tagptr += audiobuflen;
1694 for(i = 0;i < 3;i++)
1696 if(tagptr >= audiobuflen)
1697 tagptr -= audiobuflen;
1699 if(audiobuf[tagptr] != tag[i])
1701 taglen = 0;
1702 break;
1705 tagptr++;
1708 if(taglen)
1710 /* Skip id3v1 tag */
1711 DEBUGF("Skipping ID3v1 tag\n");
1712 len -= taglen;
1714 /* In the very rare case when the entire tag
1715 wasn't read in this read() len will be < 0.
1716 Take care of this when changing the write
1717 pointer. */
1721 audiobuf_write += len;
1723 if (audiobuf_write < 0)
1724 audiobuf_write += audiobuflen;
1726 if(audiobuf_write >= audiobuflen)
1728 audiobuf_write = 0;
1729 DEBUGF("W\n");
1732 /* Tell ourselves that we want more data */
1733 queue_post(&mpeg_queue, MPEG_NEED_DATA, 0);
1735 else
1737 if(len < 0)
1739 DEBUGF("MPEG read error\n");
1742 close(mpeg_file);
1743 mpeg_file = -1;
1745 if(new_file(1) < 0)
1747 /* No more data to play */
1748 DEBUGF("No more files to play\n");
1749 filling = false;
1751 else
1753 /* Tell ourselves that we want more data */
1754 queue_post(&mpeg_queue, MPEG_NEED_DATA, 0);
1758 break;
1760 case MPEG_TRACK_CHANGE:
1761 track_change();
1762 break;
1764 #ifndef USB_NONE
1765 case SYS_USB_CONNECTED:
1766 is_playing = false;
1767 paused = false;
1768 stop_playing();
1770 /* Tell the USB thread that we are safe */
1771 DEBUGF("mpeg_thread got SYS_USB_CONNECTED\n");
1772 usb_acknowledge(SYS_USB_CONNECTED_ACK);
1774 /* Wait until the USB cable is extracted again */
1775 usb_wait_for_disconnect(&mpeg_queue);
1776 break;
1777 #endif /* !USB_NONE */
1779 #if CONFIG_CODEC == MAS3587F
1780 case MPEG_INIT_RECORDING:
1781 init_recording();
1782 init_recording_done = true;
1783 break;
1784 #endif /* CONFIG_CODEC == MAS3587F */
1786 case SYS_TIMEOUT:
1787 if (playing)
1788 playlist_update_resume_info(audio_current_track());
1789 break;
1791 #if CONFIG_CODEC == MAS3587F
1793 else
1795 queue_wait(&mpeg_queue, &ev);
1796 switch(ev.id)
1798 case MPEG_RECORD:
1799 if (is_prerecording)
1801 int startpos;
1803 /* Go back prerecord_count seconds in the buffer */
1804 startpos = prerecord_index - prerecord_count;
1805 if(startpos < 0)
1806 startpos += prerecording_max_seconds;
1808 /* Read the position data from the prerecord buffer */
1809 frame_count_start = prerecord_buffer[startpos].framecount;
1810 startpos = prerecord_buffer[startpos].mempos;
1812 DEBUGF("Start looking at address %x (%x)\n",
1813 audiobuf+startpos, startpos);
1815 saved_header = mpeg_get_last_header();
1817 mem_find_next_frame(startpos, &offset, 1800,
1818 saved_header);
1820 audiobuf_read = startpos + offset;
1821 if(audiobuf_read >= audiobuflen)
1822 audiobuf_read -= audiobuflen;
1824 DEBUGF("New audiobuf_read address: %x (%x)\n",
1825 audiobuf+audiobuf_read, audiobuf_read);
1827 level = set_irq_level(HIGHEST_IRQ_LEVEL);
1828 num_rec_bytes = get_unsaved_space();
1829 set_irq_level(level);
1831 else
1833 frame_count_start = 0;
1834 num_rec_bytes = 0;
1835 audiobuf_read = MPEG_RESERVED_HEADER_SPACE;
1836 audiobuf_write = MPEG_RESERVED_HEADER_SPACE;
1839 prepend_header();
1840 DEBUGF("Recording...\n");
1841 start_recording();
1843 /* Wait until at least one frame is encoded and get the
1844 frame header, for later use by the Xing header
1845 generation */
1846 sleep(HZ/5);
1847 saved_header = mpeg_get_last_header();
1849 /* delayed until buffer is saved, don't open yet */
1850 strcpy(delayed_filename, recording_filename);
1851 mpeg_file = -1;
1853 break;
1855 case MPEG_STOP:
1856 DEBUGF("MPEG_STOP\n");
1858 stop_recording();
1860 /* Save the remaining data in the buffer */
1861 save_endpos = audiobuf_write;
1862 saving_status = STOP_RECORDING;
1863 queue_post(&mpeg_queue, MPEG_SAVE_DATA, 0);
1864 break;
1866 case MPEG_STOP_DONE:
1867 DEBUGF("MPEG_STOP_DONE\n");
1869 if (mpeg_file >= 0)
1870 close(mpeg_file);
1871 mpeg_file = -1;
1873 update_header();
1874 #ifdef DEBUG1
1876 int i;
1877 for(i = 0;i < 512;i++)
1879 DEBUGF("%d - %d us (%d bytes)\n",
1880 timing_info[i*2],
1881 (timing_info[i*2+1] & 0xffff) *
1882 10000 / 13824,
1883 timing_info[i*2+1] >> 16);
1886 #endif /* DEBUG1 */
1888 if (prerecording)
1890 start_prerecording();
1892 mpeg_stop_done = true;
1893 break;
1895 case MPEG_NEW_FILE:
1896 /* Bail out when a more important save is happening */
1897 if (saving_status > NEW_FILE)
1898 break;
1900 /* Make sure we have at least one complete frame
1901 in the buffer. If we haven't recorded a single
1902 frame within 200ms, the MAS is probably not recording
1903 anything, and we bail out. */
1904 amount_to_save = get_unsaved_space();
1905 if (amount_to_save < 1800)
1907 sleep(HZ/5);
1908 amount_to_save = get_unsaved_space();
1911 mas_readmem(MAS_BANK_D0, MAS_D0_MPEG_FRAME_COUNT,
1912 &frame_count_end, 1);
1914 last_rec_time = current_tick - record_start_time;
1915 record_start_time = current_tick;
1916 if (paused)
1917 pause_start_time = record_start_time;
1919 /* capture all values at one point */
1920 level = set_irq_level(HIGHEST_IRQ_LEVEL);
1921 save_endpos = audiobuf_write;
1922 last_rec_bytes = num_rec_bytes;
1923 num_rec_bytes = 0;
1924 set_irq_level(level);
1926 if (amount_to_save >= 1800)
1928 /* Now find a frame boundary to split at */
1929 save_endpos -= 1800;
1930 if (save_endpos < 0)
1931 save_endpos += audiobuflen;
1933 rc = mem_find_next_frame(save_endpos, &offset, 1800,
1934 saved_header);
1935 if (!rc) /* No header found, save whole buffer */
1936 offset = 1800;
1938 save_endpos += offset;
1939 if (save_endpos >= audiobuflen)
1940 save_endpos -= audiobuflen;
1942 last_rec_bytes += offset - 1800;
1943 level = set_irq_level(HIGHEST_IRQ_LEVEL);
1944 num_rec_bytes += 1800 - offset;
1945 set_irq_level(level);
1948 saving_status = NEW_FILE;
1949 queue_post(&mpeg_queue, MPEG_SAVE_DATA, 0);
1950 break;
1952 case MPEG_SAVE_DATA:
1953 if (saving_status == BUFFER_FULL)
1954 save_endpos = audiobuf_write;
1956 if (mpeg_file < 0) /* delayed file open */
1958 mpeg_file = open(delayed_filename, O_WRONLY|O_CREAT);
1960 if (mpeg_file < 0)
1961 panicf("recfile: %d", mpeg_file);
1964 amount_to_save = save_endpos - audiobuf_read;
1965 if (amount_to_save < 0)
1966 amount_to_save += audiobuflen;
1968 amount_to_save = MIN(amount_to_save,
1969 audiobuflen - audiobuf_read);
1970 #ifdef HAVE_MMC /* MMC is slow, so don't save too large chunks at once */
1971 amount_to_save = MIN(0x40000, amount_to_save);
1972 #elif MEM == 8
1973 amount_to_save = MIN(0x100000, amount_to_save);
1974 #endif
1975 rc = write(mpeg_file, audiobuf + audiobuf_read,
1976 amount_to_save);
1977 if (rc < 0)
1979 if (errno == ENOSPC)
1981 mpeg_errno = AUDIOERR_DISK_FULL;
1982 stop_recording();
1983 queue_post(&mpeg_queue, MPEG_STOP_DONE, 0);
1984 /* will close the file */
1985 break;
1987 else
1988 panicf("rec wrt: %d", rc);
1991 audiobuf_read += amount_to_save;
1992 if (audiobuf_read >= audiobuflen)
1993 audiobuf_read = 0;
1995 if (audiobuf_read == save_endpos) /* all saved */
1997 switch (saving_status)
1999 case BUFFER_FULL:
2000 rc = fsync(mpeg_file);
2001 if (rc < 0)
2002 panicf("rec fls: %d", rc);
2003 ata_sleep();
2004 break;
2006 case NEW_FILE:
2007 /* Close the current file */
2008 rc = close(mpeg_file);
2009 if (rc < 0)
2010 panicf("rec cls: %d", rc);
2011 mpeg_file = -1;
2012 update_header();
2013 ata_sleep();
2015 /* copy new filename */
2016 strcpy(delayed_filename, recording_filename);
2017 prepend_header();
2018 frame_count_start = frame_count_end;
2019 break;
2021 case STOP_RECORDING:
2022 queue_post(&mpeg_queue, MPEG_STOP_DONE, 0);
2023 /* will close the file */
2024 break;
2026 default:
2027 break;
2029 saving_status = NOT_SAVING;
2031 else /* tell ourselves to save the next chunk */
2032 queue_post(&mpeg_queue, MPEG_SAVE_DATA, 0);
2034 break;
2036 case MPEG_PRERECORDING_TICK:
2037 if(!is_prerecording)
2038 break;
2040 /* Store the write pointer every second */
2041 prerecord_buffer[prerecord_index].mempos = audiobuf_write;
2042 mas_readmem(MAS_BANK_D0, MAS_D0_MPEG_FRAME_COUNT,
2043 &prerecord_buffer[prerecord_index].framecount, 1);
2045 /* Wrap if necessary */
2046 if(++prerecord_index == prerecording_max_seconds)
2047 prerecord_index = 0;
2049 /* Update the number of seconds recorded */
2050 if(prerecord_count < prerecording_max_seconds)
2051 prerecord_count++;
2052 break;
2054 case MPEG_INIT_PLAYBACK:
2055 /* Stop the prerecording */
2056 stop_recording();
2057 reset_mp3_buffer();
2058 mp3_play_init();
2059 init_playback_done = true;
2060 break;
2062 case MPEG_PAUSE_RECORDING:
2063 pause_recording();
2064 break;
2066 case MPEG_RESUME_RECORDING:
2067 resume_recording();
2068 break;
2070 case SYS_USB_CONNECTED:
2071 /* We can safely go to USB mode if no recording
2072 is taking place */
2073 if((!is_recording || is_prerecording) && mpeg_stop_done)
2075 /* Even if we aren't recording, we still call this
2076 function, to put the MAS in monitoring mode,
2077 to save power. */
2078 stop_recording();
2080 /* Tell the USB thread that we are safe */
2081 DEBUGF("mpeg_thread got SYS_USB_CONNECTED\n");
2082 usb_acknowledge(SYS_USB_CONNECTED_ACK);
2084 /* Wait until the USB cable is extracted again */
2085 usb_wait_for_disconnect(&mpeg_queue);
2087 break;
2090 #endif /* CONFIG_CODEC == MAS3587F */
2093 #endif /* !SIMULATOR */
2095 void mpeg_id3_options(bool _v1first)
2097 v1first = _v1first;
2100 struct mp3entry* audio_current_track()
2102 #ifdef SIMULATOR
2103 return &taginfo;
2104 #else /* !SIMULATOR */
2105 if(num_tracks_in_memory())
2106 return &get_trackdata(0)->id3;
2107 else
2108 return NULL;
2109 #endif /* !SIMULATOR */
2112 struct mp3entry* audio_next_track()
2114 #ifdef SIMULATOR
2115 return &taginfo;
2116 #else /* !SIMULATOR */
2117 if(num_tracks_in_memory() > 1)
2118 return &get_trackdata(1)->id3;
2119 else
2120 return NULL;
2121 #endif /* !SIMULATOR */
2124 bool audio_has_changed_track(void)
2126 if(last_track_counter != current_track_counter)
2128 last_track_counter = current_track_counter;
2129 return true;
2131 return false;
2134 #if CONFIG_CODEC == MAS3587F
2135 #ifndef SIMULATOR
2136 void audio_init_playback(void)
2138 init_playback_done = false;
2139 queue_post(&mpeg_queue, MPEG_INIT_PLAYBACK, 0);
2141 while(!init_playback_done)
2142 sleep_thread(1);
2146 /****************************************************************************
2147 * Recording functions
2148 ***************************************************************************/
2149 void audio_init_recording(unsigned int buffer_offset)
2151 buffer_offset = buffer_offset;
2152 init_recording_done = false;
2153 queue_post(&mpeg_queue, MPEG_INIT_RECORDING, 0);
2155 while(!init_recording_done)
2156 sleep_thread(1);
2159 static void init_recording(void)
2161 unsigned long val;
2162 int rc;
2164 /* Disable IRQ6 */
2165 IPRB &= 0xff0f;
2167 stop_playing();
2168 is_playing = false;
2169 paused = false;
2171 /* Init the recording variables */
2172 is_recording = false;
2173 is_prerecording = false;
2175 mpeg_stop_done = true;
2177 mas_reset();
2179 /* Enable the audio CODEC and the DSP core, max analog voltage range */
2180 rc = mas_direct_config_write(MAS_CONTROL, 0x8c00);
2181 if(rc < 0)
2182 panicf("mas_ctrl_w: %d", rc);
2184 /* Stop the current application */
2185 val = 0;
2186 mas_writemem(MAS_BANK_D0, MAS_D0_APP_SELECT, &val, 1);
2189 mas_readmem(MAS_BANK_D0, MAS_D0_APP_RUNNING, &val, 1);
2190 } while(val);
2192 /* Perform black magic as described by the data sheet */
2193 if((mas_version_code & 0x0fff) == 0x0102)
2195 DEBUGF("Performing MAS black magic for B2 version\n");
2196 mas_writereg(0xa3, 0x98);
2197 mas_writereg(0x94, 0xfffff);
2198 val = 0;
2199 mas_writemem(MAS_BANK_D1, 0, &val, 1);
2200 mas_writereg(0xa3, 0x90);
2203 /* Enable A/D Converters */
2204 shadow_codec_reg0 = 0xcccd;
2205 mas_codec_writereg(0x0, shadow_codec_reg0);
2207 /* Copy left channel to right (mono mode) */
2208 mas_codec_writereg(8, 0x8000);
2210 /* ADC scale 0%, DSP scale 100%
2211 We use the DSP output for monitoring, because it works with all
2212 sources including S/PDIF */
2213 mas_codec_writereg(6, 0x0000);
2214 mas_codec_writereg(7, 0x4000);
2216 /* No mute */
2217 shadow_soft_mute = 0;
2218 mas_writemem(MAS_BANK_D0, MAS_D0_SOFT_MUTE, &shadow_soft_mute, 1);
2220 #ifdef HAVE_SPDIF_OUT
2221 val = 0x09; /* Disable SDO and SDI, low impedance S/PDIF outputs */
2222 #else
2223 val = 0x2d; /* Disable SDO and SDI, disable S/PDIF output */
2224 #endif
2225 mas_writemem(MAS_BANK_D0, MAS_D0_INTERFACE_CONTROL, &val, 1);
2227 /* Set Demand mode, monitoring OFF and validate all settings */
2228 shadow_io_control_main = 0x125;
2229 mas_writemem(MAS_BANK_D0, MAS_D0_IO_CONTROL_MAIN, &shadow_io_control_main, 1);
2231 /* Start the encoder application */
2232 val = 0x40;
2233 mas_writemem(MAS_BANK_D0, MAS_D0_APP_SELECT, &val, 1);
2236 mas_readmem(MAS_BANK_D0, MAS_D0_APP_RUNNING, &val, 1);
2237 } while(!(val & 0x40));
2239 /* We have started the recording application with monitoring OFF.
2240 This is because we want to record at least one frame to fill the DMA
2241 buffer, because the silly MAS will not negate EOD until at least one
2242 DMA transfer has taken place.
2243 Now let's wait for some data to be encoded. */
2244 sleep(HZ/5);
2246 /* Now set it to Monitoring mode as default, saves power */
2247 shadow_io_control_main = 0x525;
2248 mas_writemem(MAS_BANK_D0, MAS_D0_IO_CONTROL_MAIN, &shadow_io_control_main, 1);
2250 /* Wait until the DSP has accepted the settings */
2253 mas_readmem(MAS_BANK_D0, MAS_D0_IO_CONTROL_MAIN, &val,1);
2254 } while(val & 1);
2256 drain_dma_buffer();
2257 mpeg_mode = MPEG_ENCODER;
2259 DEBUGF("MAS Recording application started\n");
2261 /* At this point, all settings are the reset MAS defaults, next thing is to
2262 call mpeg_set_recording_options(). */
2265 void audio_record(const char *filename)
2267 mpeg_errno = 0;
2269 strncpy(recording_filename, filename, MAX_PATH - 1);
2270 recording_filename[MAX_PATH - 1] = 0;
2272 queue_post(&mpeg_queue, MPEG_RECORD, 0);
2275 void audio_pause_recording(void)
2277 queue_post(&mpeg_queue, MPEG_PAUSE_RECORDING, 0);
2280 void audio_resume_recording(void)
2282 queue_post(&mpeg_queue, MPEG_RESUME_RECORDING, 0);
2285 static void prepend_header(void)
2287 int startpos;
2288 unsigned i;
2290 /* Make room for header */
2291 audiobuf_read -= MPEG_RESERVED_HEADER_SPACE;
2292 if(audiobuf_read < 0)
2294 /* Clear the bottom half */
2295 memset(audiobuf, 0, audiobuf_read + MPEG_RESERVED_HEADER_SPACE);
2297 /* And the top half */
2298 audiobuf_read += audiobuflen;
2299 memset(audiobuf + audiobuf_read, 0, audiobuflen - audiobuf_read);
2301 else
2303 memset(audiobuf + audiobuf_read, 0, MPEG_RESERVED_HEADER_SPACE);
2305 /* Copy the empty ID3 header */
2306 startpos = audiobuf_read;
2307 for(i = 0; i < sizeof(empty_id3_header); i++)
2309 audiobuf[startpos++] = empty_id3_header[i];
2310 if(startpos == audiobuflen)
2311 startpos = 0;
2315 static void update_header(void)
2317 int fd, framelen;
2318 unsigned long frames;
2320 if (last_rec_bytes > 0)
2322 /* Create the Xing header */
2323 fd = open(delayed_filename, O_RDWR);
2324 if (fd < 0)
2325 panicf("rec upd: %d (%s)", fd, recording_filename);
2327 frames = frame_count_end - frame_count_start;
2328 /* If the number of recorded frames has reached 0x7ffff,
2329 we can no longer trust it */
2330 if (frame_count_end == 0x7ffff)
2331 frames = 0;
2333 /* saved_header is saved right before stopping the MAS */
2334 framelen = create_xing_header(fd, 0, last_rec_bytes, xing_buffer,
2335 frames, last_rec_time * (1000/HZ),
2336 saved_header, NULL, false);
2338 lseek(fd, MPEG_RESERVED_HEADER_SPACE - framelen, SEEK_SET);
2339 write(fd, xing_buffer, framelen);
2340 close(fd);
2344 static void start_prerecording(void)
2346 unsigned long val;
2348 DEBUGF("Starting prerecording\n");
2350 prerecord_index = 0;
2351 prerecord_count = 0;
2352 prerecord_timeout = current_tick + HZ;
2353 memset(prerecord_buffer, 0, sizeof(prerecord_buffer));
2354 reset_mp3_buffer();
2356 is_prerecording = true;
2358 /* Stop monitoring and start the encoder */
2359 shadow_io_control_main &= ~(1 << 10);
2360 mas_writemem(MAS_BANK_D0, MAS_D0_IO_CONTROL_MAIN, &shadow_io_control_main, 1);
2361 DEBUGF("mas_writemem(MAS_BANK_D0, IO_CONTROL_MAIN, %x)\n", shadow_io_control_main);
2363 /* Wait until the DSP has accepted the settings */
2366 mas_readmem(MAS_BANK_D0, MAS_D0_IO_CONTROL_MAIN, &val,1);
2367 } while(val & 1);
2369 is_recording = true;
2370 saving_status = NOT_SAVING;
2372 demand_irq_enable(true);
2375 static void start_recording(void)
2377 unsigned long val;
2379 if(is_prerecording)
2381 /* This will make the IRQ handler start recording
2382 for real, i.e send MPEG_SAVE_DATA messages when
2383 the buffer is full */
2384 is_prerecording = false;
2386 else
2388 /* If prerecording is off, we need to stop the monitoring
2389 and start the encoder */
2390 shadow_io_control_main &= ~(1 << 10);
2391 mas_writemem(MAS_BANK_D0, MAS_D0_IO_CONTROL_MAIN, &shadow_io_control_main, 1);
2392 DEBUGF("mas_writemem(MAS_BANK_D0, IO_CONTROL_MAIN, %x)\n", shadow_io_control_main);
2394 /* Wait until the DSP has accepted the settings */
2397 mas_readmem(MAS_BANK_D0, MAS_D0_IO_CONTROL_MAIN, &val,1);
2398 } while(val & 1);
2401 is_recording = true;
2402 saving_status = NOT_SAVING;
2403 paused = false;
2405 /* Store the current time */
2406 if(prerecording)
2407 record_start_time = current_tick - prerecord_count * HZ;
2408 else
2409 record_start_time = current_tick;
2411 pause_start_time = 0;
2413 demand_irq_enable(true);
2416 static void pause_recording(void)
2418 pause_start_time = current_tick;
2420 /* Set the pause bit */
2421 shadow_soft_mute |= 2;
2422 mas_writemem(MAS_BANK_D0, MAS_D0_SOFT_MUTE, &shadow_soft_mute, 1);
2424 paused = true;
2427 static void resume_recording(void)
2429 paused = false;
2431 /* Clear the pause bit */
2432 shadow_soft_mute &= ~2;
2433 mas_writemem(MAS_BANK_D0, MAS_D0_SOFT_MUTE, &shadow_soft_mute, 1);
2435 /* Compensate for the time we have been paused */
2436 if(pause_start_time)
2438 record_start_time =
2439 current_tick - (pause_start_time - record_start_time);
2440 pause_start_time = 0;
2444 static void stop_recording(void)
2446 unsigned long val;
2448 /* Let it finish the last frame */
2449 if(!paused)
2450 pause_recording();
2451 sleep(HZ/5);
2453 demand_irq_enable(false);
2455 is_recording = false;
2456 is_prerecording = false;
2458 last_rec_bytes = num_rec_bytes;
2459 mas_readmem(MAS_BANK_D0, MAS_D0_MPEG_FRAME_COUNT, &frame_count_end, 1);
2460 last_rec_time = current_tick - record_start_time;
2462 /* Start monitoring */
2463 shadow_io_control_main |= (1 << 10);
2464 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 /* Wait until the DSP has accepted the settings */
2470 mas_readmem(MAS_BANK_D0, MAS_D0_IO_CONTROL_MAIN, &val,1);
2471 } while(val & 1);
2473 resume_recording();
2476 void audio_set_recording_options(struct audio_recording_options *options)
2478 bool is_mpeg1;
2480 is_mpeg1 = (options->rec_frequency < 3)?true:false;
2482 rec_version_index = is_mpeg1?3:2;
2483 rec_frequency_index = options->rec_frequency % 3;
2485 shadow_encoder_control = (options->rec_quality << 17) |
2486 (rec_frequency_index << 10) |
2487 ((is_mpeg1?1:0) << 9) |
2488 (((options->rec_channels * 2 + 1) & 3) << 6) |
2489 (1 << 5) /* MS-stereo */ |
2490 (1 << 2) /* Is an original */;
2491 mas_writemem(MAS_BANK_D0, MAS_D0_ENCODER_CONTROL, &shadow_encoder_control,1);
2493 DEBUGF("mas_writemem(MAS_BANK_D0, ENCODER_CONTROL, %x)\n", shadow_encoder_control);
2495 shadow_soft_mute = options->rec_editable?4:0;
2496 mas_writemem(MAS_BANK_D0, MAS_D0_SOFT_MUTE, &shadow_soft_mute,1);
2498 DEBUGF("mas_writemem(MAS_BANK_D0, SOFT_MUTE, %x)\n", shadow_soft_mute);
2500 shadow_io_control_main = ((1 << 10) | /* Monitoring ON */
2501 ((options->rec_source < 2)?1:2) << 8) | /* Input select */
2502 (1 << 5) | /* SDO strobe invert */
2503 ((is_mpeg1?0:1) << 3) |
2504 (1 << 2) | /* Inverted SIBC clock signal */
2505 1; /* Validate */
2506 mas_writemem(MAS_BANK_D0, MAS_D0_IO_CONTROL_MAIN, &shadow_io_control_main,1);
2508 DEBUGF("mas_writemem(MAS_BANK_D0, IO_CONTROL_MAIN, %x)\n", shadow_io_control_main);
2510 if(options->rec_source == AUDIO_SRC_MIC)
2512 /* Copy left channel to right (mono mode) */
2513 mas_codec_writereg(8, 0x8000);
2515 else
2517 /* Stereo input mode */
2518 mas_codec_writereg(8, 0);
2521 prerecording_max_seconds = options->rec_prerecord_time;
2522 if(prerecording_max_seconds)
2524 prerecording = true;
2525 start_prerecording();
2527 else
2529 prerecording = false;
2530 is_prerecording = false;
2531 is_recording = false;
2535 /* If use_mic is true, the left gain is used */
2536 void audio_set_recording_gain(int left, int right, int type)
2538 /* Enable both left and right A/D */
2539 shadow_codec_reg0 = (left << 12) |
2540 (right << 8) |
2541 (left << 4) |
2542 (type==AUDIO_GAIN_MIC?0x0008:0) | /* Connect left A/D to mic */
2543 0x0007;
2544 mas_codec_writereg(0x0, shadow_codec_reg0);
2547 #if CONFIG_TUNER & S1A0903X01
2548 /* Get the (unpitched) MAS PLL frequency, for avoiding FM interference with the
2549 * Samsung tuner. Zero means unknown. Currently handles recording from analog
2550 * input only. */
2551 int mpeg_get_mas_pllfreq(void)
2553 if (mpeg_mode != MPEG_ENCODER)
2554 return 0;
2556 if (rec_frequency_index == 0) /* 44.1 kHz / 22.05 kHz */
2557 return 22579000;
2558 else
2559 return 24576000;
2561 #endif /* CONFIG_TUNER & S1A0903X01 */
2563 /* try to make some kind of beep, also in recording mode */
2564 void audio_beep(int duration)
2566 long starttick = current_tick;
2568 { /* toggle bit 0 of codec register 0, toggling the DAC off & on.
2569 * While this is still audible even without an external signal,
2570 * it doesn't affect the (pre-)recording. */
2571 mas_codec_writereg(0, shadow_codec_reg0 ^ 1);
2572 mas_codec_writereg(0, shadow_codec_reg0);
2573 yield();
2575 while (current_tick - starttick < duration);
2578 void audio_new_file(const char *filename)
2580 mpeg_errno = 0;
2582 strncpy(recording_filename, filename, MAX_PATH - 1);
2583 recording_filename[MAX_PATH - 1] = 0;
2585 queue_post(&mpeg_queue, MPEG_NEW_FILE, 0);
2588 unsigned long audio_recorded_time(void)
2590 if(is_prerecording)
2591 return prerecord_count * HZ;
2593 if(is_recording)
2595 if(paused)
2596 return pause_start_time - record_start_time;
2597 else
2598 return current_tick - record_start_time;
2601 return 0;
2604 unsigned long audio_num_recorded_bytes(void)
2606 int num_bytes;
2607 int index;
2609 if(is_recording)
2611 if(is_prerecording)
2613 index = prerecord_index - prerecord_count;
2614 if(index < 0)
2615 index += prerecording_max_seconds;
2617 num_bytes = audiobuf_write - prerecord_buffer[index].mempos;
2618 if(num_bytes < 0)
2619 num_bytes += audiobuflen;
2621 return num_bytes;;
2623 else
2624 return num_rec_bytes;
2626 else
2627 return 0;
2630 #else /* SIMULATOR */
2632 /* dummies coming up */
2634 void audio_init_playback(void)
2636 /* a dummy */
2638 unsigned long audio_recorded_time(void)
2640 /* a dummy */
2641 return 0;
2643 void audio_beep(int duration)
2645 /* a dummy */
2646 (void)duration;
2648 void audio_pause_recording(void)
2650 /* a dummy */
2652 void audio_resume_recording(void)
2654 /* a dummy */
2656 unsigned long audio_num_recorded_bytes(void)
2658 /* a dummy */
2659 return 0;
2661 void audio_record(const char *filename)
2663 /* a dummy */
2664 (void)filename;
2666 void audio_new_file(const char *filename)
2668 /* a dummy */
2669 (void)filename;
2672 void audio_set_recording_gain(int left, int right, int type)
2674 /* a dummy */
2675 (void)left;
2676 (void)right;
2677 (void)type;
2679 void audio_init_recording(unsigned int buffer_offset)
2681 /* a dummy */
2682 (void)buffer_offset;
2684 void audio_set_recording_options(struct audio_recording_options *options)
2686 /* a dummy */
2687 (void)options;
2689 #endif /* SIMULATOR */
2690 #endif /* CONFIG_CODEC == MAS3587F */
2692 void audio_play(long offset)
2694 #ifdef SIMULATOR
2695 char* trackname;
2696 int steps=0;
2698 is_playing = true;
2700 do {
2701 trackname = playlist_peek( steps );
2702 if (!trackname)
2703 break;
2704 if(mp3info(&taginfo, trackname, v1first)) {
2705 /* bad mp3, move on */
2706 if(++steps > playlist_amount())
2707 break;
2708 continue;
2710 #ifdef HAVE_MPEG_PLAY
2711 real_mpeg_play(trackname);
2712 #endif
2713 playlist_next(steps);
2714 taginfo.offset = offset;
2715 set_elapsed(&taginfo);
2716 is_playing = true;
2717 playing = true;
2718 break;
2719 } while(1);
2720 #else /* !SIMULATOR */
2721 is_playing = true;
2723 queue_post(&mpeg_queue, MPEG_PLAY, offset);
2724 #endif /* !SIMULATOR */
2726 mpeg_errno = 0;
2729 void audio_stop(void)
2731 #ifndef SIMULATOR
2732 if (playing)
2734 struct trackdata *track = get_trackdata(0);
2735 prev_track_elapsed = track->id3.elapsed;
2737 mpeg_stop_done = false;
2738 queue_post(&mpeg_queue, MPEG_STOP, 0);
2739 while(!mpeg_stop_done)
2740 yield();
2741 #else /* SIMULATOR */
2742 paused = false;
2743 is_playing = false;
2744 playing = false;
2745 #endif /* SIMULATOR */
2748 /* dummy */
2749 void audio_stop_recording(void)
2751 audio_stop();
2754 void audio_pause(void)
2756 #ifndef SIMULATOR
2757 queue_post(&mpeg_queue, MPEG_PAUSE, 0);
2758 #else /* SIMULATOR */
2759 is_playing = true;
2760 playing = false;
2761 paused = true;
2762 #endif /* SIMULATOR */
2765 void audio_resume(void)
2767 #ifndef SIMULATOR
2768 queue_post(&mpeg_queue, MPEG_RESUME, 0);
2769 #else /* SIMULATOR */
2770 is_playing = true;
2771 playing = true;
2772 paused = false;
2773 #endif /* SIMULATOR */
2776 void audio_next(void)
2778 #ifndef SIMULATOR
2779 queue_remove_from_head(&mpeg_queue, MPEG_NEED_DATA);
2780 queue_post(&mpeg_queue, MPEG_NEXT, 0);
2781 #else /* SIMULATOR */
2782 char* file;
2783 int steps = 1;
2784 int index;
2786 do {
2787 file = playlist_peek(steps);
2788 if(!file)
2789 break;
2790 if(mp3info(&taginfo, file, v1first)) {
2791 if(++steps > playlist_amount())
2792 break;
2793 continue;
2795 index = playlist_next(steps);
2796 taginfo.index = index;
2797 current_track_counter++;
2798 is_playing = true;
2799 playing = true;
2800 break;
2801 } while(1);
2802 #endif /* SIMULATOR */
2805 void audio_prev(void)
2807 #ifndef SIMULATOR
2808 queue_remove_from_head(&mpeg_queue, MPEG_NEED_DATA);
2809 queue_post(&mpeg_queue, MPEG_PREV, 0);
2810 #else /* SIMULATOR */
2811 char* file;
2812 int steps = -1;
2813 int index;
2815 do {
2816 file = playlist_peek(steps);
2817 if(!file)
2818 break;
2819 if(mp3info(&taginfo, file, v1first)) {
2820 steps--;
2821 continue;
2823 index = playlist_next(steps);
2824 taginfo.index = index;
2825 current_track_counter++;
2826 is_playing = true;
2827 playing = true;
2828 break;
2829 } while(1);
2830 #endif /* SIMULATOR */
2833 void audio_ff_rewind(long newtime)
2835 #ifndef SIMULATOR
2836 queue_post(&mpeg_queue, MPEG_FF_REWIND, newtime);
2837 #else /* SIMULATOR */
2838 (void)newtime;
2839 #endif /* SIMULATOR */
2842 void audio_flush_and_reload_tracks(void)
2844 #ifndef SIMULATOR
2845 queue_post(&mpeg_queue, MPEG_FLUSH_RELOAD, 0);
2846 #endif /* !SIMULATOR*/
2849 int audio_status(void)
2851 int ret = 0;
2853 if(is_playing)
2854 ret |= AUDIO_STATUS_PLAY;
2856 if(paused)
2857 ret |= AUDIO_STATUS_PAUSE;
2859 #if (CONFIG_CODEC == MAS3587F) && !defined(SIMULATOR)
2860 if(is_recording && !is_prerecording)
2861 ret |= AUDIO_STATUS_RECORD;
2863 if(is_prerecording)
2864 ret |= AUDIO_STATUS_PRERECORD;
2865 #endif /* CONFIG_CODEC == MAS3587F */
2867 if(mpeg_errno)
2868 ret |= AUDIO_STATUS_ERROR;
2870 return ret;
2873 unsigned int audio_error(void)
2875 return mpeg_errno;
2878 void audio_error_clear(void)
2880 mpeg_errno = 0;
2883 #ifdef SIMULATOR
2884 static void mpeg_thread(void)
2886 struct mp3entry* id3;
2887 while ( 1 ) {
2888 if (is_playing) {
2889 id3 = audio_current_track();
2890 if (!paused)
2892 id3->elapsed+=1000;
2893 id3->offset+=1000;
2895 if (id3->elapsed>=id3->length)
2896 audio_next();
2898 sleep(HZ);
2901 #endif /* SIMULATOR */
2903 void audio_init(void)
2905 mpeg_errno = 0;
2906 track_buffer_callback = NULL;
2907 track_unbuffer_callback = NULL;
2908 track_changed_callback = NULL;
2910 #ifndef SIMULATOR
2911 audiobuflen = audiobufend - audiobuf;
2912 queue_init(&mpeg_queue, true);
2913 #endif /* !SIMULATOR */
2914 create_thread(mpeg_thread, mpeg_stack,
2915 sizeof(mpeg_stack), mpeg_thread_name IF_PRIO(, PRIORITY_SYSTEM)
2916 IF_COP(, CPU, false));
2918 memset(trackdata, sizeof(trackdata), 0);
2920 #if (CONFIG_CODEC == MAS3587F) && !defined(SIMULATOR)
2921 if (HW_MASK & PR_ACTIVE_HIGH)
2922 and_b(~0x08, &PADRH);
2923 else
2924 or_b(0x08, &PADRH);
2925 #endif /* CONFIG_CODEC == MAS3587F */
2927 #ifdef DEBUG
2928 dbg_timer_start();
2929 dbg_cnt2us(0);
2930 #endif /* DEBUG */
2933 #endif /* CONFIG_CODEC != SWCODEC */