1
/* the Music Player Daemon (MPD)
2
* (c)2003-2004 by Warren Dukes (shank@mercury.chem.pitt.edu)
3
* This project's homepage is: http://www.musicpd.org
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.
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
19
#include "../inputPlugin.h"
23
#include "../pcm_utils.h"
25
#include "../libmad/mad.h"
31
#include "../libid3tag/id3tag.h"
42
#include <sys/types.h>
47
#define FRAMES_CUSHION 2000
49
#define READ_BUFFER_SIZE 40960
51
#define DECODE_SKIP -3
52
#define DECODE_BREAK -2
53
#define DECODE_CONT -1
56
#define MUTEFRAME_SKIP 1
57
#define MUTEFRAME_SEEK 2
59
/* this is stolen from mpg321! */
65
unsigned long prng(unsigned long state) {
66
return (state * 0x0019660dL + 0x3c6ef35fL) & 0xffffffffL;
69
signed long audio_linear_dither(unsigned int bits, mad_fixed_t sample, struct audio_dither *dither) {
70
unsigned int scalebits;
71
mad_fixed_t output, mask, random;
78
sample += dither->error[0] - dither->error[1] + dither->error[2];
80
dither->error[2] = dither->error[1];
81
dither->error[1] = dither->error[0] / 2;
83
output = sample + (1L << (MAD_F_FRACBITS + 1 - bits - 1));
85
scalebits = MAD_F_FRACBITS + 1 - bits;
86
mask = (1L << scalebits) - 1;
88
random = prng(dither->random);
89
output += (random & mask) - (dither->random & mask);
91
dither->random = random;
99
else if (output < MIN) {
108
dither->error[0] = sample - output;
110
return output >> scalebits;
112
/* end of stolen stuff from mpg321 */
114
/* decoder stuff is based on madlld */
116
#define MP3_DATA_OUTPUT_BUFFER_SIZE 4096
118
typedef struct _mp3DecodeData {
119
struct mad_stream stream;
120
struct mad_frame frame;
121
struct mad_synth synth;
123
unsigned char readBuffer[READ_BUFFER_SIZE];
124
char outputBuffer[MP3_DATA_OUTPUT_BUFFER_SIZE];
126
char * outputBufferEnd;
136
unsigned long bitRate;
137
InputStream * inStream;
138
struct audio_dither dither;
141
void initMp3DecodeData(mp3DecodeData * data, InputStream * inStream) {
142
data->outputPtr = data->outputBuffer;
143
data->outputBufferEnd = data->outputBuffer+MP3_DATA_OUTPUT_BUFFER_SIZE;
145
data->highestFrame = 0;
147
data->frameOffset = NULL;
149
data->currentFrame = 0;
151
data->inStream = inStream;
152
memset(&(data->dither), 0, sizeof(struct audio_dither));
154
mad_stream_init(&data->stream);
155
data->stream.options |= MAD_OPTION_IGNORECRC;
156
mad_frame_init(&data->frame);
157
mad_synth_init(&data->synth);
158
mad_timer_reset(&data->timer);
161
int seekMp3InputBuffer(mp3DecodeData * data, long offset) {
162
if(seekInputStream(data->inStream,offset,SEEK_SET) < 0) {
166
mad_stream_buffer(&data->stream,data->readBuffer,0);
167
(data->stream).error = 0;
172
int fillMp3InputBuffer(mp3DecodeData * data) {
176
unsigned char * readStart;
178
if((data->stream).next_frame!=NULL) {
179
remaining = (data->stream).bufend-(data->stream).next_frame;
180
memmove(data->readBuffer,(data->stream).next_frame,remaining);
181
readStart = (data->readBuffer)+remaining;
182
readSize = READ_BUFFER_SIZE-remaining;
185
readSize = READ_BUFFER_SIZE;
186
readStart = data->readBuffer,
190
readed = readFromInputStream(data->inStream, readStart, (size_t)1,
192
if(readed <= 0 && inputStreamAtEOF(data->inStream)) return -1;
193
/* sleep for a fraction of a second! */
194
else if(readed <= 0) {
199
mad_stream_buffer(&data->stream,data->readBuffer,readed+remaining);
200
(data->stream).error = 0;
206
static MpdTag * mp3_parseId3Tag(mp3DecodeData * data, signed long tagsize) {
208
struct id3_tag * id3Tag = NULL;
210
id3_byte_t const *id3_data;
211
id3_byte_t * allocated = NULL;
213
count = data->stream.bufend - data->stream.this_frame;
215
if(tagsize <= count) {
216
id3_data = data->stream.this_frame;
217
mad_stream_skip(&(data->stream), tagsize);
220
allocated = malloc(tagsize);
221
if(!allocated) goto fail;
223
memcpy(allocated, data->stream.this_frame, count);
224
mad_stream_skip(&(data->stream), count);
226
while(count < tagsize) {
229
len = readFromInputStream(data->inStream,
230
allocated+count, (size_t)1,
232
if(len <= 0 && inputStreamAtEOF(data->inStream)) {
235
else if(len <= 0) my_usleep(10000);
239
if(count != tagsize) {
240
DEBUG("mp3_decode: error parsing ID3 tag\n");
244
id3_data = allocated;
247
id3Tag = id3_tag_parse(id3_data, tagsize);
250
ret = parseId3Tag(id3Tag);
251
id3_tag_delete(id3Tag);
255
if(allocated) free(allocated);
260
int decodeNextFrameHeader(mp3DecodeData * data, MpdTag ** tag) {
261
if((data->stream).buffer==NULL || (data->stream).error==MAD_ERROR_BUFLEN) {
262
if(fillMp3InputBuffer(data) < 0) {
266
if(mad_header_decode(&data->frame.header,&data->stream)) {
268
if((data->stream).error==MAD_ERROR_LOSTSYNC &&
269
(data->stream).this_frame)
271
signed long tagsize = id3_tag_query(
272
(data->stream).this_frame,
273
(data->stream).bufend-
274
(data->stream).this_frame);
278
*tag = mp3_parseId3Tag(data, tagsize);
282
mad_stream_skip(&(data->stream),
289
if(MAD_RECOVERABLE((data->stream).error)) {
293
if((data->stream).error==MAD_ERROR_BUFLEN) return DECODE_CONT;
296
ERROR("unrecoverable frame level error "
298
mad_stream_errorstr(&data->stream));
304
if(data->frame.header.layer != MAD_LAYER_III) {
311
int decodeNextFrame(mp3DecodeData * data) {
312
if((data->stream).buffer==NULL || (data->stream).error==MAD_ERROR_BUFLEN) {
313
if(fillMp3InputBuffer(data) < 0) {
317
if(mad_frame_decode(&data->frame,&data->stream)) {
319
if((data->stream).error==MAD_ERROR_LOSTSYNC) {
320
signed long tagsize = id3_tag_query(
321
(data->stream).this_frame,
322
(data->stream).bufend-
323
(data->stream).this_frame);
325
mad_stream_skip(&(data->stream),tagsize);
330
if(MAD_RECOVERABLE((data->stream).error)) {
334
if((data->stream).error==MAD_ERROR_BUFLEN) return DECODE_CONT;
337
ERROR("unrecoverable frame level error "
339
mad_stream_errorstr(&data->stream));
349
/* xing stuff stolen from alsaplayer */
350
# define XING_MAGIC (('X' << 24) | ('i' << 16) | ('n' << 8) | 'g')
353
long flags; /* valid fields (see below) */
354
unsigned long frames; /* total number of frames */
355
unsigned long bytes; /* total number of bytes */
356
unsigned char toc[100]; /* 100-point seek table */
361
XING_FRAMES = 0x00000001L,
362
XING_BYTES = 0x00000002L,
363
XING_TOC = 0x00000004L,
364
XING_SCALE = 0x00000008L
367
int parse_xing(struct xing *xing, struct mad_bitptr ptr, unsigned int bitlen)
369
if (bitlen < 64 || mad_bit_read(&ptr, 32) != XING_MAGIC) goto fail;
371
xing->flags = mad_bit_read(&ptr, 32);
374
if (xing->flags & XING_FRAMES) {
375
if (bitlen < 32) goto fail;
376
xing->frames = mad_bit_read(&ptr, 32);
380
if (xing->flags & XING_BYTES) {
381
if (bitlen < 32) goto fail;
382
xing->bytes = mad_bit_read(&ptr, 32);
386
if (xing->flags & XING_TOC) {
388
if (bitlen < 800) goto fail;
389
for (i = 0; i < 100; ++i) xing->toc[i] = mad_bit_read(&ptr, 8);
393
if (xing->flags & XING_SCALE) {
394
if (bitlen < 32) goto fail;
395
xing->scale = mad_bit_read(&ptr, 32);
406
int decodeFirstFrame(mp3DecodeData * data, DecoderControl * dc,
413
memset(&xing,0,sizeof(struct xing));
418
while((ret = decodeNextFrameHeader(data, tag))==DECODE_CONT &&
420
if(ret==DECODE_SKIP) skip = 1;
421
else if(ret==DECODE_BREAK || (dc && dc->stop)) return -1;
422
while((ret = decodeNextFrame(data))==DECODE_CONT &&
424
if(ret==DECODE_BREAK || (dc && dc->stop)) return -1;
425
if(!skip && ret==DECODE_OK) break;
428
if(parse_xing(&xing,data->stream.anc_ptr,data->stream.anc_bitlen)) {
429
if(xing.flags & XING_FRAMES) {
430
mad_timer_t duration = data->frame.header.duration;
431
mad_timer_multiply(&duration,xing.frames);
432
data->muteFrame = MUTEFRAME_SKIP;
433
data->totalTime = ((float)mad_timer_count(duration,
434
MAD_UNITS_MILLISECONDS))/1000;
435
data->maxFrames = xing.frames;
439
size_t offset = data->inStream->offset;
440
mad_timer_t duration = data->frame.header.duration;
441
float frameTime = ((float)mad_timer_count(duration,
442
MAD_UNITS_MILLISECONDS))/1000;
443
if(data->stream.this_frame!=NULL) {
444
offset-= data->stream.bufend-data->stream.this_frame;
447
offset-= data->stream.bufend-data->stream.buffer;
449
if(data->inStream->size >= offset) {
450
data->totalTime = ((data->inStream->size-offset)*8.0)/
451
(data->frame).header.bitrate;
453
data->totalTime/frameTime+FRAMES_CUSHION;
456
data->maxFrames = FRAMES_CUSHION;
461
data->frameOffset = malloc(sizeof(long)*data->maxFrames);
462
data->times = malloc(sizeof(mad_timer_t)*data->maxFrames);
467
void mp3DecodeDataFinalize(mp3DecodeData * data) {
468
mad_synth_finish(&data->synth);
469
mad_frame_finish(&data->frame);
470
mad_stream_finish(&data->stream);
472
if(data->frameOffset) free(data->frameOffset);
473
if(data->times) free(data->times);
476
/* this is primarily used for getting total time for tags */
477
int getMp3TotalTime(char * file) {
478
InputStream inStream;
482
if(openInputStream(&inStream, file) < 0) return -1;
483
initMp3DecodeData(&data,&inStream);
484
if(decodeFirstFrame(&data, NULL, NULL)<0) ret = -1;
485
else ret = data.totalTime+0.5;
486
mp3DecodeDataFinalize(&data);
487
closeInputStream(&inStream);
492
int openMp3FromInputStream(InputStream * inStream, mp3DecodeData * data,
493
DecoderControl * dc, MpdTag ** tag)
495
initMp3DecodeData(data, inStream);
497
if(decodeFirstFrame(data, dc, tag)<0) {
498
mp3DecodeDataFinalize(data);
499
if(tag && *tag) freeMpdTag(*tag);
506
int mp3Read(mp3DecodeData * data, OutputBuffer * cb, DecoderControl * dc) {
511
if(data->currentFrame>=data->highestFrame) {
512
mad_timer_add(&data->timer,(data->frame).header.duration);
513
data->bitRate = (data->frame).header.bitrate;
514
if(data->currentFrame>=data->maxFrames) {
515
data->currentFrame = data->maxFrames - 1;
517
else data->highestFrame++;
518
data->frameOffset[data->currentFrame] = data->inStream->offset;
519
if(data->stream.this_frame!=NULL) {
520
data->frameOffset[data->currentFrame]-=
522
data->stream.this_frame;
525
data->frameOffset[data->currentFrame]-=
526
data->stream.bufend-data->stream.buffer;
528
data->times[data->currentFrame] = data->timer;
530
else data->timer = data->times[data->currentFrame];
531
data->currentFrame++;
532
data->elapsedTime = ((float)mad_timer_count(data->timer,MAD_UNITS_MILLISECONDS))/1000;
534
switch(data->muteFrame) {
539
if(dc->seekWhere<=data->elapsedTime) {
540
data->outputPtr = data->outputBuffer;
541
clearOutputBuffer(cb);
547
mad_synth_frame(&data->synth,&data->frame);
549
if(data->inStream->metaTitle) {
550
MpdTag * tag = newMpdTag();
551
if(data->inStream->metaName) {
552
tag->name = strdup(data->inStream->metaName);
554
tag->title = strdup(data->inStream->metaTitle);
555
free(data->inStream->metaTitle);
556
data->inStream->metaTitle = NULL;
557
copyMpdTagToOutputBuffer(cb, tag);
561
for(i=0;i<(data->synth).pcm.length;i++) {
564
sample = (mpd_sint16 *)data->outputPtr;
565
*sample = (mpd_sint16) audio_linear_dither(16,
566
(data->synth).pcm.samples[0][i],
570
if(MAD_NCHANNELS(&(data->frame).header)==2) {
571
sample = (mpd_sint16 *)data->outputPtr;
572
*sample = (mpd_sint16) audio_linear_dither(16,
573
(data->synth).pcm.samples[1][i],
578
if(data->outputPtr>=data->outputBufferEnd) {
580
ret = sendDataToOutputBuffer(cb,
583
data->inStream->seekable,
589
if(ret == OUTPUT_BUFFER_DC_STOP) {
594
data->outputPtr = data->outputBuffer;
596
if(ret == OUTPUT_BUFFER_DC_SEEK) break;
600
if(dc->seek && data->inStream->seekable) {
602
data->muteFrame = MUTEFRAME_SEEK;
603
while(i<data->highestFrame && dc->seekWhere >
604
((float)mad_timer_count(data->times[i],
605
MAD_UNITS_MILLISECONDS))/1000)
609
if(i<data->highestFrame) {
610
if(seekMp3InputBuffer(data,
611
data->frameOffset[i]) == 0)
613
data->outputPtr = data->outputBuffer;
614
clearOutputBuffer(cb);
615
data->currentFrame = i;
617
else dc->seekError = 1;
622
else if(dc->seek && !data->inStream->seekable) {
630
while((ret = decodeNextFrameHeader(data, NULL))==DECODE_CONT &&
631
!dc->stop && !dc->seek);
632
if(ret==DECODE_BREAK || dc->stop || dc->seek) break;
633
else if(ret==DECODE_SKIP) skip = 1;
634
if(!data->muteFrame) {
635
while((ret = decodeNextFrame(data))==DECODE_CONT &&
636
!dc->stop && !dc->seek);
637
if(ret==DECODE_BREAK || dc->stop || dc->seek) break;
639
if(!skip && ret==DECODE_OK) break;
642
if(dc->stop) return DECODE_BREAK;
647
void initAudioFormatFromMp3DecodeData(mp3DecodeData * data, AudioFormat * af) {
649
af->sampleRate = (data->frame).header.samplerate;
650
af->channels = MAD_NCHANNELS(&(data->frame).header);
653
int mp3_decode(OutputBuffer * cb, DecoderControl * dc, InputStream * inStream) {
657
if(openMp3FromInputStream(inStream, &data, dc, &tag) < 0) {
658
closeInputStream(inStream);
660
ERROR("Input does not appear to be a mp3 bit stream.\n");
664
dc->state = DECODE_STATE_STOP;
670
initAudioFormatFromMp3DecodeData(&data, &(dc->audioFormat));
671
getOutputAudioFormat(&(dc->audioFormat), &(cb->audioFormat));
673
dc->totalTime = data.totalTime;
675
if(inStream->metaTitle) {
676
if(tag) freeMpdTag(tag);
678
tag->title = strdup(inStream->metaTitle);
679
free(inStream->metaTitle);
680
inStream->metaTitle = NULL;
681
if(inStream->metaName) {
682
tag->name = strdup(inStream->metaName);
684
copyMpdTagToOutputBuffer(cb, tag);
688
if(inStream->metaName) {
689
if(tag->name) free(tag->name);
690
tag->name = strdup(inStream->metaName);
692
copyMpdTagToOutputBuffer(cb, tag);
695
else if(inStream->metaName) {
697
if(inStream->metaName) {
698
tag->name = strdup(inStream->metaName);
700
copyMpdTagToOutputBuffer(cb, tag);
704
dc->state = DECODE_STATE_DECODE;
706
while(mp3Read(&data,cb,dc)!=DECODE_BREAK);
707
/* send last little bit if not dc->stop */
708
if(!dc->stop && data.outputPtr!=data.outputBuffer && data.flush) {
709
sendDataToOutputBuffer(cb, NULL, dc,
710
data.inStream->seekable,
712
data.outputPtr-data.outputBuffer,
713
data.elapsedTime,data.bitRate/1000);
716
closeInputStream(inStream);
718
if(dc->seek && data.muteFrame == MUTEFRAME_SEEK) {
719
clearOutputBuffer(cb);
723
flushOutputBuffer(cb);
724
mp3DecodeDataFinalize(&data);
727
dc->state = DECODE_STATE_STOP;
730
else dc->state = DECODE_STATE_STOP;
735
MpdTag * mp3_tagDup(char * file) {
741
time = getMp3TotalTime(file);
744
if(!ret) ret = newMpdTag();
751
char * mp3_suffixes[] = {"mp3", NULL};
752
char * mp3_mimeTypes[] = {"audio/mpeg", NULL};
754
InputPlugin mp3Plugin =
762
INPUT_PLUGIN_STREAM_FILE | INPUT_PLUGIN_STREAM_URL,
768
InputPlugin mp3Plugin =