music_mad.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396
  1. /*
  2. SDL_mixer: An audio mixer library based on the SDL library
  3. Copyright (C) 1997-2004 Sam Lantinga
  4. This library is free software; you can redistribute it and/or
  5. modify it under the terms of the GNU Library General Public
  6. License as published by the Free Software Foundation; either
  7. version 2 of the License, or (at your option) any later version.
  8. This library is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  11. Library General Public License for more details.
  12. You should have received a copy of the GNU Library General Public
  13. License along with this library; if not, write to the Free
  14. Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  15. Sam Lantinga
  16. slouken@libsdl.org
  17. */
  18. #include <stdio.h>
  19. #include <string.h>
  20. #include <stdlib.h>
  21. #include "music_mad.h"
  22. #include "../resampler.h" /* SDLPAL */
  23. #ifndef SDL_AUDIO_BITSIZE
  24. # define SDL_AUDIO_BITSIZE(x) (x & 0xFF)
  25. #endif
  26. mad_data *
  27. mad_openFile(const char *filename, SDL_AudioSpec *mixer, int resampler_quality) {
  28. SDL_RWops *rw;
  29. rw = SDL_RWFromFile(filename, "rb");
  30. if (rw == NULL) {
  31. return NULL;
  32. }
  33. return mad_openFileRW(rw, mixer, resampler_quality);
  34. }
  35. mad_data *
  36. mad_openFileRW(SDL_RWops *rw, SDL_AudioSpec *mixer, int resampler_quality) {
  37. mad_data *mp3_mad;
  38. mp3_mad = (mad_data *)malloc(sizeof(mad_data));
  39. mp3_mad->rw = rw;
  40. mad_stream_init(&mp3_mad->stream);
  41. mad_frame_init(&mp3_mad->frame);
  42. mad_synth_init(&mp3_mad->synth);
  43. mp3_mad->frames_read = 0;
  44. mad_timer_reset(&mp3_mad->next_frame_start);
  45. mp3_mad->volume = 128;
  46. mp3_mad->status = 0;
  47. mp3_mad->output_begin = 0;
  48. mp3_mad->output_end = 0;
  49. mp3_mad->mixer = *mixer;
  50. mp3_mad->upsample = 0; /* SDLPAL */
  51. mp3_mad->resampler_quality = resampler_quality; /* SDLPAL */
  52. memset(mp3_mad->resampler, 0, sizeof(mp3_mad->resampler)); /* SDLPAL */
  53. return mp3_mad;
  54. }
  55. void
  56. mad_closeFile(mad_data *mp3_mad) {
  57. SDL_FreeRW(mp3_mad->rw);
  58. mad_stream_finish(&mp3_mad->stream);
  59. mad_frame_finish(&mp3_mad->frame);
  60. mad_synth_finish(&mp3_mad->synth);
  61. free(mp3_mad);
  62. }
  63. /* Starts the playback. */
  64. void
  65. mad_start(mad_data *mp3_mad) {
  66. mp3_mad->status |= MS_playing;
  67. }
  68. /* Stops the playback. */
  69. void
  70. mad_stop(mad_data *mp3_mad) {
  71. mp3_mad->status &= ~MS_playing;
  72. }
  73. /* Returns true if the playing is engaged, false otherwise. */
  74. int
  75. mad_isPlaying(mad_data *mp3_mad) {
  76. return ((mp3_mad->status & MS_playing) != 0);
  77. }
  78. /* Reads the next frame from the file. Returns true on success or
  79. false on failure. */
  80. static int
  81. read_next_frame(mad_data *mp3_mad) {
  82. if (mp3_mad->stream.buffer == NULL ||
  83. mp3_mad->stream.error == MAD_ERROR_BUFLEN) {
  84. size_t read_size;
  85. size_t remaining;
  86. unsigned char *read_start;
  87. /* There might be some bytes in the buffer left over from last
  88. time. If so, move them down and read more bytes following
  89. them. */
  90. if (mp3_mad->stream.next_frame != NULL) {
  91. remaining = mp3_mad->stream.bufend - mp3_mad->stream.next_frame;
  92. memmove(mp3_mad->input_buffer, mp3_mad->stream.next_frame, remaining);
  93. read_start = mp3_mad->input_buffer + remaining;
  94. read_size = MAD_INPUT_BUFFER_SIZE - remaining;
  95. } else {
  96. read_size = MAD_INPUT_BUFFER_SIZE;
  97. read_start = mp3_mad->input_buffer;
  98. remaining = 0;
  99. }
  100. /* Now read additional bytes from the input file. */
  101. read_size = SDL_RWread(mp3_mad->rw, read_start, 1, read_size);
  102. if (read_size <= 0) {
  103. if ((mp3_mad->status & (MS_input_eof | MS_input_error)) == 0) {
  104. if (read_size == 0) {
  105. mp3_mad->status |= MS_input_eof;
  106. } else {
  107. mp3_mad->status |= MS_input_error;
  108. }
  109. /* At the end of the file, we must stuff MAD_BUFFER_GUARD
  110. number of 0 bytes. */
  111. memset(read_start + read_size, 0, MAD_BUFFER_GUARD);
  112. read_size += MAD_BUFFER_GUARD;
  113. }
  114. }
  115. /* Now feed those bytes into the libmad stream. */
  116. mad_stream_buffer(&mp3_mad->stream, mp3_mad->input_buffer,
  117. read_size + remaining);
  118. mp3_mad->stream.error = MAD_ERROR_NONE;
  119. }
  120. /* Now ask libmad to extract a frame from the data we just put in
  121. its buffer. */
  122. if (mad_frame_decode(&mp3_mad->frame, &mp3_mad->stream)) {
  123. if (MAD_RECOVERABLE(mp3_mad->stream.error)) {
  124. return 0;
  125. } else if (mp3_mad->stream.error == MAD_ERROR_BUFLEN) {
  126. return 0;
  127. } else {
  128. mp3_mad->status |= MS_decode_error;
  129. return 0;
  130. }
  131. }
  132. mp3_mad->frames_read++;
  133. mad_timer_add(&mp3_mad->next_frame_start, mp3_mad->frame.header.duration);
  134. return 1;
  135. }
  136. /* Scale a MAD sample to 16 bits for output. */
  137. static signed int
  138. scale(mad_fixed_t sample) {
  139. /* round */
  140. sample += (1L << (MAD_F_FRACBITS - 16));
  141. /* clip */
  142. if (sample >= MAD_F_ONE)
  143. sample = MAD_F_ONE - 1;
  144. else if (sample < -MAD_F_ONE)
  145. sample = -MAD_F_ONE;
  146. /* quantize */
  147. return sample >> (MAD_F_FRACBITS + 1 - 16);
  148. }
  149. /* Once the frame has been read, copies its samples into the output
  150. buffer. */
  151. static void
  152. decode_frame(mad_data *mp3_mad) {
  153. struct mad_pcm *pcm;
  154. unsigned int nchannels, nsamples;
  155. mad_fixed_t const *left_ch, *right_ch;
  156. unsigned char *out;
  157. mad_synth_frame(&mp3_mad->synth, &mp3_mad->frame);
  158. pcm = &mp3_mad->synth.pcm;
  159. out = mp3_mad->output_buffer + mp3_mad->output_end;
  160. if ((mp3_mad->status & MS_cvt_decoded) == 0) {
  161. int hi, lo; /* SDLPAL */
  162. mp3_mad->status |= MS_cvt_decoded;
  163. /* The first frame determines some key properties of the stream.
  164. In particular, it tells us enough to set up the convert
  165. structure now. */
  166. /* ------------------------------- SDLPAL start ------------------------------- */
  167. hi = (int)mp3_mad->frame.header.samplerate > mp3_mad->mixer.freq ? mp3_mad->frame.header.samplerate : mp3_mad->mixer.freq;
  168. lo = (int)mp3_mad->frame.header.samplerate < mp3_mad->mixer.freq ? mp3_mad->frame.header.samplerate : mp3_mad->mixer.freq;
  169. if (hi != lo) {
  170. /* Need sample rate conversion, resampler should be used. Try to create resamplers. */
  171. if (mp3_mad->resampler[0] = resampler_create()) {
  172. if (mp3_mad->mixer.channels == 2) {
  173. if ((mp3_mad->resampler[1] = resampler_create())) {
  174. resampler_set_quality(mp3_mad->resampler[1], (hi % lo == 0) ? RESAMPLER_QUALITY_MIN : mp3_mad->resampler_quality);
  175. resampler_set_rate(mp3_mad->resampler[1], (double)mp3_mad->frame.header.samplerate / (double)mp3_mad->mixer.freq);
  176. }
  177. else {
  178. resampler_delete(mp3_mad->resampler[0]);
  179. mp3_mad->resampler[0] = NULL;
  180. }
  181. }
  182. }
  183. if (mp3_mad->resampler[0]) {
  184. resampler_set_quality(mp3_mad->resampler[0], mp3_mad->resampler_quality);
  185. resampler_set_rate(mp3_mad->resampler[0], (double)mp3_mad->frame.header.samplerate / (double)mp3_mad->mixer.freq);
  186. /* Resampler successfully created, cheat SDL for not converting sample rate */
  187. mp3_mad->upsample = mp3_mad->mixer.freq > (int)mp3_mad->frame.header.samplerate;
  188. mp3_mad->mixer.freq = mp3_mad->frame.header.samplerate;
  189. }
  190. }
  191. /* ------------------------------- SDLPAL end ------------------------------- */
  192. SDL_BuildAudioCVT(&mp3_mad->cvt, AUDIO_S16, (Uint8)pcm->channels, mp3_mad->frame.header.samplerate, mp3_mad->mixer.format, mp3_mad->mixer.channels, mp3_mad->mixer.freq);
  193. }
  194. /* pcm->samplerate contains the sampling frequency */
  195. nchannels = pcm->channels;
  196. nsamples = pcm->length;
  197. left_ch = pcm->samples[0];
  198. right_ch = pcm->samples[1];
  199. while (nsamples--) {
  200. signed int sample;
  201. /* output sample(s) in 16-bit signed little-endian PCM */
  202. sample = scale(*left_ch++);
  203. *out++ = ((sample >> 0) & 0xff);
  204. *out++ = ((sample >> 8) & 0xff);
  205. if (nchannels == 2) {
  206. sample = scale(*right_ch++);
  207. *out++ = ((sample >> 0) & 0xff);
  208. *out++ = ((sample >> 8) & 0xff);
  209. }
  210. }
  211. mp3_mad->output_end = out - mp3_mad->output_buffer;
  212. /*assert(mp3_mad->output_end <= MAD_OUTPUT_BUFFER_SIZE);*/
  213. }
  214. void
  215. mad_getSamples(mad_data *mp3_mad, Uint8 *stream, int len) {
  216. int bytes_remaining;
  217. int num_bytes;
  218. Uint8 *out;
  219. if ((mp3_mad->status & MS_playing) == 0) {
  220. /* We're not supposed to be playing, so send silence instead. */
  221. memset(stream, 0, len);
  222. return;
  223. }
  224. out = stream;
  225. bytes_remaining = len;
  226. while (bytes_remaining > 0) {
  227. if (mp3_mad->output_end == mp3_mad->output_begin) {
  228. /* We need to get a new frame. */
  229. mp3_mad->output_begin = 0;
  230. mp3_mad->output_end = 0;
  231. if (!read_next_frame(mp3_mad)) {
  232. if ((mp3_mad->status & MS_error_flags) != 0) {
  233. /* Couldn't read a frame; either an error condition or
  234. end-of-file. Stop. */
  235. memset(out, 0, bytes_remaining);
  236. mp3_mad->status &= ~MS_playing;
  237. return;
  238. }
  239. } else {
  240. decode_frame(mp3_mad);
  241. /* Now convert the frame data to the appropriate format for
  242. output. */
  243. mp3_mad->cvt.buf = mp3_mad->output_buffer;
  244. mp3_mad->cvt.len = mp3_mad->output_end;
  245. mp3_mad->output_end = (int)(mp3_mad->output_end * mp3_mad->cvt.len_ratio);
  246. /*assert(mp3_mad->output_end <= MAD_OUTPUT_BUFFER_SIZE);*/
  247. SDL_ConvertAudio(&mp3_mad->cvt);
  248. /* ------------------------------- SDLPAL start ------------------------------- */
  249. if (mp3_mad->resampler[0]) {
  250. int dst_samples = 0, pos = 0, i;
  251. if (mp3_mad->upsample) {
  252. /* Upsample, should move memory blocks to avoid overwrite. MP3's lowest samplerate
  253. is 32KHz, while SDLPAL support up to 48KHz, so maximum upsample rate is 1.5.
  254. As one frame has 1152 samples, the maximum bytes used will be 6912 bytes. So
  255. it is safe by first moving memory blocks to the end of the buffer */
  256. pos = sizeof(mp3_mad->output_buffer) - mp3_mad->output_end;
  257. memmove(mp3_mad->output_buffer + pos, mp3_mad->output_buffer, mp3_mad->output_end);
  258. }
  259. for (i = 0; i < mp3_mad->mixer.channels; i++) {
  260. short *src = (short *)(mp3_mad->output_buffer + pos) + i;
  261. short *dst = (short *)mp3_mad->output_buffer + i;
  262. int src_samples = 1152; /* Defined by MP3 specification */
  263. while(src_samples > 0) {
  264. int to_write = resampler_get_free_count(mp3_mad->resampler[i]), j;
  265. for (j = 0; j < to_write; j++) {
  266. resampler_write_sample(mp3_mad->resampler[i], SDL_SwapLE16(*src));
  267. src += mp3_mad->mixer.channels;
  268. }
  269. src_samples -= to_write;
  270. while (resampler_get_sample_count(mp3_mad->resampler[i]) > 0) {
  271. *dst = SDL_SwapLE16(resampler_get_and_remove_sample(mp3_mad->resampler[i]));
  272. dst += mp3_mad->mixer.channels; dst_samples++;
  273. }
  274. }
  275. }
  276. mp3_mad->output_end = dst_samples * (SDL_AUDIO_BITSIZE(mp3_mad->mixer.format) >> 3);
  277. }
  278. /* ------------------------------- SDLPAL end ------------------------------- */
  279. }
  280. }
  281. num_bytes = mp3_mad->output_end - mp3_mad->output_begin;
  282. if (bytes_remaining < num_bytes) {
  283. num_bytes = bytes_remaining;
  284. }
  285. if (mp3_mad->volume == 128) {
  286. memcpy(out, mp3_mad->output_buffer + mp3_mad->output_begin, num_bytes);
  287. } else {
  288. SDL_MixAudio(out, mp3_mad->output_buffer + mp3_mad->output_begin,
  289. num_bytes, mp3_mad->volume);
  290. }
  291. out += num_bytes;
  292. mp3_mad->output_begin += num_bytes;
  293. bytes_remaining -= num_bytes;
  294. }
  295. }
  296. void
  297. mad_seek(mad_data *mp3_mad, double position) {
  298. mad_timer_t target;
  299. int int_part;
  300. int_part = (int)position;
  301. mad_timer_set(&target, int_part,
  302. (int)((position - int_part) * 1000000), 1000000);
  303. if (mad_timer_compare(mp3_mad->next_frame_start, target) > 0) {
  304. /* In order to seek backwards in a VBR file, we have to rewind and
  305. start again from the beginning. This isn't necessary if the
  306. file happens to be CBR, of course; in that case we could seek
  307. directly to the frame we want. But I leave that little
  308. optimization for the future developer who discovers she really
  309. needs it. */
  310. mp3_mad->frames_read = 0;
  311. mad_timer_reset(&mp3_mad->next_frame_start);
  312. mp3_mad->status &= ~MS_error_flags;
  313. mp3_mad->output_begin = 0;
  314. mp3_mad->output_end = 0;
  315. SDL_RWseek(mp3_mad->rw, 0, SEEK_SET);
  316. }
  317. /* Now we have to skip frames until we come to the right one.
  318. Again, only truly necessary if the file is VBR. */
  319. while (mad_timer_compare(mp3_mad->next_frame_start, target) < 0) {
  320. if (!read_next_frame(mp3_mad)) {
  321. if ((mp3_mad->status & MS_error_flags) != 0) {
  322. /* Couldn't read a frame; either an error condition or
  323. end-of-file. Stop. */
  324. mp3_mad->status &= ~MS_playing;
  325. return;
  326. }
  327. }
  328. }
  329. /* Here we are, at the beginning of the frame that contains the
  330. target time. Ehh, I say that's close enough. If we wanted to,
  331. we could get more precise by decoding the frame now and counting
  332. the appropriate number of samples out of it. */
  333. }
  334. void
  335. mad_setVolume(mad_data *mp3_mad, int volume) {
  336. mp3_mad->volume = volume;
  337. }