1 // Some mp3 related code for Sega/Mega CD
2 // (c) Copyright 2007, Grazvydas "notaz" Ignotas
7 #include "../../Pico/sound/mix.h"
8 #include "code940/940shared.h"
9 #include "helix/pub/mp3dec.h"
11 static short mp3_out_buffer[2*1152];
12 static HMP3Decoder mp3dec = 0;
13 static int mp3_buffer_offs = 0;
15 extern _940_ctl_t *shared_ctl;
16 extern unsigned char *mp3_mem;
20 static int try_get_header(unsigned char *buff, MP3FrameInfo *fi)
22 int ret, offs1, offs = 0;
26 offs1 = MP3FindSyncWord(buff + offs, 2048 - offs);
27 if (offs1 < 0) return -2;
29 if (2048 - offs < 4) return -3;
31 // printf("trying header %08x\n", *(int *)(buff + offs));
33 ret = MP3GetNextFrameInfo(mp3dec, fi, buff + offs);
34 if (ret == 0 && fi->bitrate != 0) break;
41 int mp3_get_bitrate(FILE *f, int len)
43 unsigned char buff[2048];
47 memset(buff, 0, 2048);
49 if (!mp3dec) mp3dec = MP3InitDecoder();
51 fseek(f, 0, SEEK_SET);
52 ret = fread(buff, 1, 2048, f);
53 fseek(f, 0, SEEK_SET);
54 if (ret <= 0) return -1;
56 ret = try_get_header(buff, &fi);
57 if (ret != 0 || fi.bitrate == 0) {
58 // try to read somewhere around the middle
59 fseek(f, len>>1, SEEK_SET);
60 fread(buff, 1, 2048, f);
61 fseek(f, 0, SEEK_SET);
62 ret = try_get_header(buff, &fi);
64 if (ret != 0) return ret;
66 // printf("bitrate: %i\n", fi.bitrate / 1000);
68 return fi.bitrate / 1000;
72 static void mp3_decode(void)
74 // tried copying this to cached mem, no improvement noticed
75 int mp3_offs = shared_ctl->mp3_offs;
76 unsigned char *readPtr = mp3_mem + mp3_offs;
77 int bytesLeft = shared_ctl->mp3_len - mp3_offs;
78 int offset; // frame offset from readPtr
81 if (bytesLeft <= 0) return; // EOF, nothing to do
83 offset = MP3FindSyncWord(readPtr, bytesLeft);
85 shared_ctl->mp3_offs = shared_ctl->mp3_len;
91 err = MP3Decode(mp3dec, &readPtr, &bytesLeft, mp3_out_buffer, 0);
93 if (err == ERR_MP3_INDATA_UNDERFLOW) {
94 shared_ctl->mp3_offs = shared_ctl->mp3_len; // EOF
96 } else if (err <= -6 && err >= -12) {
97 // ERR_MP3_INVALID_FRAMEHEADER, ERR_MP3_INVALID_*
98 // just try to skip the offending frame..
101 shared_ctl->mp3_errors++;
102 shared_ctl->mp3_lasterr = err;
104 shared_ctl->mp3_offs = readPtr - mp3_mem;
108 void mp3_update_local(int *buffer, int length, int stereo)
110 int length_mp3, shr = 0;
111 void (*mix_samples)(int *dest_buf, short *mp3_buf, int count) = mix_16h_to_32;
114 if (PsndRate == 22050) { mix_samples = mix_16h_to_32_s1; length_mp3 <<= 1; shr = 1; }
115 else if (PsndRate == 11025) { mix_samples = mix_16h_to_32_s2; length_mp3 <<= 2; shr = 2; }
117 if (1152 - mp3_buffer_offs >= length_mp3) {
118 mix_samples(buffer, mp3_out_buffer + mp3_buffer_offs*2, length<<1);
120 mp3_buffer_offs += length_mp3;
122 int left = 1152 - mp3_buffer_offs;
124 mix_samples(buffer, mp3_out_buffer + mp3_buffer_offs*2, (left>>shr)<<1);
126 mp3_buffer_offs = length_mp3 - left;
127 mix_samples(buffer + ((left>>shr)<<1), mp3_out_buffer, (mp3_buffer_offs>>shr)<<1);
132 void mp3_start_local(void)