* Onda VX747: add browse screen, pitchscreen, context menu, quickscreen, rewind...
[kugel-rb.git] / apps / mpeg.c
blobe28260b6a727fcdcc4a2d7311d5afd8217c1b237
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 #include "cuesheet.h"
44 #include "settings.h"
45 #ifndef SIMULATOR
46 #include "i2c.h"
47 #include "mas.h"
48 #include "system.h"
49 #include "usb.h"
50 #include "file.h"
51 #include "hwcompat.h"
52 #endif /* !SIMULATOR */
53 #ifdef HAVE_LCD_BITMAP
54 #include "lcd.h"
55 #endif
57 #ifndef SIMULATOR
58 extern unsigned long mas_version_code;
59 #endif
61 #if CONFIG_CODEC == MAS3587F
62 extern enum /* from mp3_playback.c */
64 MPEG_DECODER,
65 MPEG_ENCODER
66 } mpeg_mode;
67 #endif /* CONFIG_CODEC == MAS3587F */
69 extern char* playlist_peek(int steps);
70 extern bool playlist_check(int steps);
71 extern int playlist_next(int steps);
72 extern int playlist_amount(void);
73 extern int playlist_update_resume_info(const struct mp3entry* id3);
75 #define MPEG_PLAY 1
76 #define MPEG_STOP 2
77 #define MPEG_PAUSE 3
78 #define MPEG_RESUME 4
79 #define MPEG_NEXT 5
80 #define MPEG_PREV 6
81 #define MPEG_FF_REWIND 7
82 #define MPEG_FLUSH_RELOAD 8
83 #define MPEG_RECORD 9
84 #define MPEG_INIT_RECORDING 10
85 #define MPEG_INIT_PLAYBACK 11
86 #define MPEG_NEW_FILE 12
87 #define MPEG_PAUSE_RECORDING 13
88 #define MPEG_RESUME_RECORDING 14
89 #define MPEG_NEED_DATA 100
90 #define MPEG_TRACK_CHANGE 101
91 #define MPEG_SAVE_DATA 102
92 #define MPEG_STOP_DONE 103
93 #define MPEG_PRERECORDING_TICK 104
95 /* indicator for MPEG_NEED_DATA */
96 #define GENERATE_UNBUFFER_EVENTS 1
98 /* list of tracks in memory */
99 #define MAX_TRACK_ENTRIES (1<<4) /* Must be power of 2 */
100 #define MAX_TRACK_ENTRIES_MASK (MAX_TRACK_ENTRIES - 1)
102 struct trackdata
104 struct mp3entry id3;
105 int mempos;
106 int load_ahead_index;
109 static struct trackdata trackdata[MAX_TRACK_ENTRIES];
111 static unsigned int current_track_counter = 0;
113 /* Play time of the previous track */
114 unsigned long prev_track_elapsed;
116 #ifndef SIMULATOR
117 static int track_read_idx = 0;
118 static int track_write_idx = 0;
119 #endif /* !SIMULATOR */
121 /* Cuesheet support */
122 static struct cuesheet *curr_cuesheet = NULL;
123 static bool checked_for_cuesheet = false;
125 static const char mpeg_thread_name[] = "mpeg";
126 static unsigned int mpeg_errno;
128 static bool playing = false; /* We are playing an MP3 stream */
129 static bool is_playing = false; /* We are (attempting to) playing MP3 files */
130 static bool paused; /* playback is paused */
132 #ifdef SIMULATOR
133 static char mpeg_stack[DEFAULT_STACK_SIZE];
134 static struct mp3entry taginfo;
136 #else /* !SIMULATOR */
137 static struct event_queue mpeg_queue;
138 static long mpeg_stack[(DEFAULT_STACK_SIZE + 0x1000)/sizeof(long)];
140 static int audiobuflen;
141 static int audiobuf_write;
142 static int audiobuf_swapwrite;
143 static int audiobuf_read;
145 static int mpeg_file;
147 static bool play_pending; /* We are about to start playing */
148 static bool play_pending_track_change; /* When starting play we're starting a new file */
149 static bool filling; /* We are filling the buffer with data from disk */
150 static bool dma_underrun; /* True when the DMA has stopped because of
151 slow disk reading (read error, shaking) */
152 static bool mpeg_stop_done;
154 static int last_dma_tick = 0;
155 static int last_dma_chunk_size;
157 static long low_watermark; /* Dynamic low watermark level */
158 static long low_watermark_margin = 0; /* Extra time in seconds for watermark */
159 static long lowest_watermark_level; /* Debug value to observe the buffer
160 usage */
161 #if CONFIG_CODEC == MAS3587F
162 static char recording_filename[MAX_PATH]; /* argument to thread */
163 static char delayed_filename[MAX_PATH]; /* internal copy of above */
165 static char xing_buffer[MAX_XING_HEADER_SIZE];
167 static bool init_recording_done;
168 static bool init_playback_done;
169 static bool prerecording; /* True if prerecording is enabled */
170 static bool is_prerecording; /* True if we are prerecording */
171 static bool is_recording; /* We are recording */
173 static enum {
174 NOT_SAVING = 0, /* reasons to save data, sorted by importance */
175 BUFFER_FULL,
176 NEW_FILE,
177 STOP_RECORDING
178 } saving_status;
180 static int rec_frequency_index; /* For create_xing_header() calls */
181 static int rec_version_index; /* For create_xing_header() calls */
183 struct prerecord_info {
184 int mempos;
185 unsigned long framecount;
188 static struct prerecord_info prerecord_buffer[MPEG_MAX_PRERECORD_SECONDS];
189 static int prerecord_index; /* Current index in the prerecord buffer */
190 static int prerecording_max_seconds; /* Max number of seconds to store */
191 static int prerecord_count; /* Number of seconds in the prerecord buffer */
192 static int prerecord_timeout; /* The tick count of the next prerecord data
193 store */
195 unsigned long record_start_time; /* Value of current_tick when recording
196 was started */
197 unsigned long pause_start_time; /* Value of current_tick when pause was
198 started */
199 static unsigned long last_rec_time;
200 static unsigned long num_rec_bytes;
201 static unsigned long last_rec_bytes;
202 static unsigned long frame_count_start;
203 static unsigned long frame_count_end;
204 static unsigned long saved_header = 0;
206 /* Shadow MAS registers */
207 unsigned long shadow_encoder_control = 0;
208 #endif /* CONFIG_CODEC == MAS3587F */
210 #if (CONFIG_CODEC == MAS3587F) || (CONFIG_CODEC == MAS3539F)
211 unsigned long shadow_io_control_main = 0;
212 unsigned long shadow_soft_mute = 0;
213 unsigned shadow_codec_reg0;
214 #endif /* (CONFIG_CODEC == MAS3587F) || (CONFIG_CODEC == MAS3539F) */
216 #ifdef HAVE_RECORDING
217 static const unsigned char empty_id3_header[] =
219 'I', 'D', '3', 0x03, 0x00, 0x00,
220 0x00, 0x00, 0x1f, 0x76 /* Size is 4096 minus 10 bytes for the header */
222 #endif /* HAVE_RECORDING */
225 static int get_unplayed_space(void);
226 static int get_playable_space(void);
227 static int get_unswapped_space(void);
228 #endif /* !SIMULATOR */
230 #if (CONFIG_CODEC == MAS3587F) && !defined(SIMULATOR)
231 static void init_recording(void);
232 static void prepend_header(void);
233 static void update_header(void);
234 static void start_prerecording(void);
235 static void start_recording(void);
236 static void stop_recording(void);
237 static int get_unsaved_space(void);
238 static void pause_recording(void);
239 static void resume_recording(void);
240 #endif /* (CONFIG_CODEC == MAS3587F) && !defined(SIMULATOR) */
243 #ifndef SIMULATOR
244 static int num_tracks_in_memory(void)
246 return (track_write_idx - track_read_idx) & MAX_TRACK_ENTRIES_MASK;
249 #ifdef DEBUG_TAGS
250 static void debug_tags(void)
252 int i;
254 for(i = 0;i < MAX_TRACK_ENTRIES;i++)
256 DEBUGF("%d - %s\n", i, trackdata[i].id3.path);
258 DEBUGF("read: %d, write :%d\n", track_read_idx, track_write_idx);
259 DEBUGF("num_tracks_in_memory: %d\n", num_tracks_in_memory());
261 #else /* !DEBUG_TAGS */
262 #define debug_tags()
263 #endif /* !DEBUG_TAGS */
265 static void remove_current_tag(void)
267 if(num_tracks_in_memory() > 0)
269 /* First move the index, so nobody tries to access the tag */
270 track_read_idx = (track_read_idx+1) & MAX_TRACK_ENTRIES_MASK;
271 checked_for_cuesheet = false;
272 debug_tags();
274 else
276 DEBUGF("remove_current_tag: no tracks to remove\n");
280 static void remove_all_non_current_tags(void)
282 track_write_idx = (track_read_idx+1) & MAX_TRACK_ENTRIES_MASK;
283 debug_tags();
286 static void remove_all_tags(void)
288 track_write_idx = track_read_idx;
290 debug_tags();
293 static struct trackdata *get_trackdata(int offset)
295 if(offset >= num_tracks_in_memory())
296 return NULL;
297 else
298 return &trackdata[(track_read_idx + offset) & MAX_TRACK_ENTRIES_MASK];
300 #endif /* !SIMULATOR */
302 /***********************************************************************/
303 /* audio event handling */
305 #define MAX_EVENT_HANDLERS 10
306 struct event_handlers_table
308 AUDIO_EVENT_HANDLER handler;
309 unsigned short mask;
311 static struct event_handlers_table event_handlers[MAX_EVENT_HANDLERS];
312 static int event_handlers_count = 0;
314 void audio_register_event_handler(AUDIO_EVENT_HANDLER handler, unsigned short mask)
316 if (event_handlers_count < MAX_EVENT_HANDLERS)
318 event_handlers[event_handlers_count].handler = handler;
319 event_handlers[event_handlers_count].mask = mask;
320 event_handlers_count++;
324 /* dispatch calls each handler in the order registered and returns after some
325 handler actually handles the event (the event is assumed to no longer be valid
326 after this, due to the handler changing some condition); returns true if someone
327 handled the event, which is expected to cause the caller to skip its own handling
328 of the event */
329 #ifndef SIMULATOR
330 static bool audio_dispatch_event(unsigned short event, unsigned long data)
332 int i = 0;
333 for(i=0; i < event_handlers_count; i++)
335 if ( event_handlers[i].mask & event )
337 int rc = event_handlers[i].handler(event, data);
338 if ( rc == AUDIO_EVENT_RC_HANDLED )
339 return true;
342 return false;
344 #endif
346 /***********************************************************************/
348 static void set_elapsed(struct mp3entry* id3)
350 if ( id3->vbr ) {
351 if ( id3->has_toc ) {
352 /* calculate elapsed time using TOC */
353 int i;
354 unsigned int remainder, plen, relpos, nextpos;
356 /* find wich percent we're at */
357 for (i=0; i<100; i++ )
359 if ( id3->offset < id3->toc[i] * (id3->filesize / 256) )
361 break;
365 i--;
366 if (i < 0)
367 i = 0;
369 relpos = id3->toc[i];
371 if (i < 99)
373 nextpos = id3->toc[i+1];
375 else
377 nextpos = 256;
380 remainder = id3->offset - (relpos * (id3->filesize / 256));
382 /* set time for this percent (divide before multiply to prevent
383 overflow on long files. loss of precision is negligible on
384 short files) */
385 id3->elapsed = i * (id3->length / 100);
387 /* calculate remainder time */
388 plen = (nextpos - relpos) * (id3->filesize / 256);
389 id3->elapsed += (((remainder * 100) / plen) *
390 (id3->length / 10000));
392 else {
393 /* no TOC exists. set a rough estimate using average bitrate */
394 int tpk = id3->length / (id3->filesize / 1024);
395 id3->elapsed = id3->offset / 1024 * tpk;
398 else
399 /* constant bitrate, use exact calculation */
400 id3->elapsed = id3->offset / (id3->bitrate / 8);
403 int audio_get_file_pos(void)
405 int pos = -1;
406 struct mp3entry *id3 = audio_current_track();
408 if (id3->vbr)
410 if (id3->has_toc)
412 /* Use the TOC to find the new position */
413 unsigned int percent, remainder;
414 int curtoc, nexttoc, plen;
416 percent = (id3->elapsed*100)/id3->length;
417 if (percent > 99)
418 percent = 99;
420 curtoc = id3->toc[percent];
422 if (percent < 99)
423 nexttoc = id3->toc[percent+1];
424 else
425 nexttoc = 256;
427 pos = (id3->filesize/256)*curtoc;
429 /* Use the remainder to get a more accurate position */
430 remainder = (id3->elapsed*100)%id3->length;
431 remainder = (remainder*100)/id3->length;
432 plen = (nexttoc - curtoc)*(id3->filesize/256);
433 pos += (plen/100)*remainder;
435 else
437 /* No TOC exists, estimate the new position */
438 pos = (id3->filesize / (id3->length / 1000)) *
439 (id3->elapsed / 1000);
442 else if (id3->bitrate)
443 pos = id3->elapsed * (id3->bitrate / 8);
444 else
446 return -1;
449 if (pos >= (int)(id3->filesize - id3->id3v1len))
451 /* Don't seek right to the end of the file so that we can
452 transition properly to the next song */
453 pos = id3->filesize - id3->id3v1len - 1;
455 else if (pos < (int)id3->first_frame_offset)
457 /* skip past id3v2 tag and other leading garbage */
458 pos = id3->first_frame_offset;
460 return pos;
463 unsigned long mpeg_get_last_header(void)
465 #ifdef SIMULATOR
466 return 0;
467 #else /* !SIMULATOR */
468 unsigned long tmp[2];
470 /* Read the frame data from the MAS and reconstruct it with the
471 frame sync and all */
472 mas_readmem(MAS_BANK_D0, MAS_D0_MPEG_STATUS_1, tmp, 2);
473 return 0xffe00000 | ((tmp[0] & 0x7c00) << 6) | (tmp[1] & 0xffff);
474 #endif /* !SIMULATOR */
477 #ifndef SIMULATOR
478 /* Send callback events to notify about removing old tracks. */
479 static void generate_unbuffer_events(void)
481 int i;
482 int numentries = MAX_TRACK_ENTRIES - num_tracks_in_memory();
483 int cur_idx = track_write_idx;
485 for (i = 0; i < numentries; i++)
487 /* Send an event to notify that track has finished. */
488 send_event(PLAYBACK_EVENT_TRACK_FINISH, &trackdata[cur_idx].id3);
489 cur_idx = (cur_idx + 1) & MAX_TRACK_ENTRIES_MASK;
493 /* Send callback events to notify about new tracks. */
494 static void generate_postbuffer_events(void)
496 int i;
497 int numentries = num_tracks_in_memory();
498 int cur_idx = track_read_idx;
500 for (i = 0; i < numentries; i++)
502 send_event(PLAYBACK_EVENT_TRACK_BUFFER, &trackdata[cur_idx].id3);
503 cur_idx = (cur_idx + 1) & MAX_TRACK_ENTRIES_MASK;
507 static void recalculate_watermark(int bitrate)
509 int bytes_per_sec;
510 int time = storage_spinup_time();
512 /* A bitrate of 0 probably means empty VBR header. We play safe
513 and set a high threshold */
514 if(bitrate == 0)
515 bitrate = 320;
517 bytes_per_sec = bitrate * 1000 / 8;
519 if(time)
521 /* No drive spins up faster than 3.5s */
522 if(time < 350)
523 time = 350;
525 time = time * 3;
526 low_watermark = ((low_watermark_margin * HZ + time) *
527 bytes_per_sec) / HZ;
529 else
531 low_watermark = MPEG_LOW_WATER;
535 #ifdef HAVE_DISK_STORAGE
536 void audio_set_buffer_margin(int seconds)
538 low_watermark_margin = seconds;
540 #endif
542 void audio_get_debugdata(struct audio_debug *dbgdata)
544 dbgdata->audiobuflen = audiobuflen;
545 dbgdata->audiobuf_write = audiobuf_write;
546 dbgdata->audiobuf_swapwrite = audiobuf_swapwrite;
547 dbgdata->audiobuf_read = audiobuf_read;
549 dbgdata->last_dma_chunk_size = last_dma_chunk_size;
551 #if CONFIG_CPU == SH7034
552 dbgdata->dma_on = (SCR0 & 0x80) != 0;
553 #endif
554 dbgdata->playing = playing;
555 dbgdata->play_pending = play_pending;
556 dbgdata->is_playing = is_playing;
557 dbgdata->filling = filling;
558 dbgdata->dma_underrun = dma_underrun;
560 dbgdata->unplayed_space = get_unplayed_space();
561 dbgdata->playable_space = get_playable_space();
562 dbgdata->unswapped_space = get_unswapped_space();
564 dbgdata->low_watermark_level = low_watermark;
565 dbgdata->lowest_watermark_level = lowest_watermark_level;
568 #ifdef DEBUG
569 static void dbg_timer_start(void)
571 /* We are using timer 2 */
573 TSTR &= ~0x04; /* Stop the timer */
574 TSNC &= ~0x04; /* No synchronization */
575 TMDR &= ~0x44; /* Operate normally */
577 TCNT2 = 0; /* Start counting at 0 */
578 TCR2 = 0x03; /* Sysclock/8 */
580 TSTR |= 0x04; /* Start timer 2 */
583 static int dbg_cnt2us(unsigned int cnt)
585 return (cnt * 10000) / (FREQ/800);
587 #endif /* DEBUG */
589 static int get_unplayed_space(void)
591 int space = audiobuf_write - audiobuf_read;
592 if (space < 0)
593 space += audiobuflen;
594 return space;
597 static int get_playable_space(void)
599 int space = audiobuf_swapwrite - audiobuf_read;
600 if (space < 0)
601 space += audiobuflen;
602 return space;
605 static int get_unplayed_space_current_song(void)
607 int space;
609 if (num_tracks_in_memory() > 1)
611 space = get_trackdata(1)->mempos - audiobuf_read;
613 else
615 space = audiobuf_write - audiobuf_read;
618 if (space < 0)
619 space += audiobuflen;
621 return space;
624 static int get_unswapped_space(void)
626 int space = audiobuf_write - audiobuf_swapwrite;
627 if (space < 0)
628 space += audiobuflen;
629 return space;
632 #if CONFIG_CODEC == MAS3587F
633 static int get_unsaved_space(void)
635 int space = audiobuf_write - audiobuf_read;
636 if (space < 0)
637 space += audiobuflen;
638 return space;
641 static void drain_dma_buffer(void)
643 while (PBDRH & 0x40)
645 xor_b(0x08, &PADRH);
647 while (PBDRH & 0x80);
649 xor_b(0x08, &PADRH);
651 while (!(PBDRH & 0x80));
655 #ifdef DEBUG
656 static long timing_info_index = 0;
657 static long timing_info[1024];
658 #endif /* DEBUG */
660 void rec_tick (void) __attribute__ ((section (".icode")));
661 void rec_tick(void)
663 int i;
664 int delay;
665 char data;
667 if(is_recording && (PBDRH & 0x40))
669 #ifdef DEBUG
670 timing_info[timing_info_index++] = current_tick;
671 TCNT2 = 0;
672 #endif /* DEBUG */
673 /* Note: Although this loop is run in interrupt context, further
674 * optimisation will do no good. The MAS would then deliver bad
675 * frames occasionally, as observed in extended experiments. */
676 i = 0;
677 while (PBDRH & 0x40) /* We try to read as long as EOD is high */
679 xor_b(0x08, &PADRH); /* Set PR active, independent of polarity */
681 delay = 100;
682 while (PBDRH & 0x80) /* Wait until /RTW becomes active */
684 if (--delay <= 0) /* Bail out if we have to wait too long */
685 { /* i.e. the MAS doesn't want to talk to us */
686 xor_b(0x08, &PADRH); /* Set PR inactive */
687 goto transfer_end; /* and get out of here */
691 data = *(unsigned char *)0x04000000; /* read data byte */
693 xor_b(0x08, &PADRH); /* Set PR inactive */
695 audiobuf[audiobuf_write++] = data;
697 if (audiobuf_write >= audiobuflen)
698 audiobuf_write = 0;
700 i++;
702 transfer_end:
704 #ifdef DEBUG
705 timing_info[timing_info_index++] = TCNT2 + (i << 16);
706 timing_info_index &= 0x3ff;
707 #endif /* DEBUG */
709 num_rec_bytes += i;
711 if(is_prerecording)
713 if(TIME_AFTER(current_tick, prerecord_timeout))
715 prerecord_timeout = current_tick + HZ;
716 queue_post(&mpeg_queue, MPEG_PRERECORDING_TICK, 0);
719 else
721 /* Signal to save the data if we are running out of buffer
722 space */
723 if (audiobuflen - get_unsaved_space() < MPEG_RECORDING_LOW_WATER
724 && saving_status == NOT_SAVING)
726 saving_status = BUFFER_FULL;
727 queue_post(&mpeg_queue, MPEG_SAVE_DATA, 0);
732 #endif /* CONFIG_CODEC == MAS3587F */
734 void playback_tick(void)
736 struct trackdata *ptd = get_trackdata(0);
737 if(ptd)
739 ptd->id3.elapsed += (current_tick - last_dma_tick) * 1000 / HZ;
740 last_dma_tick = current_tick;
741 audio_dispatch_event(AUDIO_EVENT_POS_REPORT,
742 (unsigned long)ptd->id3.elapsed);
746 static void reset_mp3_buffer(void)
748 audiobuf_read = 0;
749 audiobuf_write = 0;
750 audiobuf_swapwrite = 0;
751 lowest_watermark_level = audiobuflen;
754 /* DMA transfer end interrupt callback */
755 static void transfer_end(unsigned char** ppbuf, size_t* psize)
757 if(playing && !paused)
759 int unplayed_space_left;
760 int space_until_end_of_buffer;
761 int track_offset = 1;
762 struct trackdata *track;
764 audiobuf_read += last_dma_chunk_size;
765 if(audiobuf_read >= audiobuflen)
766 audiobuf_read = 0;
768 /* First, check if we are on a track boundary */
769 if (num_tracks_in_memory() > 1)
771 if (audiobuf_read == get_trackdata(track_offset)->mempos)
773 if ( ! audio_dispatch_event(AUDIO_EVENT_END_OF_TRACK, 0) )
775 queue_post(&mpeg_queue, MPEG_TRACK_CHANGE, 0);
776 track_offset++;
781 unplayed_space_left = get_unplayed_space();
783 space_until_end_of_buffer = audiobuflen - audiobuf_read;
785 if(!filling && unplayed_space_left < low_watermark)
787 filling = true;
788 queue_post(&mpeg_queue, MPEG_NEED_DATA, GENERATE_UNBUFFER_EVENTS);
791 if(unplayed_space_left)
793 last_dma_chunk_size = MIN(0x2000, unplayed_space_left);
794 last_dma_chunk_size = MIN(last_dma_chunk_size,
795 space_until_end_of_buffer);
797 /* several tracks loaded? */
798 track = get_trackdata(track_offset);
799 if(track)
801 /* will we move across the track boundary? */
802 if (( audiobuf_read < track->mempos ) &&
803 ((audiobuf_read+last_dma_chunk_size) >
804 track->mempos ))
806 /* Make sure that we end exactly on the boundary */
807 last_dma_chunk_size = track->mempos - audiobuf_read;
811 *psize = last_dma_chunk_size & 0xffff;
812 *ppbuf = audiobuf + audiobuf_read;
813 track = get_trackdata(0);
814 if(track)
815 track->id3.offset += last_dma_chunk_size;
817 /* Update the watermark debug level */
818 if(unplayed_space_left < lowest_watermark_level)
819 lowest_watermark_level = unplayed_space_left;
821 else
823 /* Check if the end of data is because of a hard disk error.
824 If there is an open file handle, we are still playing music.
825 If not, the last file has been loaded, and the file handle is
826 closed. */
827 if(mpeg_file >= 0)
829 /* Update the watermark debug level */
830 if(unplayed_space_left < lowest_watermark_level)
831 lowest_watermark_level = unplayed_space_left;
833 DEBUGF("DMA underrun.\n");
834 dma_underrun = true;
836 else
838 if ( ! audio_dispatch_event(AUDIO_EVENT_END_OF_TRACK, 0) )
840 DEBUGF("No more MP3 data. Stopping.\n");
841 queue_post(&mpeg_queue, MPEG_TRACK_CHANGE, 0);
842 playing = false;
845 *psize = 0; /* no more transfer */
850 static struct trackdata *add_track_to_tag_list(const char *filename)
852 struct trackdata *track;
853 bool send_nid3_event;
855 if(num_tracks_in_memory() >= MAX_TRACK_ENTRIES)
857 DEBUGF("Tag memory is full\n");
858 return NULL;
861 track = &trackdata[track_write_idx];
863 /* grab id3 tag of new file and
864 remember where in memory it starts */
865 if(mp3info(&track->id3, filename))
867 DEBUGF("Bad mp3\n");
868 return NULL;
870 track->mempos = audiobuf_write;
871 track->id3.elapsed = 0;
872 #ifdef HAVE_LCD_BITMAP
873 if (track->id3.title)
874 lcd_getstringsize(track->id3.title, NULL, NULL);
875 if (track->id3.artist)
876 lcd_getstringsize(track->id3.artist, NULL, NULL);
877 if (track->id3.album)
878 lcd_getstringsize(track->id3.album, NULL, NULL);
879 #endif
881 /* if this track is the next track then let the UI know it can get it */
882 send_nid3_event = (track_write_idx == track_read_idx + 1);
883 track_write_idx = (track_write_idx+1) & MAX_TRACK_ENTRIES_MASK;
884 if (send_nid3_event)
885 send_event(PLAYBACK_EVENT_NEXTTRACKID3_AVAILABLE, NULL);
886 debug_tags();
887 return track;
890 static int new_file(int steps)
892 int max_steps = playlist_amount();
893 int start = 0;
894 int i;
895 struct trackdata *track;
897 /* Find out how many steps to advance. The load_ahead_index field tells
898 us how many playlist entries it had to skip to get to a valid one.
899 We add those together to find out where to start. */
900 if(steps > 0 && num_tracks_in_memory() > 1)
902 /* Begin with the song after the currently playing one */
903 i = 1;
904 while((track = get_trackdata(i++)))
906 start += track->load_ahead_index;
910 do {
911 char *trackname;
913 trackname = playlist_peek( start + steps );
914 if ( !trackname )
915 return -1;
917 DEBUGF("Loading %s\n", trackname);
919 mpeg_file = open(trackname, O_RDONLY);
920 if(mpeg_file < 0) {
921 DEBUGF("Couldn't open file: %s\n",trackname);
922 if(steps < 0)
923 steps--;
924 else
925 steps++;
927 else
929 struct trackdata *track = add_track_to_tag_list(trackname);
931 if(!track)
933 /* Bad mp3 file */
934 if(steps < 0)
935 steps--;
936 else
937 steps++;
938 close(mpeg_file);
939 mpeg_file = -1;
941 else
943 /* skip past id3v2 tag */
944 lseek(mpeg_file,
945 track->id3.first_frame_offset,
946 SEEK_SET);
947 track->id3.index = steps;
948 track->load_ahead_index = steps;
949 track->id3.offset = 0;
951 if(track->id3.vbr)
952 /* Average bitrate * 1.5 */
953 recalculate_watermark(
954 (track->id3.bitrate * 3) / 2);
955 else
956 recalculate_watermark(
957 track->id3.bitrate);
962 /* Bail out if no file could be opened */
963 if(abs(steps) > max_steps)
964 return -1;
965 } while ( mpeg_file < 0 );
967 return 0;
970 static void stop_playing(void)
972 struct trackdata *track;
974 /* Stop the current stream */
975 mp3_play_stop();
976 playing = false;
977 filling = false;
979 track = get_trackdata(0);
980 if (track != NULL)
981 prev_track_elapsed = track->id3.elapsed;
983 if(mpeg_file >= 0)
984 close(mpeg_file);
985 mpeg_file = -1;
986 remove_all_tags();
987 generate_unbuffer_events();
988 reset_mp3_buffer();
991 static void end_current_track(void) {
992 struct trackdata *track;
994 play_pending = false;
995 playing = false;
996 mp3_play_pause(false);
998 track = get_trackdata(0);
999 if (track != NULL)
1000 prev_track_elapsed = track->id3.elapsed;
1002 reset_mp3_buffer();
1003 remove_all_tags();
1004 generate_unbuffer_events();
1006 if(mpeg_file >= 0)
1007 close(mpeg_file);
1010 /* Is this a really the end of playback or is a new playlist starting */
1011 static void check_playlist_end(int direction)
1013 /* Use the largest possible step size to account for skipped tracks */
1014 int steps = playlist_amount();
1016 if (direction < 0)
1017 steps = -steps;
1019 if (playlist_next(steps) < 0)
1020 is_playing = false;
1023 static void update_playlist(void)
1025 if (num_tracks_in_memory() > 0)
1027 struct trackdata *track = get_trackdata(0);
1028 track->id3.index = playlist_next(track->id3.index);
1030 else
1032 /* End of playlist? */
1033 check_playlist_end(1);
1036 playlist_update_resume_info(audio_current_track());
1039 static void track_change(void)
1041 DEBUGF("Track change\n");
1043 struct trackdata *track = get_trackdata(0);
1044 prev_track_elapsed = track->id3.elapsed;
1046 #if (CONFIG_CODEC == MAS3587F) || (CONFIG_CODEC == MAS3539F)
1047 /* Reset the AVC */
1048 sound_set_avc(-1);
1049 #endif /* (CONFIG_CODEC == MAS3587F) || (CONFIG_CODEC == MAS3539F) */
1051 if (num_tracks_in_memory() > 0)
1053 remove_current_tag();
1054 update_playlist();
1055 if (is_playing)
1056 send_event(PLAYBACK_EVENT_TRACK_CHANGE, audio_current_track());
1059 current_track_counter++;
1062 unsigned long audio_prev_elapsed(void)
1064 return prev_track_elapsed;
1067 #ifdef DEBUG
1068 void hexdump(const unsigned char *buf, int len)
1070 int i;
1072 for(i = 0;i < len;i++)
1074 if(i && (i & 15) == 0)
1076 DEBUGF("\n");
1078 DEBUGF("%02x ", buf[i]);
1080 DEBUGF("\n");
1082 #endif /* DEBUG */
1084 static void start_playback_if_ready(void)
1086 int playable_space;
1088 playable_space = audiobuf_swapwrite - audiobuf_read;
1089 if(playable_space < 0)
1090 playable_space += audiobuflen;
1092 /* See if we have started playing yet. If not, do it. */
1093 if(play_pending || dma_underrun)
1095 /* If the filling has stopped, and we still haven't reached
1096 the watermark, the file must be smaller than the
1097 watermark. We must still play it. */
1098 if((playable_space >= MPEG_PLAY_PENDING_THRESHOLD) ||
1099 !filling || dma_underrun)
1101 DEBUGF("P\n");
1102 if (play_pending) /* don't do this when recovering from DMA underrun */
1104 generate_postbuffer_events(); /* signal first track as buffered */
1105 if (play_pending_track_change)
1107 play_pending_track_change = false;
1108 send_event(PLAYBACK_EVENT_TRACK_CHANGE, audio_current_track());
1110 play_pending = false;
1112 playing = true;
1114 last_dma_chunk_size = MIN(0x2000, get_unplayed_space_current_song());
1115 mp3_play_data(audiobuf + audiobuf_read, last_dma_chunk_size, transfer_end);
1116 dma_underrun = false;
1118 if (!paused)
1120 last_dma_tick = current_tick;
1121 mp3_play_pause(true);
1124 /* Tell ourselves that we need more data */
1125 queue_post(&mpeg_queue, MPEG_NEED_DATA, 0);
1130 static bool swap_one_chunk(void)
1132 int free_space_left;
1133 int amount_to_swap;
1135 free_space_left = get_unswapped_space();
1137 if(free_space_left == 0 && !play_pending)
1138 return false;
1140 /* Swap in larger chunks when the user is waiting for the playback
1141 to start, or when there is dangerously little playable data left */
1142 if(play_pending)
1143 amount_to_swap = MIN(MPEG_PLAY_PENDING_SWAPSIZE, free_space_left);
1144 else
1146 if(get_playable_space() < low_watermark)
1147 amount_to_swap = MIN(MPEG_LOW_WATER_SWAP_CHUNKSIZE,
1148 free_space_left);
1149 else
1150 amount_to_swap = MIN(MPEG_SWAP_CHUNKSIZE, free_space_left);
1153 if(audiobuf_write < audiobuf_swapwrite)
1154 amount_to_swap = MIN(audiobuflen - audiobuf_swapwrite,
1155 amount_to_swap);
1156 else
1157 amount_to_swap = MIN(audiobuf_write - audiobuf_swapwrite,
1158 amount_to_swap);
1160 bitswap(audiobuf + audiobuf_swapwrite, amount_to_swap);
1162 audiobuf_swapwrite += amount_to_swap;
1163 if(audiobuf_swapwrite >= audiobuflen)
1165 audiobuf_swapwrite = 0;
1168 return true;
1171 static void mpeg_thread(void)
1173 static int pause_tick = 0;
1174 static unsigned int pause_track = 0;
1175 struct queue_event ev;
1176 int len;
1177 int free_space_left;
1178 int unplayed_space_left;
1179 int amount_to_read;
1180 int t1, t2;
1181 int start_offset;
1182 #if CONFIG_CODEC == MAS3587F
1183 int amount_to_save;
1184 int save_endpos = 0;
1185 int rc;
1186 int level;
1187 long offset;
1188 #endif /* CONFIG_CODEC == MAS3587F */
1190 is_playing = false;
1191 play_pending = false;
1192 playing = false;
1193 mpeg_file = -1;
1195 while(1)
1197 #if CONFIG_CODEC == MAS3587F
1198 if(mpeg_mode == MPEG_DECODER)
1200 #endif /* CONFIG_CODEC == MAS3587F */
1201 yield();
1203 /* Swap if necessary, and don't block on the queue_wait() */
1204 if(swap_one_chunk())
1206 queue_wait_w_tmo(&mpeg_queue, &ev, 0);
1208 else if (playing)
1210 /* periodically update resume info */
1211 queue_wait_w_tmo(&mpeg_queue, &ev, HZ/2);
1213 else
1215 DEBUGF("S R:%x W:%x SW:%x\n",
1216 audiobuf_read, audiobuf_write, audiobuf_swapwrite);
1217 queue_wait(&mpeg_queue, &ev);
1220 start_playback_if_ready();
1222 switch(ev.id)
1224 case MPEG_PLAY:
1225 DEBUGF("MPEG_PLAY\n");
1227 #if CONFIG_TUNER
1228 /* Silence the A/D input, it may be on because the radio
1229 may be playing */
1230 mas_codec_writereg(6, 0x0000);
1231 #endif /* CONFIG_TUNER */
1233 /* Stop the current stream */
1234 paused = false;
1235 end_current_track();
1237 if ( new_file(0) == -1 )
1239 is_playing = false;
1240 track_change();
1241 break;
1244 start_offset = (int)ev.data;
1246 /* mid-song resume? */
1247 if (start_offset) {
1248 struct mp3entry* id3 = &get_trackdata(0)->id3;
1249 lseek(mpeg_file, start_offset, SEEK_SET);
1250 id3->offset = start_offset;
1251 set_elapsed(id3);
1253 else {
1254 /* skip past id3v2 tag */
1255 lseek(mpeg_file,
1256 get_trackdata(0)->id3.first_frame_offset,
1257 SEEK_SET);
1261 /* Make it read more data */
1262 filling = true;
1263 queue_post(&mpeg_queue, MPEG_NEED_DATA, 0);
1265 /* Tell the file loading code that we want to start playing
1266 as soon as we have some data */
1267 play_pending = true;
1268 play_pending_track_change = true;
1270 update_playlist();
1271 current_track_counter++;
1272 break;
1274 case MPEG_STOP:
1275 DEBUGF("MPEG_STOP\n");
1276 is_playing = false;
1277 paused = false;
1279 if (playing)
1280 playlist_update_resume_info(audio_current_track());
1282 stop_playing();
1283 mpeg_stop_done = true;
1284 break;
1286 case MPEG_PAUSE:
1287 DEBUGF("MPEG_PAUSE\n");
1288 /* Stop the current stream */
1289 if (playing)
1290 playlist_update_resume_info(audio_current_track());
1291 paused = true;
1292 playing = false;
1293 pause_tick = current_tick;
1294 pause_track = current_track_counter;
1295 mp3_play_pause(false);
1296 break;
1298 case MPEG_RESUME:
1299 DEBUGF("MPEG_RESUME\n");
1300 /* Continue the current stream */
1301 paused = false;
1302 if (!play_pending)
1304 playing = true;
1305 if ( current_track_counter == pause_track )
1306 last_dma_tick += current_tick - pause_tick;
1307 else
1308 last_dma_tick = current_tick;
1309 pause_tick = 0;
1310 mp3_play_pause(true);
1312 break;
1314 case MPEG_NEXT:
1315 DEBUGF("MPEG_NEXT\n");
1316 /* is next track in ram? */
1317 if ( num_tracks_in_memory() > 1 ) {
1318 int unplayed_space_left, unswapped_space_left;
1320 /* stop the current stream */
1321 play_pending = false;
1322 playing = false;
1323 mp3_play_pause(false);
1325 track_change();
1326 audiobuf_read = get_trackdata(0)->mempos;
1327 last_dma_chunk_size = MIN(0x2000, get_unplayed_space_current_song());
1328 mp3_play_data(audiobuf + audiobuf_read, last_dma_chunk_size, transfer_end);
1329 dma_underrun = false;
1330 last_dma_tick = current_tick;
1332 unplayed_space_left = get_unplayed_space();
1333 unswapped_space_left = get_unswapped_space();
1335 /* should we start reading more data? */
1336 if(!filling && (unplayed_space_left < low_watermark)) {
1337 filling = true;
1338 queue_post(&mpeg_queue, MPEG_NEED_DATA, GENERATE_UNBUFFER_EVENTS);
1339 play_pending = true;
1340 } else if(unswapped_space_left &&
1341 unswapped_space_left > unplayed_space_left) {
1342 /* Stop swapping the data from the previous file */
1343 audiobuf_swapwrite = audiobuf_read;
1344 play_pending = true;
1345 } else {
1346 playing = true;
1347 if (!paused)
1348 mp3_play_pause(true);
1351 else {
1352 if (!playlist_check(1))
1353 break;
1355 /* stop the current stream */
1356 end_current_track();
1358 if (new_file(1) < 0) {
1359 DEBUGF("No more files to play\n");
1360 filling = false;
1362 check_playlist_end(1);
1363 current_track_counter++;
1364 } else {
1365 /* Make it read more data */
1366 filling = true;
1367 queue_post(&mpeg_queue, MPEG_NEED_DATA, 0);
1369 /* Tell the file loading code that we want
1370 to start playing as soon as we have some data */
1371 play_pending = true;
1372 play_pending_track_change = true;
1374 update_playlist();
1375 current_track_counter++;
1378 break;
1380 case MPEG_PREV: {
1381 DEBUGF("MPEG_PREV\n");
1383 if (!playlist_check(-1))
1384 break;
1386 /* stop the current stream */
1387 end_current_track();
1389 /* Open the next file */
1390 if (new_file(-1) < 0) {
1391 DEBUGF("No more files to play\n");
1392 filling = false;
1394 check_playlist_end(-1);
1395 current_track_counter++;
1396 } else {
1397 /* Make it read more data */
1398 filling = true;
1399 queue_post(&mpeg_queue, MPEG_NEED_DATA, 0);
1401 /* Tell the file loading code that we want to
1402 start playing as soon as we have some data */
1403 play_pending = true;
1404 play_pending_track_change = true;
1406 update_playlist();
1407 current_track_counter++;
1409 break;
1412 case MPEG_FF_REWIND: {
1413 struct mp3entry *id3 = audio_current_track();
1414 unsigned int oldtime = id3->elapsed;
1415 unsigned int newtime = (unsigned int)ev.data;
1416 int curpos, newpos, diffpos;
1417 DEBUGF("MPEG_FF_REWIND\n");
1419 id3->elapsed = newtime;
1421 newpos = audio_get_file_pos();
1422 if(newpos < 0)
1424 id3->elapsed = oldtime;
1425 break;
1428 if (mpeg_file >= 0)
1429 curpos = lseek(mpeg_file, 0, SEEK_CUR);
1430 else
1431 curpos = id3->filesize;
1433 if (num_tracks_in_memory() > 1)
1435 /* We have started loading other tracks that need to be
1436 accounted for */
1437 struct trackdata *track;
1438 int i = 0;
1440 while((track = get_trackdata(i++)))
1442 curpos += track->id3.filesize;
1446 diffpos = curpos - newpos;
1448 if(!filling && diffpos >= 0 && diffpos < audiobuflen)
1450 int unplayed_space_left, unswapped_space_left;
1452 /* We are changing to a position that's already in
1453 memory, so we just move the DMA read pointer. */
1454 audiobuf_read = audiobuf_write - diffpos;
1455 if (audiobuf_read < 0)
1457 audiobuf_read += audiobuflen;
1460 unplayed_space_left = get_unplayed_space();
1461 unswapped_space_left = get_unswapped_space();
1463 /* If unswapped_space_left is larger than
1464 unplayed_space_left, it means that the swapwrite pointer
1465 hasn't yet advanced up to the new location of the read
1466 pointer. We just move it, there is no need to swap
1467 data that won't be played anyway. */
1469 if (unswapped_space_left > unplayed_space_left)
1471 DEBUGF("Moved swapwrite\n");
1472 audiobuf_swapwrite = audiobuf_read;
1473 play_pending = true;
1476 if (mpeg_file>=0 && unplayed_space_left < low_watermark)
1478 /* We need to load more data before starting */
1479 filling = true;
1480 queue_post(&mpeg_queue, MPEG_NEED_DATA, GENERATE_UNBUFFER_EVENTS);
1481 play_pending = true;
1483 else
1485 /* resume will start at new position */
1486 last_dma_chunk_size =
1487 MIN(0x2000, get_unplayed_space_current_song());
1488 mp3_play_data(audiobuf + audiobuf_read,
1489 last_dma_chunk_size, transfer_end);
1490 dma_underrun = false;
1493 else
1495 /* Move to the new position in the file and start
1496 loading data */
1497 reset_mp3_buffer();
1499 if (num_tracks_in_memory() > 1)
1501 /* We have to reload the current track */
1502 close(mpeg_file);
1503 remove_all_non_current_tags();
1504 generate_unbuffer_events();
1505 mpeg_file = -1;
1508 if (mpeg_file < 0)
1510 mpeg_file = open(id3->path, O_RDONLY);
1511 if (mpeg_file < 0)
1513 id3->elapsed = oldtime;
1514 break;
1518 if(-1 == lseek(mpeg_file, newpos, SEEK_SET))
1520 id3->elapsed = oldtime;
1521 break;
1524 filling = true;
1525 queue_post(&mpeg_queue, MPEG_NEED_DATA, 0);
1527 /* Tell the file loading code that we want to start playing
1528 as soon as we have some data */
1529 play_pending = true;
1532 id3->offset = newpos;
1534 break;
1537 case MPEG_FLUSH_RELOAD: {
1538 int numtracks = num_tracks_in_memory();
1539 bool reload_track = false;
1541 if (numtracks > 1)
1543 /* Reset the buffer */
1544 audiobuf_write = get_trackdata(1)->mempos;
1546 /* Reset swapwrite unless we're still swapping current
1547 track */
1548 if (get_unplayed_space() <= get_playable_space())
1549 audiobuf_swapwrite = audiobuf_write;
1551 close(mpeg_file);
1552 remove_all_non_current_tags();
1553 generate_unbuffer_events();
1554 mpeg_file = -1;
1555 reload_track = true;
1557 else if (numtracks == 1 && mpeg_file < 0)
1559 reload_track = true;
1562 if(reload_track && new_file(1) >= 0)
1564 /* Tell ourselves that we want more data */
1565 filling = true;
1566 queue_post(&mpeg_queue, MPEG_NEED_DATA, 0);
1569 break;
1572 case MPEG_NEED_DATA:
1573 free_space_left = audiobuf_read - audiobuf_write;
1575 /* We interpret 0 as "empty buffer" */
1576 if(free_space_left <= 0)
1577 free_space_left += audiobuflen;
1579 unplayed_space_left = audiobuflen - free_space_left;
1581 /* Make sure that we don't fill the entire buffer */
1582 free_space_left -= MPEG_HIGH_WATER;
1584 if (ev.data == GENERATE_UNBUFFER_EVENTS)
1585 generate_unbuffer_events();
1587 /* do we have any more buffer space to fill? */
1588 if(free_space_left <= 0)
1590 DEBUGF("0\n");
1591 filling = false;
1592 generate_postbuffer_events();
1593 storage_sleep();
1594 break;
1597 /* Read small chunks while we are below the low water mark */
1598 if(unplayed_space_left < low_watermark)
1599 amount_to_read = MIN(MPEG_LOW_WATER_CHUNKSIZE,
1600 free_space_left);
1601 else
1602 amount_to_read = free_space_left;
1604 /* Don't read more than until the end of the buffer */
1605 amount_to_read = MIN(audiobuflen - audiobuf_write,
1606 amount_to_read);
1607 #if (CONFIG_STORAGE & STORAGE_MMC)
1608 /* MMC is slow, so don't read too large chunks */
1609 amount_to_read = MIN(0x40000, amount_to_read);
1610 #elif MEM == 8
1611 amount_to_read = MIN(0x100000, amount_to_read);
1612 #endif
1614 /* Read as much mpeg data as we can fit in the buffer */
1615 if(mpeg_file >= 0)
1617 DEBUGF("R\n");
1618 t1 = current_tick;
1619 len = read(mpeg_file, audiobuf + audiobuf_write,
1620 amount_to_read);
1621 if(len > 0)
1623 t2 = current_tick;
1624 DEBUGF("time: %d\n", t2 - t1);
1625 DEBUGF("R: %x\n", len);
1627 /* Now make sure that we don't feed the MAS with ID3V1
1628 data */
1629 if (len < amount_to_read)
1631 int i;
1632 static const unsigned char tag[] = "TAG";
1633 int taglen = 128;
1634 int tagptr = audiobuf_write + len - 128;
1636 /* Really rare case: entire potential tag wasn't
1637 read in this call AND audiobuf_write < 128 */
1638 if (tagptr < 0)
1639 tagptr += audiobuflen;
1641 for(i = 0;i < 3;i++)
1643 if(tagptr >= audiobuflen)
1644 tagptr -= audiobuflen;
1646 if(audiobuf[tagptr] != tag[i])
1648 taglen = 0;
1649 break;
1652 tagptr++;
1655 if(taglen)
1657 /* Skip id3v1 tag */
1658 DEBUGF("Skipping ID3v1 tag\n");
1659 len -= taglen;
1661 /* In the very rare case when the entire tag
1662 wasn't read in this read() len will be < 0.
1663 Take care of this when changing the write
1664 pointer. */
1668 audiobuf_write += len;
1670 if (audiobuf_write < 0)
1671 audiobuf_write += audiobuflen;
1673 if(audiobuf_write >= audiobuflen)
1675 audiobuf_write = 0;
1676 DEBUGF("W\n");
1679 /* Tell ourselves that we want more data */
1680 queue_post(&mpeg_queue, MPEG_NEED_DATA, 0);
1682 else
1684 if(len < 0)
1686 DEBUGF("MPEG read error\n");
1689 close(mpeg_file);
1690 mpeg_file = -1;
1692 if(new_file(1) < 0)
1694 /* No more data to play */
1695 DEBUGF("No more files to play\n");
1696 filling = false;
1698 else
1700 /* Tell ourselves that we want more data */
1701 queue_post(&mpeg_queue, MPEG_NEED_DATA, 0);
1705 break;
1707 case MPEG_TRACK_CHANGE:
1708 track_change();
1709 break;
1711 #ifndef USB_NONE
1712 case SYS_USB_CONNECTED:
1713 is_playing = false;
1714 paused = false;
1715 stop_playing();
1717 /* Tell the USB thread that we are safe */
1718 DEBUGF("mpeg_thread got SYS_USB_CONNECTED\n");
1719 usb_acknowledge(SYS_USB_CONNECTED_ACK);
1721 /* Wait until the USB cable is extracted again */
1722 usb_wait_for_disconnect(&mpeg_queue);
1723 break;
1724 #endif /* !USB_NONE */
1726 #if CONFIG_CODEC == MAS3587F
1727 case MPEG_INIT_RECORDING:
1728 init_recording();
1729 init_recording_done = true;
1730 break;
1731 #endif /* CONFIG_CODEC == MAS3587F */
1733 case SYS_TIMEOUT:
1734 if (playing)
1735 playlist_update_resume_info(audio_current_track());
1736 break;
1738 #if CONFIG_CODEC == MAS3587F
1740 else
1742 queue_wait(&mpeg_queue, &ev);
1743 switch(ev.id)
1745 case MPEG_RECORD:
1746 if (is_prerecording)
1748 int startpos;
1750 /* Go back prerecord_count seconds in the buffer */
1751 startpos = prerecord_index - prerecord_count;
1752 if(startpos < 0)
1753 startpos += prerecording_max_seconds;
1755 /* Read the position data from the prerecord buffer */
1756 frame_count_start = prerecord_buffer[startpos].framecount;
1757 startpos = prerecord_buffer[startpos].mempos;
1759 DEBUGF("Start looking at address %x (%x)\n",
1760 audiobuf+startpos, startpos);
1762 saved_header = mpeg_get_last_header();
1764 mem_find_next_frame(startpos, &offset, 1800,
1765 saved_header);
1767 audiobuf_read = startpos + offset;
1768 if(audiobuf_read >= audiobuflen)
1769 audiobuf_read -= audiobuflen;
1771 DEBUGF("New audiobuf_read address: %x (%x)\n",
1772 audiobuf+audiobuf_read, audiobuf_read);
1774 level = disable_irq_save();
1775 num_rec_bytes = get_unsaved_space();
1776 restore_irq(level);
1778 else
1780 frame_count_start = 0;
1781 num_rec_bytes = 0;
1782 audiobuf_read = MPEG_RESERVED_HEADER_SPACE;
1783 audiobuf_write = MPEG_RESERVED_HEADER_SPACE;
1786 prepend_header();
1787 DEBUGF("Recording...\n");
1788 start_recording();
1790 /* Wait until at least one frame is encoded and get the
1791 frame header, for later use by the Xing header
1792 generation */
1793 sleep(HZ/5);
1794 saved_header = mpeg_get_last_header();
1796 /* delayed until buffer is saved, don't open yet */
1797 strcpy(delayed_filename, recording_filename);
1798 mpeg_file = -1;
1800 break;
1802 case MPEG_STOP:
1803 DEBUGF("MPEG_STOP\n");
1805 stop_recording();
1807 /* Save the remaining data in the buffer */
1808 save_endpos = audiobuf_write;
1809 saving_status = STOP_RECORDING;
1810 queue_post(&mpeg_queue, MPEG_SAVE_DATA, 0);
1811 break;
1813 case MPEG_STOP_DONE:
1814 DEBUGF("MPEG_STOP_DONE\n");
1816 if (mpeg_file >= 0)
1817 close(mpeg_file);
1818 mpeg_file = -1;
1820 update_header();
1821 #ifdef DEBUG1
1823 int i;
1824 for(i = 0;i < 512;i++)
1826 DEBUGF("%d - %d us (%d bytes)\n",
1827 timing_info[i*2],
1828 (timing_info[i*2+1] & 0xffff) *
1829 10000 / 13824,
1830 timing_info[i*2+1] >> 16);
1833 #endif /* DEBUG1 */
1835 if (prerecording)
1837 start_prerecording();
1839 mpeg_stop_done = true;
1840 break;
1842 case MPEG_NEW_FILE:
1843 /* Bail out when a more important save is happening */
1844 if (saving_status > NEW_FILE)
1845 break;
1847 /* Make sure we have at least one complete frame
1848 in the buffer. If we haven't recorded a single
1849 frame within 200ms, the MAS is probably not recording
1850 anything, and we bail out. */
1851 amount_to_save = get_unsaved_space();
1852 if (amount_to_save < 1800)
1854 sleep(HZ/5);
1855 amount_to_save = get_unsaved_space();
1858 mas_readmem(MAS_BANK_D0, MAS_D0_MPEG_FRAME_COUNT,
1859 &frame_count_end, 1);
1861 last_rec_time = current_tick - record_start_time;
1862 record_start_time = current_tick;
1863 if (paused)
1864 pause_start_time = record_start_time;
1866 /* capture all values at one point */
1867 level = disable_irq_save();
1868 save_endpos = audiobuf_write;
1869 last_rec_bytes = num_rec_bytes;
1870 num_rec_bytes = 0;
1871 restore_irq(level);
1873 if (amount_to_save >= 1800)
1875 /* Now find a frame boundary to split at */
1876 save_endpos -= 1800;
1877 if (save_endpos < 0)
1878 save_endpos += audiobuflen;
1880 rc = mem_find_next_frame(save_endpos, &offset, 1800,
1881 saved_header);
1882 if (!rc) /* No header found, save whole buffer */
1883 offset = 1800;
1885 save_endpos += offset;
1886 if (save_endpos >= audiobuflen)
1887 save_endpos -= audiobuflen;
1889 last_rec_bytes += offset - 1800;
1890 level = disable_irq_save();
1891 num_rec_bytes += 1800 - offset;
1892 restore_irq(level);
1895 saving_status = NEW_FILE;
1896 queue_post(&mpeg_queue, MPEG_SAVE_DATA, 0);
1897 break;
1899 case MPEG_SAVE_DATA:
1900 if (saving_status == BUFFER_FULL)
1901 save_endpos = audiobuf_write;
1903 if (mpeg_file < 0) /* delayed file open */
1905 mpeg_file = open(delayed_filename, O_WRONLY|O_CREAT);
1907 if (mpeg_file < 0)
1908 panicf("recfile: %d", mpeg_file);
1911 amount_to_save = save_endpos - audiobuf_read;
1912 if (amount_to_save < 0)
1913 amount_to_save += audiobuflen;
1915 amount_to_save = MIN(amount_to_save,
1916 audiobuflen - audiobuf_read);
1917 #if (CONFIG_STORAGE & STORAGE_MMC)
1918 /* MMC is slow, so don't save too large chunks at once */
1919 amount_to_save = MIN(0x40000, amount_to_save);
1920 #elif MEM == 8
1921 amount_to_save = MIN(0x100000, amount_to_save);
1922 #endif
1923 rc = write(mpeg_file, audiobuf + audiobuf_read,
1924 amount_to_save);
1925 if (rc < 0)
1927 if (errno == ENOSPC)
1929 mpeg_errno = AUDIOERR_DISK_FULL;
1930 stop_recording();
1931 queue_post(&mpeg_queue, MPEG_STOP_DONE, 0);
1932 /* will close the file */
1933 break;
1935 else
1936 panicf("rec wrt: %d", rc);
1939 audiobuf_read += amount_to_save;
1940 if (audiobuf_read >= audiobuflen)
1941 audiobuf_read = 0;
1943 if (audiobuf_read == save_endpos) /* all saved */
1945 switch (saving_status)
1947 case BUFFER_FULL:
1948 rc = fsync(mpeg_file);
1949 if (rc < 0)
1950 panicf("rec fls: %d", rc);
1951 storage_sleep();
1952 break;
1954 case NEW_FILE:
1955 /* Close the current file */
1956 rc = close(mpeg_file);
1957 if (rc < 0)
1958 panicf("rec cls: %d", rc);
1959 mpeg_file = -1;
1960 update_header();
1961 storage_sleep();
1963 /* copy new filename */
1964 strcpy(delayed_filename, recording_filename);
1965 prepend_header();
1966 frame_count_start = frame_count_end;
1967 break;
1969 case STOP_RECORDING:
1970 queue_post(&mpeg_queue, MPEG_STOP_DONE, 0);
1971 /* will close the file */
1972 break;
1974 default:
1975 break;
1977 saving_status = NOT_SAVING;
1979 else /* tell ourselves to save the next chunk */
1980 queue_post(&mpeg_queue, MPEG_SAVE_DATA, 0);
1982 break;
1984 case MPEG_PRERECORDING_TICK:
1985 if(!is_prerecording)
1986 break;
1988 /* Store the write pointer every second */
1989 prerecord_buffer[prerecord_index].mempos = audiobuf_write;
1990 mas_readmem(MAS_BANK_D0, MAS_D0_MPEG_FRAME_COUNT,
1991 &prerecord_buffer[prerecord_index].framecount, 1);
1993 /* Wrap if necessary */
1994 if(++prerecord_index == prerecording_max_seconds)
1995 prerecord_index = 0;
1997 /* Update the number of seconds recorded */
1998 if(prerecord_count < prerecording_max_seconds)
1999 prerecord_count++;
2000 break;
2002 case MPEG_INIT_PLAYBACK:
2003 /* Stop the prerecording */
2004 stop_recording();
2005 reset_mp3_buffer();
2006 mp3_play_init();
2007 init_playback_done = true;
2008 break;
2010 case MPEG_PAUSE_RECORDING:
2011 pause_recording();
2012 break;
2014 case MPEG_RESUME_RECORDING:
2015 resume_recording();
2016 break;
2018 case SYS_USB_CONNECTED:
2019 /* We can safely go to USB mode if no recording
2020 is taking place */
2021 if((!is_recording || is_prerecording) && mpeg_stop_done)
2023 /* Even if we aren't recording, we still call this
2024 function, to put the MAS in monitoring mode,
2025 to save power. */
2026 stop_recording();
2028 /* Tell the USB thread that we are safe */
2029 DEBUGF("mpeg_thread got SYS_USB_CONNECTED\n");
2030 usb_acknowledge(SYS_USB_CONNECTED_ACK);
2032 /* Wait until the USB cable is extracted again */
2033 usb_wait_for_disconnect(&mpeg_queue);
2035 break;
2038 #endif /* CONFIG_CODEC == MAS3587F */
2041 #endif /* !SIMULATOR */
2043 struct mp3entry* audio_current_track()
2045 #ifdef SIMULATOR
2046 struct mp3entry *id3 = &taginfo;
2047 #else /* !SIMULATOR */
2048 if(num_tracks_in_memory())
2050 struct mp3entry *id3 = &get_trackdata(0)->id3;
2051 #endif
2052 if (!checked_for_cuesheet && curr_cuesheet && id3->cuesheet == NULL)
2054 checked_for_cuesheet = true; /* only check once per track */
2055 char cuepath[MAX_PATH];
2057 if (look_for_cuesheet_file(id3->path, cuepath) &&
2058 parse_cuesheet(cuepath, curr_cuesheet))
2060 id3->cuesheet = curr_cuesheet;
2061 cue_spoof_id3(curr_cuesheet, id3);
2064 return id3;
2065 #ifndef SIMULATOR
2067 else
2068 return NULL;
2069 #endif /* !SIMULATOR */
2072 struct mp3entry* audio_next_track()
2074 #ifdef SIMULATOR
2075 return &taginfo;
2076 #else /* !SIMULATOR */
2077 if(num_tracks_in_memory() > 1)
2078 return &get_trackdata(1)->id3;
2079 else
2080 return NULL;
2081 #endif /* !SIMULATOR */
2084 #if CONFIG_CODEC == MAS3587F
2085 #ifndef SIMULATOR
2086 void audio_init_playback(void)
2088 init_playback_done = false;
2089 queue_post(&mpeg_queue, MPEG_INIT_PLAYBACK, 0);
2091 while(!init_playback_done)
2092 sleep(1);
2096 /****************************************************************************
2097 * Recording functions
2098 ***************************************************************************/
2099 void audio_init_recording(unsigned int buffer_offset)
2101 buffer_offset = buffer_offset;
2102 init_recording_done = false;
2103 queue_post(&mpeg_queue, MPEG_INIT_RECORDING, 0);
2105 while(!init_recording_done)
2106 sleep(1);
2109 static void init_recording(void)
2111 unsigned long val;
2112 int rc;
2114 /* Disable IRQ6 */
2115 IPRB &= 0xff0f;
2117 stop_playing();
2118 is_playing = false;
2119 paused = false;
2121 /* Init the recording variables */
2122 is_recording = false;
2123 is_prerecording = false;
2125 mpeg_stop_done = true;
2127 mas_reset();
2129 /* Enable the audio CODEC and the DSP core, max analog voltage range */
2130 rc = mas_direct_config_write(MAS_CONTROL, 0x8c00);
2131 if(rc < 0)
2132 panicf("mas_ctrl_w: %d", rc);
2134 /* Stop the current application */
2135 val = 0;
2136 mas_writemem(MAS_BANK_D0, MAS_D0_APP_SELECT, &val, 1);
2139 mas_readmem(MAS_BANK_D0, MAS_D0_APP_RUNNING, &val, 1);
2140 } while(val);
2142 /* Perform black magic as described by the data sheet */
2143 if((mas_version_code & 0x0fff) == 0x0102)
2145 DEBUGF("Performing MAS black magic for B2 version\n");
2146 mas_writereg(0xa3, 0x98);
2147 mas_writereg(0x94, 0xfffff);
2148 val = 0;
2149 mas_writemem(MAS_BANK_D1, 0, &val, 1);
2150 mas_writereg(0xa3, 0x90);
2153 /* Enable A/D Converters */
2154 shadow_codec_reg0 = 0xcccd;
2155 mas_codec_writereg(0x0, shadow_codec_reg0);
2157 /* Copy left channel to right (mono mode) */
2158 mas_codec_writereg(8, 0x8000);
2160 /* ADC scale 0%, DSP scale 100%
2161 We use the DSP output for monitoring, because it works with all
2162 sources including S/PDIF */
2163 mas_codec_writereg(6, 0x0000);
2164 mas_codec_writereg(7, 0x4000);
2166 /* No mute */
2167 shadow_soft_mute = 0;
2168 mas_writemem(MAS_BANK_D0, MAS_D0_SOFT_MUTE, &shadow_soft_mute, 1);
2170 #ifdef HAVE_SPDIF_OUT
2171 val = 0x09; /* Disable SDO and SDI, low impedance S/PDIF outputs */
2172 #else
2173 val = 0x2d; /* Disable SDO and SDI, disable S/PDIF output */
2174 #endif
2175 mas_writemem(MAS_BANK_D0, MAS_D0_INTERFACE_CONTROL, &val, 1);
2177 /* Set Demand mode, monitoring OFF and validate all settings */
2178 shadow_io_control_main = 0x125;
2179 mas_writemem(MAS_BANK_D0, MAS_D0_IO_CONTROL_MAIN, &shadow_io_control_main, 1);
2181 /* Start the encoder application */
2182 val = 0x40;
2183 mas_writemem(MAS_BANK_D0, MAS_D0_APP_SELECT, &val, 1);
2186 mas_readmem(MAS_BANK_D0, MAS_D0_APP_RUNNING, &val, 1);
2187 } while(!(val & 0x40));
2189 /* We have started the recording application with monitoring OFF.
2190 This is because we want to record at least one frame to fill the DMA
2191 buffer, because the silly MAS will not negate EOD until at least one
2192 DMA transfer has taken place.
2193 Now let's wait for some data to be encoded. */
2194 sleep(HZ/5);
2196 /* Now set it to Monitoring mode as default, saves power */
2197 shadow_io_control_main = 0x525;
2198 mas_writemem(MAS_BANK_D0, MAS_D0_IO_CONTROL_MAIN, &shadow_io_control_main, 1);
2200 /* Wait until the DSP has accepted the settings */
2203 mas_readmem(MAS_BANK_D0, MAS_D0_IO_CONTROL_MAIN, &val,1);
2204 } while(val & 1);
2206 drain_dma_buffer();
2207 mpeg_mode = MPEG_ENCODER;
2209 DEBUGF("MAS Recording application started\n");
2211 /* At this point, all settings are the reset MAS defaults, next thing is to
2212 call mpeg_set_recording_options(). */
2215 void audio_record(const char *filename)
2217 mpeg_errno = 0;
2219 strlcpy(recording_filename, filename, MAX_PATH);
2221 queue_post(&mpeg_queue, MPEG_RECORD, 0);
2224 void audio_pause_recording(void)
2226 queue_post(&mpeg_queue, MPEG_PAUSE_RECORDING, 0);
2229 void audio_resume_recording(void)
2231 queue_post(&mpeg_queue, MPEG_RESUME_RECORDING, 0);
2234 static void prepend_header(void)
2236 int startpos;
2237 unsigned i;
2239 /* Make room for header */
2240 audiobuf_read -= MPEG_RESERVED_HEADER_SPACE;
2241 if(audiobuf_read < 0)
2243 /* Clear the bottom half */
2244 memset(audiobuf, 0, audiobuf_read + MPEG_RESERVED_HEADER_SPACE);
2246 /* And the top half */
2247 audiobuf_read += audiobuflen;
2248 memset(audiobuf + audiobuf_read, 0, audiobuflen - audiobuf_read);
2250 else
2252 memset(audiobuf + audiobuf_read, 0, MPEG_RESERVED_HEADER_SPACE);
2254 /* Copy the empty ID3 header */
2255 startpos = audiobuf_read;
2256 for(i = 0; i < sizeof(empty_id3_header); i++)
2258 audiobuf[startpos++] = empty_id3_header[i];
2259 if(startpos == audiobuflen)
2260 startpos = 0;
2264 static void update_header(void)
2266 int fd, framelen;
2267 unsigned long frames;
2269 if (last_rec_bytes > 0)
2271 /* Create the Xing header */
2272 fd = open(delayed_filename, O_RDWR);
2273 if (fd < 0)
2274 panicf("rec upd: %d (%s)", fd, recording_filename);
2276 frames = frame_count_end - frame_count_start;
2277 /* If the number of recorded frames has reached 0x7ffff,
2278 we can no longer trust it */
2279 if (frame_count_end == 0x7ffff)
2280 frames = 0;
2282 /* saved_header is saved right before stopping the MAS */
2283 framelen = create_xing_header(fd, 0, last_rec_bytes, xing_buffer,
2284 frames, last_rec_time * (1000/HZ),
2285 saved_header, NULL, false);
2287 lseek(fd, MPEG_RESERVED_HEADER_SPACE - framelen, SEEK_SET);
2288 write(fd, xing_buffer, framelen);
2289 close(fd);
2293 static void start_prerecording(void)
2295 unsigned long val;
2297 DEBUGF("Starting prerecording\n");
2299 prerecord_index = 0;
2300 prerecord_count = 0;
2301 prerecord_timeout = current_tick + HZ;
2302 memset(prerecord_buffer, 0, sizeof(prerecord_buffer));
2303 reset_mp3_buffer();
2305 is_prerecording = true;
2307 /* Stop monitoring and start the encoder */
2308 shadow_io_control_main &= ~(1 << 10);
2309 mas_writemem(MAS_BANK_D0, MAS_D0_IO_CONTROL_MAIN, &shadow_io_control_main, 1);
2310 DEBUGF("mas_writemem(MAS_BANK_D0, IO_CONTROL_MAIN, %x)\n", shadow_io_control_main);
2312 /* Wait until the DSP has accepted the settings */
2315 mas_readmem(MAS_BANK_D0, MAS_D0_IO_CONTROL_MAIN, &val,1);
2316 } while(val & 1);
2318 is_recording = true;
2319 saving_status = NOT_SAVING;
2321 demand_irq_enable(true);
2324 static void start_recording(void)
2326 unsigned long val;
2328 if(is_prerecording)
2330 /* This will make the IRQ handler start recording
2331 for real, i.e send MPEG_SAVE_DATA messages when
2332 the buffer is full */
2333 is_prerecording = false;
2335 else
2337 /* If prerecording is off, we need to stop the monitoring
2338 and start the encoder */
2339 shadow_io_control_main &= ~(1 << 10);
2340 mas_writemem(MAS_BANK_D0, MAS_D0_IO_CONTROL_MAIN, &shadow_io_control_main, 1);
2341 DEBUGF("mas_writemem(MAS_BANK_D0, IO_CONTROL_MAIN, %x)\n", shadow_io_control_main);
2343 /* Wait until the DSP has accepted the settings */
2346 mas_readmem(MAS_BANK_D0, MAS_D0_IO_CONTROL_MAIN, &val,1);
2347 } while(val & 1);
2350 is_recording = true;
2351 saving_status = NOT_SAVING;
2352 paused = false;
2354 /* Store the current time */
2355 if(prerecording)
2356 record_start_time = current_tick - prerecord_count * HZ;
2357 else
2358 record_start_time = current_tick;
2360 pause_start_time = 0;
2362 demand_irq_enable(true);
2365 static void pause_recording(void)
2367 pause_start_time = current_tick;
2369 /* Set the pause bit */
2370 shadow_soft_mute |= 2;
2371 mas_writemem(MAS_BANK_D0, MAS_D0_SOFT_MUTE, &shadow_soft_mute, 1);
2373 paused = true;
2376 static void resume_recording(void)
2378 paused = false;
2380 /* Clear the pause bit */
2381 shadow_soft_mute &= ~2;
2382 mas_writemem(MAS_BANK_D0, MAS_D0_SOFT_MUTE, &shadow_soft_mute, 1);
2384 /* Compensate for the time we have been paused */
2385 if(pause_start_time)
2387 record_start_time =
2388 current_tick - (pause_start_time - record_start_time);
2389 pause_start_time = 0;
2393 static void stop_recording(void)
2395 unsigned long val;
2397 /* Let it finish the last frame */
2398 if(!paused)
2399 pause_recording();
2400 sleep(HZ/5);
2402 demand_irq_enable(false);
2404 is_recording = false;
2405 is_prerecording = false;
2407 last_rec_bytes = num_rec_bytes;
2408 mas_readmem(MAS_BANK_D0, MAS_D0_MPEG_FRAME_COUNT, &frame_count_end, 1);
2409 last_rec_time = current_tick - record_start_time;
2411 /* Start monitoring */
2412 shadow_io_control_main |= (1 << 10);
2413 mas_writemem(MAS_BANK_D0, MAS_D0_IO_CONTROL_MAIN, &shadow_io_control_main, 1);
2414 DEBUGF("mas_writemem(MAS_BANK_D0, IO_CONTROL_MAIN, %x)\n", shadow_io_control_main);
2416 /* Wait until the DSP has accepted the settings */
2419 mas_readmem(MAS_BANK_D0, MAS_D0_IO_CONTROL_MAIN, &val,1);
2420 } while(val & 1);
2422 resume_recording();
2425 void audio_set_recording_options(struct audio_recording_options *options)
2427 bool is_mpeg1;
2429 is_mpeg1 = (options->rec_frequency < 3);
2431 rec_version_index = is_mpeg1?3:2;
2432 rec_frequency_index = options->rec_frequency % 3;
2434 shadow_encoder_control = (options->rec_quality << 17) |
2435 (rec_frequency_index << 10) |
2436 ((is_mpeg1?1:0) << 9) |
2437 (((options->rec_channels * 2 + 1) & 3) << 6) |
2438 (1 << 5) /* MS-stereo */ |
2439 (1 << 2) /* Is an original */;
2440 mas_writemem(MAS_BANK_D0, MAS_D0_ENCODER_CONTROL, &shadow_encoder_control,1);
2442 DEBUGF("mas_writemem(MAS_BANK_D0, ENCODER_CONTROL, %x)\n", shadow_encoder_control);
2444 #if CONFIG_TUNER & S1A0903X01
2445 /* Store the (unpitched) MAS PLL frequency. Used for avoiding FM
2446 interference with the Samsung tuner. */
2447 if (rec_frequency_index)
2448 mas_store_pllfreq(24576000);
2449 else
2450 mas_store_pllfreq(22579000);
2451 #endif
2453 shadow_soft_mute = options->rec_editable?4:0;
2454 mas_writemem(MAS_BANK_D0, MAS_D0_SOFT_MUTE, &shadow_soft_mute,1);
2456 DEBUGF("mas_writemem(MAS_BANK_D0, SOFT_MUTE, %x)\n", shadow_soft_mute);
2458 shadow_io_control_main = ((1 << 10) | /* Monitoring ON */
2459 ((options->rec_source < 2)?1:2) << 8) | /* Input select */
2460 (1 << 5) | /* SDO strobe invert */
2461 ((is_mpeg1?0:1) << 3) |
2462 (1 << 2) | /* Inverted SIBC clock signal */
2463 1; /* Validate */
2464 mas_writemem(MAS_BANK_D0, MAS_D0_IO_CONTROL_MAIN, &shadow_io_control_main,1);
2466 DEBUGF("mas_writemem(MAS_BANK_D0, IO_CONTROL_MAIN, %x)\n", shadow_io_control_main);
2468 if(options->rec_source == AUDIO_SRC_MIC)
2470 /* Copy left channel to right (mono mode) */
2471 mas_codec_writereg(8, 0x8000);
2473 else
2475 /* Stereo input mode */
2476 mas_codec_writereg(8, 0);
2479 prerecording_max_seconds = options->rec_prerecord_time;
2480 if(prerecording_max_seconds)
2482 prerecording = true;
2483 start_prerecording();
2485 else
2487 prerecording = false;
2488 is_prerecording = false;
2489 is_recording = false;
2493 /* If use_mic is true, the left gain is used */
2494 void audio_set_recording_gain(int left, int right, int type)
2496 /* Enable both left and right A/D */
2497 shadow_codec_reg0 = (left << 12) |
2498 (right << 8) |
2499 (left << 4) |
2500 (type==AUDIO_GAIN_MIC?0x0008:0) | /* Connect left A/D to mic */
2501 0x0007;
2502 mas_codec_writereg(0x0, shadow_codec_reg0);
2505 /* try to make some kind of beep, also in recording mode */
2506 void audio_beep(int duration)
2508 long starttick = current_tick;
2510 { /* toggle bit 0 of codec register 0, toggling the DAC off & on.
2511 * While this is still audible even without an external signal,
2512 * it doesn't affect the (pre-)recording. */
2513 mas_codec_writereg(0, shadow_codec_reg0 ^ 1);
2514 mas_codec_writereg(0, shadow_codec_reg0);
2515 yield();
2517 while (current_tick - starttick < duration);
2520 void audio_new_file(const char *filename)
2522 mpeg_errno = 0;
2524 strlcpy(recording_filename, filename, MAX_PATH);
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;
2847 /* cuesheet support */
2848 if (global_settings.cuesheet)
2849 curr_cuesheet = (struct cuesheet*)buffer_alloc(sizeof(struct cuesheet));
2851 #ifndef SIMULATOR
2852 audiobuflen = audiobufend - audiobuf;
2853 queue_init(&mpeg_queue, true);
2854 #endif /* !SIMULATOR */
2855 create_thread(mpeg_thread, mpeg_stack,
2856 sizeof(mpeg_stack), 0, mpeg_thread_name
2857 IF_PRIO(, PRIORITY_SYSTEM)
2858 IF_COP(, CPU));
2860 memset(trackdata, 0, sizeof(trackdata));
2862 #if (CONFIG_CODEC == MAS3587F) && !defined(SIMULATOR)
2863 if (HW_MASK & PR_ACTIVE_HIGH)
2864 and_b(~0x08, &PADRH);
2865 else
2866 or_b(0x08, &PADRH);
2867 #endif /* CONFIG_CODEC == MAS3587F */
2869 #ifdef DEBUG
2870 #ifndef SIMULATOR
2871 dbg_timer_start();
2872 dbg_cnt2us(0);
2873 #endif /* !SIMULATOR */
2874 #endif /* DEBUG */
2877 #endif /* CONFIG_CODEC != SWCODEC */