Initial revision 6759
[qball-mpd.git] / src / inputPlugins / .svn / text-base / mp3_plugin.c.svn-base
blob3c958705a60684d5360e28386a58dddf8a8dbed5
1 /* the Music Player Daemon (MPD)
2  * Copyright (C) 2003-2007 by Warren Dukes (warren.dukes@gmail.com)
3  * This project's homepage is: http://www.musicpd.org
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 2 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software
16  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
17  */
19 #include "../inputPlugin.h"
21 #ifdef HAVE_MAD
23 #include "../pcm_utils.h"
24 #include <mad.h>
26 #ifdef HAVE_ID3TAG
27 #include <id3tag.h>
28 #endif
30 #include "../log.h"
31 #include "../utils.h"
32 #include "../replayGain.h"
33 #include "../tag.h"
34 #include "../conf.h"
36 #include <stdio.h>
37 #include <stdlib.h>
38 #include <string.h>
39 #include <sys/types.h>
40 #include <sys/stat.h>
41 #include <unistd.h>
42 #include <errno.h>
44 #define FRAMES_CUSHION          2000
46 #define READ_BUFFER_SIZE        40960
48 #define DECODE_SKIP             -3
49 #define DECODE_BREAK            -2
50 #define DECODE_CONT             -1
51 #define DECODE_OK               0
53 #define MUTEFRAME_SKIP          1
54 #define MUTEFRAME_SEEK          2
56 /* the number of samples of silence the decoder inserts at start */
57 #define DECODERDELAY 529
59 #define DEFAULT_GAPLESS_MP3_PLAYBACK 1
61 static int gaplessPlaybackEnabled;
63 /* this is stolen from mpg321! */
64 struct audio_dither {
65         mad_fixed_t error[3];
66         mad_fixed_t random;
69 static unsigned long prng(unsigned long state)
71         return (state * 0x0019660dL + 0x3c6ef35fL) & 0xffffffffL;
74 static signed long audio_linear_dither(unsigned int bits, mad_fixed_t sample,
75                                        struct audio_dither *dither)
77         unsigned int scalebits;
78         mad_fixed_t output, mask, random;
80         enum {
81                 MIN = -MAD_F_ONE,
82                 MAX = MAD_F_ONE - 1
83         };
85         sample += dither->error[0] - dither->error[1] + dither->error[2];
87         dither->error[2] = dither->error[1];
88         dither->error[1] = dither->error[0] / 2;
90         output = sample + (1L << (MAD_F_FRACBITS + 1 - bits - 1));
92         scalebits = MAD_F_FRACBITS + 1 - bits;
93         mask = (1L << scalebits) - 1;
95         random = prng(dither->random);
96         output += (random & mask) - (dither->random & mask);
98         dither->random = random;
100         if (output > MAX) {
101                 output = MAX;
103                 if (sample > MAX)
104                         sample = MAX;
105         } else if (output < MIN) {
106                 output = MIN;
108                 if (sample < MIN)
109                         sample = MIN;
110         }
112         output &= ~mask;
114         dither->error[0] = sample - output;
116         return output >> scalebits;
119 /* end of stolen stuff from mpg321 */
121 static int mp3_plugin_init(void)
123         gaplessPlaybackEnabled = getBoolConfigParam(CONF_GAPLESS_MP3_PLAYBACK);
124         if (gaplessPlaybackEnabled == -1)
125                 gaplessPlaybackEnabled = DEFAULT_GAPLESS_MP3_PLAYBACK;
126         else if (gaplessPlaybackEnabled < 0)
127                 exit(EXIT_FAILURE);
128         return 1;
131 /* decoder stuff is based on madlld */
133 #define MP3_DATA_OUTPUT_BUFFER_SIZE 4096
135 typedef struct _mp3DecodeData {
136         struct mad_stream stream;
137         struct mad_frame frame;
138         struct mad_synth synth;
139         mad_timer_t timer;
140         unsigned char readBuffer[READ_BUFFER_SIZE];
141         char outputBuffer[MP3_DATA_OUTPUT_BUFFER_SIZE];
142         char *outputPtr;
143         char *outputBufferEnd;
144         float totalTime;
145         float elapsedTime;
146         int muteFrame;
147         long *frameOffset;
148         mad_timer_t *times;
149         long highestFrame;
150         long maxFrames;
151         long currentFrame;
152         int dropFramesAtStart;
153         int dropFramesAtEnd;
154         int dropSamplesAtStart;
155         int dropSamplesAtEnd;
156         int foundXing;
157         int foundFirstFrame;
158         int decodedFirstFrame;
159         int flush;
160         unsigned long bitRate;
161         InputStream *inStream;
162         struct audio_dither dither;
163         enum mad_layer layer;
164 } mp3DecodeData;
166 static void initMp3DecodeData(mp3DecodeData * data, InputStream * inStream)
168         data->outputPtr = data->outputBuffer;
169         data->outputBufferEnd =
170             data->outputBuffer + MP3_DATA_OUTPUT_BUFFER_SIZE;
171         data->muteFrame = 0;
172         data->highestFrame = 0;
173         data->maxFrames = 0;
174         data->frameOffset = NULL;
175         data->times = NULL;
176         data->currentFrame = 0;
177         data->dropFramesAtStart = 0;
178         data->dropFramesAtEnd = 0;
179         data->dropSamplesAtStart = 0;
180         data->dropSamplesAtEnd = 0;
181         data->foundXing = 0;
182         data->foundFirstFrame = 0;
183         data->decodedFirstFrame = 0;
184         data->flush = 1;
185         data->inStream = inStream;
186         data->layer = 0;
187         memset(&(data->dither), 0, sizeof(struct audio_dither));
189         mad_stream_init(&data->stream);
190         mad_stream_options(&data->stream, MAD_OPTION_IGNORECRC);
191         mad_frame_init(&data->frame);
192         mad_synth_init(&data->synth);
193         mad_timer_reset(&data->timer);
196 static int seekMp3InputBuffer(mp3DecodeData * data, long offset)
198         if (seekInputStream(data->inStream, offset, SEEK_SET) < 0) {
199                 return -1;
200         }
202         mad_stream_buffer(&data->stream, data->readBuffer, 0);
203         (data->stream).error = 0;
205         return 0;
208 static int fillMp3InputBuffer(mp3DecodeData * data)
210         size_t readSize;
211         size_t remaining;
212         size_t readed;
213         unsigned char *readStart;
215         if ((data->stream).next_frame != NULL) {
216                 remaining = (data->stream).bufend - (data->stream).next_frame;
217                 memmove(data->readBuffer, (data->stream).next_frame, remaining);
218                 readStart = (data->readBuffer) + remaining;
219                 readSize = READ_BUFFER_SIZE - remaining;
220         } else {
221                 readSize = READ_BUFFER_SIZE;
222                 readStart = data->readBuffer, remaining = 0;
223         }
225         /* we've exhausted the read buffer, so give up!, these potential
226          * mp3 frames are way too big, and thus unlikely to be mp3 frames */
227         if (readSize == 0)
228                 return -1;
230         readed = readFromInputStream(data->inStream, readStart, (size_t) 1,
231                                      readSize);
232         if (readed <= 0 && inputStreamAtEOF(data->inStream))
233                 return -1;
234         /* sleep for a fraction of a second! */
235         else if (readed <= 0) {
236                 readed = 0;
237                 my_usleep(10000);
238         }
240         mad_stream_buffer(&data->stream, data->readBuffer, readed + remaining);
241         (data->stream).error = 0;
243         return 0;
246 #ifdef HAVE_ID3TAG
247 static ReplayGainInfo *parseId3ReplayGainInfo(struct id3_tag *tag)
249         int i;
250         char *key;
251         char *value;
252         struct id3_frame *frame;
253         int found = 0;
254         ReplayGainInfo *replayGainInfo;
256         replayGainInfo = newReplayGainInfo();
258         for (i = 0; (frame = id3_tag_findframe(tag, "TXXX", i)); i++) {
259                 if (frame->nfields < 3)
260                         continue;
262                 key = (char *)
263                     id3_ucs4_latin1duplicate(id3_field_getstring
264                                              (&frame->fields[1]));
265                 value = (char *)
266                     id3_ucs4_latin1duplicate(id3_field_getstring
267                                              (&frame->fields[2]));
269                 if (strcasecmp(key, "replaygain_track_gain") == 0) {
270                         replayGainInfo->trackGain = atof(value);
271                         found = 1;
272                 } else if (strcasecmp(key, "replaygain_album_gain") == 0) {
273                         replayGainInfo->albumGain = atof(value);
274                         found = 1;
275                 } else if (strcasecmp(key, "replaygain_track_peak") == 0) {
276                         replayGainInfo->trackPeak = atof(value);
277                         found = 1;
278                 } else if (strcasecmp(key, "replaygain_album_peak") == 0) {
279                         replayGainInfo->albumPeak = atof(value);
280                         found = 1;
281                 }
283                 free(key);
284                 free(value);
285         }
287         if (found)
288                 return replayGainInfo;
289         freeReplayGainInfo(replayGainInfo);
290         return NULL;
292 #endif
294 #ifdef HAVE_ID3TAG
295 static void mp3_parseId3Tag(mp3DecodeData * data, signed long tagsize,
296                             MpdTag ** mpdTag, ReplayGainInfo ** replayGainInfo)
298         struct id3_tag *id3Tag = NULL;
299         id3_length_t count;
300         id3_byte_t const *id3_data;
301         id3_byte_t *allocated = NULL;
302         MpdTag *tmpMpdTag;
303         ReplayGainInfo *tmpReplayGainInfo;
305         count = data->stream.bufend - data->stream.this_frame;
307         if (tagsize <= count) {
308                 id3_data = data->stream.this_frame;
309                 mad_stream_skip(&(data->stream), tagsize);
310         } else {
311                 allocated = xmalloc(tagsize);
312                 if (!allocated)
313                         goto fail;
315                 memcpy(allocated, data->stream.this_frame, count);
316                 mad_stream_skip(&(data->stream), count);
318                 while (count < tagsize) {
319                         int len;
321                         len = readFromInputStream(data->inStream,
322                                                   allocated + count, (size_t) 1,
323                                                   tagsize - count);
324                         if (len <= 0 && inputStreamAtEOF(data->inStream)) {
325                                 break;
326                         } else if (len <= 0)
327                                 my_usleep(10000);
328                         else
329                                 count += len;
330                 }
332                 if (count != tagsize) {
333                         DEBUG("mp3_decode: error parsing ID3 tag\n");
334                         goto fail;
335                 }
337                 id3_data = allocated;
338         }
340         id3Tag = id3_tag_parse(id3_data, tagsize);
341         if (!id3Tag)
342                 goto fail;
344         if (mpdTag) {
345                 tmpMpdTag = parseId3Tag(id3Tag);
346                 if (tmpMpdTag) {
347                         if (*mpdTag)
348                                 freeMpdTag(*mpdTag);
349                         *mpdTag = tmpMpdTag;
350                 }
351         }
353         if (replayGainInfo) {
354                 tmpReplayGainInfo = parseId3ReplayGainInfo(id3Tag);
355                 if (tmpReplayGainInfo) {
356                         if (*replayGainInfo)
357                                 freeReplayGainInfo(*replayGainInfo);
358                         *replayGainInfo = tmpReplayGainInfo;
359                 }
360         }
362         id3_tag_delete(id3Tag);
363 fail:
364         if (allocated)
365                 free(allocated);
367 #endif
369 static int decodeNextFrameHeader(mp3DecodeData * data, MpdTag ** tag,
370                                  ReplayGainInfo ** replayGainInfo)
372         enum mad_layer layer;
374         if ((data->stream).buffer == NULL
375             || (data->stream).error == MAD_ERROR_BUFLEN) {
376                 if (fillMp3InputBuffer(data) < 0) {
377                         return DECODE_BREAK;
378                 }
379         }
380         if (mad_header_decode(&data->frame.header, &data->stream)) {
381 #ifdef HAVE_ID3TAG
382                 if ((data->stream).error == MAD_ERROR_LOSTSYNC &&
383                     (data->stream).this_frame) {
384                         signed long tagsize = id3_tag_query((data->stream).
385                                                             this_frame,
386                                                             (data->stream).
387                                                             bufend -
388                                                             (data->stream).
389                                                             this_frame);
391                         if (tagsize > 0) {
392                                 if (tag && !(*tag)) {
393                                         mp3_parseId3Tag(data, tagsize, tag,
394                                                         replayGainInfo);
395                                 } else {
396                                         mad_stream_skip(&(data->stream),
397                                                         tagsize);
398                                 }
399                                 return DECODE_CONT;
400                         }
401                 }
402 #endif
403                 if (MAD_RECOVERABLE((data->stream).error)) {
404                         return DECODE_SKIP;
405                 } else {
406                         if ((data->stream).error == MAD_ERROR_BUFLEN)
407                                 return DECODE_CONT;
408                         else {
409                                 ERROR("unrecoverable frame level error "
410                                       "(%s).\n",
411                                       mad_stream_errorstr(&data->stream));
412                                 data->flush = 0;
413                                 return DECODE_BREAK;
414                         }
415                 }
416         }
418         layer = data->frame.header.layer;
419         if (!data->layer) {
420                 if (layer != MAD_LAYER_II && layer != MAD_LAYER_III) {
421                         /* Only layer 2 and 3 have been tested to work */
422                         return DECODE_SKIP;
423                 }
424                 data->layer = layer;
425         } else if (layer != data->layer) {
426                 /* Don't decode frames with a different layer than the first */
427                 return DECODE_SKIP;
428         }
430         return DECODE_OK;
433 static int decodeNextFrame(mp3DecodeData * data)
435         if ((data->stream).buffer == NULL
436             || (data->stream).error == MAD_ERROR_BUFLEN) {
437                 if (fillMp3InputBuffer(data) < 0) {
438                         return DECODE_BREAK;
439                 }
440         }
441         if (mad_frame_decode(&data->frame, &data->stream)) {
442 #ifdef HAVE_ID3TAG
443                 if ((data->stream).error == MAD_ERROR_LOSTSYNC) {
444                         signed long tagsize = id3_tag_query((data->stream).
445                                                             this_frame,
446                                                             (data->stream).
447                                                             bufend -
448                                                             (data->stream).
449                                                             this_frame);
450                         if (tagsize > 0) {
451                                 mad_stream_skip(&(data->stream), tagsize);
452                                 return DECODE_CONT;
453                         }
454                 }
455 #endif
456                 if (MAD_RECOVERABLE((data->stream).error)) {
457                         return DECODE_SKIP;
458                 } else {
459                         if ((data->stream).error == MAD_ERROR_BUFLEN)
460                                 return DECODE_CONT;
461                         else {
462                                 ERROR("unrecoverable frame level error "
463                                       "(%s).\n",
464                                       mad_stream_errorstr(&data->stream));
465                                 data->flush = 0;
466                                 return DECODE_BREAK;
467                         }
468                 }
469         }
471         return DECODE_OK;
474 /* xing stuff stolen from alsaplayer, and heavily modified by jat */
475 #define XI_MAGIC (('X' << 8) | 'i')
476 #define NG_MAGIC (('n' << 8) | 'g')
477 #define IN_MAGIC (('I' << 8) | 'n')
478 #define FO_MAGIC (('f' << 8) | 'o')
480 enum xing_magic {
481         XING_MAGIC_XING, /* VBR */
482         XING_MAGIC_INFO  /* CBR */
485 struct xing {
486         long flags;             /* valid fields (see below) */
487         unsigned long frames;   /* total number of frames */
488         unsigned long bytes;    /* total number of bytes */
489         unsigned char toc[100]; /* 100-point seek table */
490         long scale;             /* VBR quality */
491         enum xing_magic magic;  /* header magic */
494 enum {
495         XING_FRAMES = 0x00000001L,
496         XING_BYTES  = 0x00000002L,
497         XING_TOC    = 0x00000004L,
498         XING_SCALE  = 0x00000008L
501 struct lame {
502         char encoder[10];   /* 9 byte encoder name/version ("LAME3.97b") */
503 #if 0
504         /* See related comment in parse_lame() */
505         float peak;         /* replaygain peak */
506         float trackGain;    /* replaygain track gain */
507         float albumGain;    /* replaygain album gain */
508 #endif
509         int encoderDelay;   /* # of added samples at start of mp3 */
510         int encoderPadding; /* # of added samples at end of mp3 */
513 static int parse_xing(struct xing *xing, struct mad_bitptr *ptr, int *oldbitlen)
515         unsigned long bits;
516         int bitlen;
517         int bitsleft;
518         int i;
520         bitlen = *oldbitlen;
522         if (bitlen < 16) goto fail;
523         bits = mad_bit_read(ptr, 16);
524         bitlen -= 16;
526         if (bits == XI_MAGIC) {
527                 if (bitlen < 16) goto fail;
528                 if (mad_bit_read(ptr, 16) != NG_MAGIC) goto fail;
529                 bitlen -= 16;
530                 xing->magic = XING_MAGIC_XING;
531         } else if (bits == IN_MAGIC) {
532                 if (bitlen < 16) goto fail;
533                 if (mad_bit_read(ptr, 16) != FO_MAGIC) goto fail;
534                 bitlen -= 16;
535                 xing->magic = XING_MAGIC_INFO;
536         }
537         else if (bits == NG_MAGIC) xing->magic = XING_MAGIC_XING;
538         else if (bits == FO_MAGIC) xing->magic = XING_MAGIC_INFO;
539         else goto fail;
541         if (bitlen < 32) goto fail;
542         xing->flags = mad_bit_read(ptr, 32);
543         bitlen -= 32;
545         if (xing->flags & XING_FRAMES) {
546                 if (bitlen < 32) goto fail;
547                 xing->frames = mad_bit_read(ptr, 32);
548                 bitlen -= 32;
549         }
551         if (xing->flags & XING_BYTES) {
552                 if (bitlen < 32) goto fail;
553                 xing->bytes = mad_bit_read(ptr, 32);
554                 bitlen -= 32;
555         }
557         if (xing->flags & XING_TOC) {
558                 if (bitlen < 800) goto fail;
559                 for (i = 0; i < 100; ++i) xing->toc[i] = mad_bit_read(ptr, 8);
560                 bitlen -= 800;
561         }
563         if (xing->flags & XING_SCALE) {
564                 if (bitlen < 32) goto fail;
565                 xing->scale = mad_bit_read(ptr, 32);
566                 bitlen -= 32;
567         }
569         /* Make sure we consume no less than 120 bytes (960 bits) in hopes that
570          * the LAME tag is found there, and not right after the Xing header */
571         bitsleft = 960 - ((*oldbitlen) - bitlen);
572         if (bitsleft < 0) goto fail;
573         else if (bitsleft > 0) {
574                 mad_bit_read(ptr, bitsleft);
575                 bitlen -= bitsleft;
576         }
578         *oldbitlen = bitlen;
580         return 1;
581 fail:
582         xing->flags = 0;
583         return 0;
586 static int parse_lame(struct lame *lame, struct mad_bitptr *ptr, int *bitlen)
588         int i;
590         /* Unlike the xing header, the lame tag has a fixed length.  Fail if
591          * not all 36 bytes (288 bits) are there. */
592         if (*bitlen < 288) return 0;
594         for (i = 0; i < 9; i++) lame->encoder[i] = (char)mad_bit_read(ptr, 8);
595         lame->encoder[9] = '\0';
597         /* This is technically incorrect, since the encoder might not be lame.
598          * But there's no other way to determine if this is a lame tag, and we
599          * wouldn't want to go reading a tag that's not there. */
600         if (strncmp(lame->encoder, "LAME", 4) != 0) return 0;
602 #if 0
603         /* Apparently lame versions <3.97b1 do not calculate replaygain.  I'm
604          * using lame 3.97b2, and while it does calculate replaygain, it's
605          * setting the values to 0.  Using --replaygain-(fast|accurate) doesn't
606          * make any difference.  Leaving this code unused until we have a way
607          * of testing it. -- jat */
609         mad_bit_read(ptr, 16);
611         mad_bit_read(ptr, 32); /* peak */
613         mad_bit_read(ptr, 6); /* header */
614         bits = mad_bit_read(ptr, 1); /* sign bit */
615         lame->trackGain = mad_bit_read(ptr, 9); /* gain*10 */
616         lame->trackGain = (bits ? -lame->trackGain : lame->trackGain) / 10;
618         mad_bit_read(ptr, 6); /* header */
619         bits = mad_bit_read(ptr, 1); /* sign bit */
620         lame->albumGain = mad_bit_read(ptr, 9); /* gain*10 */
621         lame->albumGain = (bits ? -lame->albumGain : lame->albumGain) / 10;
623         mad_bit_read(ptr, 16);
624 #else
625         mad_bit_read(ptr, 96);
626 #endif
628         lame->encoderDelay = mad_bit_read(ptr, 12);
629         lame->encoderPadding = mad_bit_read(ptr, 12);
631         mad_bit_read(ptr, 96);
633         *bitlen -= 288;
635         return 1;
638 static int decodeFirstFrame(mp3DecodeData * data, DecoderControl * dc,
639                             MpdTag ** tag, ReplayGainInfo ** replayGainInfo)
641         struct xing xing;
642         struct lame lame;
643         struct mad_bitptr ptr;
644         int bitlen;
645         int ret;
647         /* stfu gcc */
648         memset(&xing, 0, sizeof(struct xing));
649         xing.flags = 0;
651         while (1) {
652                 while ((ret = decodeNextFrameHeader(data, tag, replayGainInfo)) == DECODE_CONT &&
653                        (!dc || !dc->stop));
654                 if (ret == DECODE_BREAK || (dc && dc->stop)) return -1;
655                 if (ret == DECODE_SKIP) continue;
657                 while ((ret = decodeNextFrame(data)) == DECODE_CONT &&
658                        (!dc || !dc->stop));
659                 if (ret == DECODE_BREAK || (dc && dc->stop)) return -1;
660                 if (ret == DECODE_OK) break;
661         }
663         ptr = data->stream.anc_ptr;
664         bitlen = data->stream.anc_bitlen;
666         /*
667          * Attempt to calulcate the length of the song from filesize
668          */
669         {
670                 size_t offset = data->inStream->offset;
671                 mad_timer_t duration = data->frame.header.duration;
672                 float frameTime = ((float)mad_timer_count(duration,
673                                    MAD_UNITS_MILLISECONDS)) / 1000;
675                 if (data->stream.this_frame != NULL)
676                         offset -= data->stream.bufend - data->stream.this_frame;
677                 else
678                         offset -= data->stream.bufend - data->stream.buffer;
680                 if (data->inStream->size >= offset) {
681                         data->totalTime = ((data->inStream->size - offset) *
682                                            8.0) / (data->frame).header.bitrate;
683                         data->maxFrames = data->totalTime / frameTime +
684                                           FRAMES_CUSHION;
685                 } else {
686                         data->maxFrames = FRAMES_CUSHION;
687                         data->totalTime = 0;
688                 }
689         }
690         /*
691          * if an xing tag exists, use that!
692          */
693         if (parse_xing(&xing, &ptr, &bitlen)) {
694                 data->foundXing = 1;
695                 data->muteFrame = MUTEFRAME_SKIP;
697                 if (gaplessPlaybackEnabled && data->inStream->seekable &&
698                     parse_lame(&lame, &ptr, &bitlen)) {
699                         data->dropSamplesAtStart = lame.encoderDelay + DECODERDELAY;
700                         data->dropSamplesAtEnd = lame.encoderPadding;
701                 }
703                 if ((xing.flags & XING_FRAMES) && xing.frames) {
704                         mad_timer_t duration = data->frame.header.duration;
705                         mad_timer_multiply(&duration, xing.frames);
706                         data->totalTime = ((float)mad_timer_count(duration, MAD_UNITS_MILLISECONDS)) / 1000;
707                         data->maxFrames = xing.frames;
708                 }
709         } 
711         if (!data->maxFrames) return -1;
713         data->frameOffset = xmalloc(sizeof(long) * data->maxFrames);
714         data->times = xmalloc(sizeof(mad_timer_t) * data->maxFrames);
716         return 0;
719 static void mp3DecodeDataFinalize(mp3DecodeData * data)
721         mad_synth_finish(&data->synth);
722         mad_frame_finish(&data->frame);
723         mad_stream_finish(&data->stream);
725         if (data->frameOffset) free(data->frameOffset);
726         if (data->times) free(data->times);
729 /* this is primarily used for getting total time for tags */
730 static int getMp3TotalTime(char *file)
732         InputStream inStream;
733         mp3DecodeData data;
734         int ret;
736         if (openInputStream(&inStream, file) < 0)
737                 return -1;
738         initMp3DecodeData(&data, &inStream);
739         if (decodeFirstFrame(&data, NULL, NULL, NULL) < 0)
740                 ret = -1;
741         else
742                 ret = data.totalTime + 0.5;
743         mp3DecodeDataFinalize(&data);
744         closeInputStream(&inStream);
746         return ret;
749 static int openMp3FromInputStream(InputStream * inStream, mp3DecodeData * data,
750                                   DecoderControl * dc, MpdTag ** tag,
751                                   ReplayGainInfo ** replayGainInfo)
753         initMp3DecodeData(data, inStream);
754         *tag = NULL;
755         if (decodeFirstFrame(data, dc, tag, replayGainInfo) < 0) {
756                 mp3DecodeDataFinalize(data);
757                 if (tag && *tag)
758                         freeMpdTag(*tag);
759                 return -1;
760         }
762         return 0;
765 static int mp3Read(mp3DecodeData * data, OutputBuffer * cb, DecoderControl * dc,
766                    ReplayGainInfo ** replayGainInfo)
768         int samplesPerFrame;
769         int samplesLeft;
770         int i;
771         int ret;
772         int skip;
774         if (data->currentFrame >= data->highestFrame) {
775                 mad_timer_add(&data->timer, (data->frame).header.duration);
776                 data->bitRate = (data->frame).header.bitrate;
777                 if (data->currentFrame >= data->maxFrames) {
778                         data->currentFrame = data->maxFrames - 1;
779                 } else {
780                         data->highestFrame++;
781                 }
782                 data->frameOffset[data->currentFrame] = data->inStream->offset;
783                 if (data->stream.this_frame != NULL) {
784                         data->frameOffset[data->currentFrame] -=
785                             data->stream.bufend - data->stream.this_frame;
786                 } else {
787                         data->frameOffset[data->currentFrame] -=
788                             data->stream.bufend - data->stream.buffer;
789                 }
790                 data->times[data->currentFrame] = data->timer;
791         } else {
792                 data->timer = data->times[data->currentFrame];
793         }
794         data->currentFrame++;
795         data->elapsedTime =
796             ((float)mad_timer_count(data->timer, MAD_UNITS_MILLISECONDS)) /
797             1000;
799         switch (data->muteFrame) {
800         case MUTEFRAME_SKIP:
801                 data->muteFrame = 0;
802                 break;
803         case MUTEFRAME_SEEK:
804                 if (dc->seekWhere <= data->elapsedTime) {
805                         data->outputPtr = data->outputBuffer;
806                         clearOutputBuffer(cb);
807                         data->muteFrame = 0;
808                         dc->seek = 0;
809                 }
810                 break;
811         default:
812                 mad_synth_frame(&data->synth, &data->frame);
814                 if (!data->foundFirstFrame) {
815                         samplesPerFrame = (data->synth).pcm.length;
816                         data->dropFramesAtStart = data->dropSamplesAtStart / samplesPerFrame;
817                         data->dropFramesAtEnd = data->dropSamplesAtEnd / samplesPerFrame;
818                         data->dropSamplesAtStart = data->dropSamplesAtStart % samplesPerFrame;
819                         data->dropSamplesAtEnd = data->dropSamplesAtEnd % samplesPerFrame;
820                         data->foundFirstFrame = 1;
821                 }
823                 if (data->dropFramesAtStart > 0) {
824                         data->dropFramesAtStart--;
825                         break;
826                 } else if ((data->dropFramesAtEnd > 0) && 
827                            (data->currentFrame == (data->maxFrames + 1 - data->dropFramesAtEnd))) {
828                         /* stop decoding, effectively dropping all remaining
829                          * frames */
830                         return DECODE_BREAK;
831                 }
833                 if (data->inStream->metaTitle) {
834                         MpdTag *tag = newMpdTag();
835                         if (data->inStream->metaName) {
836                                 addItemToMpdTag(tag,
837                                                 TAG_ITEM_NAME,
838                                                 data->inStream->metaName);
839                         }
840                         addItemToMpdTag(tag, TAG_ITEM_TITLE,
841                                         data->inStream->metaTitle);
842                         free(data->inStream->metaTitle);
843                         data->inStream->metaTitle = NULL;
844                         copyMpdTagToOutputBuffer(cb, tag);
845                         freeMpdTag(tag);
846                 }
848                 samplesLeft = (data->synth).pcm.length;
850                 for (i = 0; i < (data->synth).pcm.length; i++) {
851                         mpd_sint16 *sample;
853                         samplesLeft--;
855                         if (!data->decodedFirstFrame &&
856                             (i < data->dropSamplesAtStart)) {
857                                 continue;
858                         } else if (data->dropSamplesAtEnd &&
859                                    (data->currentFrame == (data->maxFrames - data->dropFramesAtEnd)) &&
860                                    (samplesLeft < data->dropSamplesAtEnd)) {
861                                 /* stop decoding, effectively dropping
862                                  * all remaining samples */
863                                 return DECODE_BREAK;
864                         }
866                         sample = (mpd_sint16 *) data->outputPtr;
867                         *sample = (mpd_sint16) audio_linear_dither(16,
868                                                                    (data->synth).pcm.samples[0][i],
869                                                                    &(data->dither));
870                         data->outputPtr += 2;
872                         if (MAD_NCHANNELS(&(data->frame).header) == 2) {
873                                 sample = (mpd_sint16 *) data->outputPtr;
874                                 *sample = (mpd_sint16) audio_linear_dither(16,
875                                                                            (data->synth).pcm.samples[1][i],
876                                                                            &(data->dither));
877                                 data->outputPtr += 2;
878                         }
880                         if (data->outputPtr >= data->outputBufferEnd) {
881                                 ret = sendDataToOutputBuffer(cb,
882                                                              data->inStream,
883                                                              dc,
884                                                              data->inStream->seekable,
885                                                              data->outputBuffer,
886                                                              data->outputPtr - data->outputBuffer,
887                                                              data->elapsedTime,
888                                                              data->bitRate / 1000,
889                                                              (replayGainInfo != NULL) ? *replayGainInfo : NULL);
890                                 if (ret == OUTPUT_BUFFER_DC_STOP) {
891                                         data->flush = 0;
892                                         return DECODE_BREAK;
893                                 }
895                                 data->outputPtr = data->outputBuffer;
897                                 if (ret == OUTPUT_BUFFER_DC_SEEK)
898                                         break;
899                         }
900                 }
902                 data->decodedFirstFrame = 1;
904                 if (dc->seek && data->inStream->seekable) {
905                         long j = 0;
906                         data->muteFrame = MUTEFRAME_SEEK;
907                         while (j < data->highestFrame && dc->seekWhere >
908                                ((float)mad_timer_count(data->times[j],
909                                                        MAD_UNITS_MILLISECONDS))
910                                / 1000) {
911                                 j++;
912                         }
913                         if (j < data->highestFrame) {
914                                 if (seekMp3InputBuffer(data,
915                                                        data->frameOffset[j]) ==
916                                     0) {
917                                         data->outputPtr = data->outputBuffer;
918                                         clearOutputBuffer(cb);
919                                         data->currentFrame = j;
920                                 } else
921                                         dc->seekError = 1;
922                                 data->muteFrame = 0;
923                                 dc->seek = 0;
924                         }
925                 } else if (dc->seek && !data->inStream->seekable) {
926                         dc->seek = 0;
927                         dc->seekError = 1;
928                 }
929         }
931         while (1) {
932                 skip = 0;
933                 while ((ret =
934                         decodeNextFrameHeader(data, NULL,
935                                               replayGainInfo)) == DECODE_CONT
936                        && !dc->stop) ;
937                 if (ret == DECODE_BREAK || dc->stop || dc->seek)
938                         break;
939                 else if (ret == DECODE_SKIP)
940                         skip = 1;
941                 if (!data->muteFrame) {
942                         while ((ret = decodeNextFrame(data)) == DECODE_CONT &&
943                                !dc->stop && !dc->seek) ;
944                         if (ret == DECODE_BREAK || dc->stop || dc->seek)
945                                 break;
946                 }
947                 if (!skip && ret == DECODE_OK)
948                         break;
949         }
951         if (dc->stop)
952                 return DECODE_BREAK;
954         return ret;
957 static void initAudioFormatFromMp3DecodeData(mp3DecodeData * data,
958                                              AudioFormat * af)
960         af->bits = 16;
961         af->sampleRate = (data->frame).header.samplerate;
962         af->channels = MAD_NCHANNELS(&(data->frame).header);
965 static int mp3_decode(OutputBuffer * cb, DecoderControl * dc,
966                       InputStream * inStream)
968         mp3DecodeData data;
969         MpdTag *tag = NULL;
970         ReplayGainInfo *replayGainInfo = NULL;
972         if (openMp3FromInputStream(inStream, &data, dc, &tag, &replayGainInfo) <
973             0) {
974                 closeInputStream(inStream);
975                 if (!dc->stop) {
976                         ERROR
977                             ("Input does not appear to be a mp3 bit stream.\n");
978                         return -1;
979                 } else {
980                         dc->state = DECODE_STATE_STOP;
981                         dc->stop = 0;
982                 }
983                 return 0;
984         }
986         initAudioFormatFromMp3DecodeData(&data, &(dc->audioFormat));
987         getOutputAudioFormat(&(dc->audioFormat), &(cb->audioFormat));
989         dc->totalTime = data.totalTime;
991         if (inStream->metaTitle) {
992                 if (tag)
993                         freeMpdTag(tag);
994                 tag = newMpdTag();
995                 addItemToMpdTag(tag, TAG_ITEM_TITLE, inStream->metaTitle);
996                 free(inStream->metaTitle);
997                 inStream->metaTitle = NULL;
998                 if (inStream->metaName) {
999                         addItemToMpdTag(tag, TAG_ITEM_NAME, inStream->metaName);
1000                 }
1001                 copyMpdTagToOutputBuffer(cb, tag);
1002                 freeMpdTag(tag);
1003         } else if (tag) {
1004                 if (inStream->metaName) {
1005                         clearItemsFromMpdTag(tag, TAG_ITEM_NAME);
1006                         addItemToMpdTag(tag, TAG_ITEM_NAME, inStream->metaName);
1007                 }
1008                 copyMpdTagToOutputBuffer(cb, tag);
1009                 freeMpdTag(tag);
1010         } else if (inStream->metaName) {
1011                 tag = newMpdTag();
1012                 if (inStream->metaName) {
1013                         addItemToMpdTag(tag, TAG_ITEM_NAME, inStream->metaName);
1014                 }
1015                 copyMpdTagToOutputBuffer(cb, tag);
1016                 freeMpdTag(tag);
1017         }
1019         dc->state = DECODE_STATE_DECODE;
1021         while (mp3Read(&data, cb, dc, &replayGainInfo) != DECODE_BREAK) ;
1022         /* send last little bit if not dc->stop */
1023         if (!dc->stop && data.outputPtr != data.outputBuffer && data.flush) {
1024                 sendDataToOutputBuffer(cb, NULL, dc,
1025                                        data.inStream->seekable,
1026                                        data.outputBuffer,
1027                                        data.outputPtr - data.outputBuffer,
1028                                        data.elapsedTime, data.bitRate / 1000,
1029                                        replayGainInfo);
1030         }
1032         if (replayGainInfo)
1033                 freeReplayGainInfo(replayGainInfo);
1035         closeInputStream(inStream);
1037         if (dc->seek && data.muteFrame == MUTEFRAME_SEEK) {
1038                 clearOutputBuffer(cb);
1039                 dc->seek = 0;
1040         }
1042         flushOutputBuffer(cb);
1043         mp3DecodeDataFinalize(&data);
1045         if (dc->stop) {
1046                 dc->state = DECODE_STATE_STOP;
1047                 dc->stop = 0;
1048         } else
1049                 dc->state = DECODE_STATE_STOP;
1051         return 0;
1054 static MpdTag *mp3_tagDup(char *file)
1056         MpdTag *ret = NULL;
1057         int time;
1059         ret = id3Dup(file);
1061         time = getMp3TotalTime(file);
1063         if (time >= 0) {
1064                 if (!ret)
1065                         ret = newMpdTag();
1066                 ret->time = time;
1067         } else {
1068                 DEBUG("mp3_tagDup: Failed to get total song time from: %s\n",
1069                       file);
1070         }
1072         return ret;
1075 static char *mp3_suffixes[] = { "mp3", "mp2", NULL };
1076 static char *mp3_mimeTypes[] = { "audio/mpeg", NULL };
1078 InputPlugin mp3Plugin = {
1079         "mp3",
1080         mp3_plugin_init,
1081         NULL,
1082         NULL,
1083         mp3_decode,
1084         NULL,
1085         mp3_tagDup,
1086         INPUT_PLUGIN_STREAM_FILE | INPUT_PLUGIN_STREAM_URL,
1087         mp3_suffixes,
1088         mp3_mimeTypes
1090 #else
1092 InputPlugin mp3Plugin;
1094 #endif /* HAVE_MAD */