Fix whitespace inconsistencies.
[herrie-working.git] / herrie / src / audio_format_mp3.c
blob330dc0be6f618a37108ebfcdae2e89288d0208cf
1 /*
2 * Copyright (c) 2006-2011 Ed Schouten <ed@80386.nl>
3 * All rights reserved.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
14 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24 * SUCH DAMAGE.
26 /**
27 * @file audio_format_mp3.c
28 * @brief MP3 decompression routines.
31 #include "stdinc.h"
33 #include <mad.h>
34 #include <id3tag.h>
36 #include "audio_file.h"
37 #include "audio_format.h"
38 #include "audio_output.h"
40 /**
41 * @brief Private MP3 data stored in the audio file structure.
43 struct mp3_drv_data {
44 /**
45 * @brief Stream data.
47 struct mad_stream mstream;
48 /**
49 * @brief Frame data.
51 struct mad_frame mframe;
52 /**
53 * @brief Frame header.
55 struct mad_header mheader;
56 /**
57 * @brief Synth data.
59 struct mad_synth msynth;
60 /**
61 * @brief Progress timer.
63 mad_timer_t mtimer;
64 /**
65 * @brief Sample offset.
67 int cursample;
68 /**
69 * @brief Length of the file.
71 off_t flen;
73 /**
74 * @brief Read buffer.
76 unsigned char buf_input[65536];
80 * File and tag matching
83 /**
84 * @brief Test if an opened file is an MP3 file.
86 static int
87 mp3_match(FILE *fp, const char *ext)
89 unsigned char buf[3];
90 int ret = 0;
92 /* Also match (broken) *.mp3 files */
93 if (ext != NULL && strcmp(ext, "mp3") == 0)
94 goto done;
96 if (fread(buf, sizeof buf, 1, fp) != 1) {
97 ret = -1;
98 goto done;
101 /* Match 1: first twelve bits high */
102 if (buf[0] == 0xff && (buf[1] & 0xf0) == 0xf0)
103 goto done;
105 /* Match 2: ID3 header */
106 if (buf[0] == 'I' && buf[1] == 'D' && buf[2] == '3')
107 goto done;
109 ret = -1;
111 done: rewind(fp);
112 return (ret);
116 * @brief Read the ID3 tag from an MP3 file.
118 static void
119 mp3_readtags(struct audio_file *fd)
121 int tmpfd;
122 unsigned int i;
123 off_t orig_off;
124 struct id3_file *id3f;
125 struct id3_tag *tag;
126 id3_ucs4_t const *str;
127 char **dst = NULL;
129 /* Duplicate the current filehandle */
130 tmpfd = dup(fileno(fd->fp));
131 if (tmpfd < 0)
132 return;
134 /* Backing up the original offset */
135 orig_off = lseek(tmpfd, 0, SEEK_CUR);
137 id3f = id3_file_fdopen(tmpfd, ID3_FILE_MODE_READONLY);
138 if (id3f == NULL)
139 goto bad;
141 /* Here we go */
142 tag = id3_file_tag(id3f);
143 if (tag == NULL)
144 goto done;
146 for (i = 0; i < tag->nframes; i++) {
147 if (strncmp("TPE1", tag->frames[i]->id, 4) == 0) {
148 dst = &fd->artist;
149 } else if (strncmp("TIT2", tag->frames[i]->id, 4) == 0) {
150 dst = &fd->title;
151 #ifdef BUILD_SCROBBLER
152 } else if (strncmp("TALB", tag->frames[i]->id, 4) == 0) {
153 dst = &fd->album;
154 #endif /* BUILD_SCROBBLER */
155 } else {
156 continue;
158 if (id3_field_getnstrings(&tag->frames[i]->fields[1]) != 0) {
159 str = id3_field_getstrings(&tag->frames[i]->fields[1], 0);
160 if (str != NULL)
161 *dst = (char*)id3_ucs4_utf8duplicate(str);
165 done:
166 id3_file_close(id3f);
167 bad:
168 lseek(tmpfd, orig_off, SEEK_SET);
169 close(tmpfd);
173 * MP3 frame decoding routines
177 * @brief Refill the databuffer when it's drained, copying the last
178 * partial frame to the beginning.
180 static size_t
181 mp3_fill_buffer(struct audio_file *fd)
183 struct mp3_drv_data *data = fd->drv_data;
184 size_t offset, filledlen, readlen;
186 if (data->mstream.next_frame == NULL) {
187 /* Place contents at the beginning */
188 offset = 0;
189 } else {
191 * We still need to save the fragmented frame. Copy it
192 * to the beginning and load as much as possible.
194 offset = data->mstream.bufend - data->mstream.next_frame;
195 memmove(data->buf_input, data->mstream.next_frame, offset);
198 readlen = sizeof data->buf_input - offset;
200 filledlen = fread(data->buf_input + offset, 1, readlen, fd->fp);
202 if (filledlen <= 0)
203 return (0);
205 if (filledlen < readlen) {
207 * Place some null bytes at the end
208 * because we may overrun it
210 memset(data->buf_input + offset + filledlen, 0x00000000,
211 MAD_BUFFER_GUARD);
212 filledlen += MAD_BUFFER_GUARD;
215 /* Return the length of the entire buffer */
216 return (offset + filledlen);
220 * @brief Try to decode a frame, refilling the buffer if needed.
222 static int
223 mp3_read_frame(struct audio_file *fd)
225 struct mp3_drv_data *data = fd->drv_data;
226 size_t buflen;
228 /* Get the next frame */
229 for (;;) {
230 /* We've run out of data. Read from file */
231 if ((data->mstream.buffer == NULL) ||
232 (data->mstream.error == MAD_ERROR_BUFLEN)) {
233 if ((buflen = mp3_fill_buffer(fd)) == 0)
234 /* Read error */
235 return (1);
237 /* Load it back in */
238 mad_stream_buffer(&data->mstream, data->buf_input,
239 buflen);
240 data->mstream.error = MAD_ERROR_NONE;
243 if (mad_header_decode(&data->mheader, &data->mstream) == 0) {
244 /* Update the audio timer */
245 mad_timer_add(&data->mtimer,
246 data->mframe.header.duration);
247 fd->time_cur = data->mtimer.seconds;
248 data->mframe.header = data->mheader;
249 return (0);
252 if (!MAD_RECOVERABLE(data->mstream.error) &&
253 (data->mstream.error != MAD_ERROR_BUFLEN)) {
254 /* Unrecoverable error - bail out */
255 return (1);
262 * @brief Convert a fixed point sample to a short.
264 static inline int16_t
265 mp3_fixed_to_short(mad_fixed_t fixed)
267 if (fixed >= MAD_F_ONE)
268 return (SHRT_MAX);
269 else if (fixed <= -MAD_F_ONE)
270 return (-SHRT_MAX);
272 return (fixed >> (MAD_F_FRACBITS - 15));
276 * @brief Rewind the current audio file handle to the beginning.
278 static void
279 mp3_rewind(struct audio_file *fd)
281 struct mp3_drv_data *data = fd->drv_data;
283 rewind(fd->fp);
285 data->cursample = 0;
286 fd->time_cur = 0;
288 mad_stream_init(&data->mstream);
289 mad_frame_init(&data->mframe);
290 mad_header_init(&data->mheader);
291 mad_synth_init(&data->msynth);
292 mad_timer_reset(&data->mtimer);
296 * @brief Calculate the length of the current audio file.
298 static void
299 mp3_calc_length(struct audio_file *fd)
301 struct mp3_drv_data *data = fd->drv_data;
302 off_t curpos;
304 /* Go to the end of the file */
305 do {
306 if (mp3_read_frame(fd) != 0) {
307 /* Short track */
308 fd->time_len = data->mtimer.seconds;
309 data->flen = ftello(fd->fp);
310 goto done;
312 } while (data->mtimer.seconds < 100);
314 /* Extrapolate the time. Not really accurate, but good enough */
315 curpos = ftello(fd->fp);
316 fseek(fd->fp, 0, SEEK_END);
317 data->flen = ftello(fd->fp);
319 fd->time_len = ((double)data->flen / curpos) *
320 data->mtimer.seconds;
321 done:
322 /* Go back to the start */
323 mp3_rewind(fd);
327 * Public API
331 mp3_open(struct audio_file *fd, const char *ext)
333 struct mp3_drv_data *data;
335 /* Don't match other files */
336 if (!fd->stream) {
337 if (mp3_match(fd->fp, ext) != 0)
338 return (-1);
339 mp3_readtags(fd);
342 data = g_slice_new(struct mp3_drv_data);
343 fd->drv_data = (void *)data;
345 mp3_rewind(fd);
346 if (!fd->stream)
347 mp3_calc_length(fd);
349 return (0);
352 void
353 mp3_close(struct audio_file *fd)
355 struct mp3_drv_data *data = fd->drv_data;
357 mad_frame_finish(&data->mframe);
358 mad_stream_finish(&data->mstream);
359 mad_synth_finish(&data->msynth);
361 g_slice_free(struct mp3_drv_data, data);
364 size_t
365 mp3_read(struct audio_file *fd, int16_t *buf, size_t len)
367 struct mp3_drv_data *data = fd->drv_data;
368 size_t written = 0;
369 int i;
371 do {
372 /* Get a new frame when we haven't go one */
373 if (data->cursample == 0) {
374 if (mp3_read_frame(fd) != 0)
375 goto done;
376 if (mad_frame_decode(&data->mframe, &data->mstream) == -1)
377 continue;
379 /* We can now set the sample rate */
380 fd->srate = data->mframe.header.samplerate;
381 fd->channels = MAD_NCHANNELS(&data->mframe.header);
383 mad_synth_frame(&data->msynth, &data->mframe);
386 while ((data->cursample < data->msynth.pcm.length) &&
387 (written < len)) {
388 /* Write out all channels */
389 for (i = 0; i < MAD_NCHANNELS(&data->mframe.header); i++) {
390 buf[written++] = mp3_fixed_to_short(
391 data->msynth.pcm.samples[i][data->cursample]);
394 data->cursample++;
397 /* Move on to the next frame */
398 if (data->cursample == data->msynth.pcm.length)
399 data->cursample = 0;
401 } while (written < len);
403 done:
404 return (written);
407 void
408 mp3_seek(struct audio_file *fd, int len, int rel)
410 struct mp3_drv_data *data = fd->drv_data;
411 off_t newpos;
413 if (rel) {
414 /* Relative seek */
415 len += fd->time_cur;
418 /* Calculate the new relative position */
419 len = CLAMP(len, 0, (int)fd->time_len);
420 newpos = ((double)len / fd->time_len) * data->flen;
422 /* Seek to the new position */
423 mp3_rewind(fd);
424 fseek(fd->fp, newpos, SEEK_SET);
425 data->mtimer.seconds = len;
426 data->mtimer.fraction = 0;
427 fd->time_cur = data->mtimer.seconds;