2 * Some mp3 related code for Sega/Mega CD.
3 * Uses the Helix Fixed-point MP3 decoder
6 * This work is licensed under the terms of MAME license.
7 * See COPYING file in the top-level directory.
14 #include <pico/pico_int.h>
15 /*#include "helix/pub/mp3dec.h"*/
19 typedef void *HMP3Decoder;
20 #define ERR_MP3_INDATA_UNDERFLOW -1
21 #define ERR_MP3_MAINDATA_UNDERFLOW -2
25 static unsigned char mp3_input_buffer[2 * 1024];
28 #define mp3dec_decode _mp3dec_decode
29 #define mp3dec_start _mp3dec_start
32 static void *libhelix;
33 HMP3Decoder (*p_MP3InitDecoder)(void);
34 void (*p_MP3FreeDecoder)(HMP3Decoder);
35 int (*p_MP3Decode)(HMP3Decoder, unsigned char **, int *, short *, int);
37 int mp3dec_decode(FILE *f, int *file_pos, int file_len)
39 unsigned char *readPtr;
41 int offset; // mp3 frame offset from readPtr
48 if (*file_pos >= file_len)
49 return 1; /* EOF, nothing to do */
51 fseek(f, *file_pos, SEEK_SET);
52 bytesLeft = fread(mp3_input_buffer, 1, sizeof(mp3_input_buffer), f);
54 offset = mp3_find_sync_word(mp3_input_buffer, bytesLeft);
56 lprintf("find_sync_word (%i/%i) err %i\n",
57 *file_pos, file_len, offset);
61 readPtr = mp3_input_buffer + offset;
65 err = p_MP3Decode(mp3dec, &readPtr, &bytesLeft, cdda_out_buffer, 0);
67 if (err == ERR_MP3_MAINDATA_UNDERFLOW && !had_err) {
68 // just need another frame
69 *file_pos += readPtr - mp3_input_buffer;
72 if (err == ERR_MP3_INDATA_UNDERFLOW && !had_err) {
74 // something's really wrong here, frame had to fit
80 if (-12 <= err && err <= -6) {
81 // ERR_MP3_INVALID_FRAMEHEADER, ERR_MP3_INVALID_*
82 // just try to skip the offending frame..
83 *file_pos += offset + 1;
86 lprintf("MP3Decode err (%i/%i) %i\n",
87 *file_pos, file_len, err);
91 *file_pos += readPtr - mp3_input_buffer;
93 while (err && --retry > 0);
98 int mp3dec_start(FILE *f, int fpos_start)
100 if (libhelix == NULL) {
101 libhelix = dlopen("./libhelix.so", RTLD_NOW);
102 if (libhelix == NULL) {
103 lprintf("mp3dec: load libhelix.so: %s\n", dlerror());
107 p_MP3InitDecoder = dlsym(libhelix, "MP3InitDecoder");
108 p_MP3FreeDecoder = dlsym(libhelix, "MP3FreeDecoder");
109 p_MP3Decode = dlsym(libhelix, "MP3Decode");
111 if (p_MP3InitDecoder == NULL || p_MP3FreeDecoder == NULL
112 || p_MP3Decode == NULL)
114 lprintf("mp3dec: missing symbol(s) in libhelix.so\n");
121 // must re-init decoder for new track
123 p_MP3FreeDecoder(mp3dec);
124 mp3dec = p_MP3InitDecoder();
126 return (mp3dec == 0) ? -1 : 0;