aboutsummaryrefslogtreecommitdiffstats
path: root/src/inputPlugins/mp3_plugin.c
blob: a9dad890434eec317e604840803206bc11ad24d5 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
/* the Music Player Daemon (MPD)
 * Copyright (C) 2003-2007 by Warren Dukes (warren.dukes@gmail.com)
 * This project's homepage is: http://www.musicpd.org
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

#include "../inputPlugin.h"

#ifdef HAVE_MAD

#include <mad.h>

#ifdef HAVE_ID3TAG
#include <id3tag.h>
#endif

#include "../log.h"
#include "../utils.h"
#include "../conf.h"

#define FRAMES_CUSHION    2000

#define READ_BUFFER_SIZE  40960

enum mp3_action {
	DECODE_SKIP = -3,
	DECODE_BREAK = -2,
	DECODE_CONT = -1,
	DECODE_OK = 0
};

enum muteframe {
	MUTEFRAME_NONE,
	MUTEFRAME_SKIP,
	MUTEFRAME_SEEK
};

/* the number of samples of silence the decoder inserts at start */
#define DECODERDELAY 529

#define DEFAULT_GAPLESS_MP3_PLAYBACK 1

static int gaplessPlaybackEnabled;

/* this is stolen from mpg321! */
struct audio_dither {
	mad_fixed_t error[3];
	mad_fixed_t random;
};

static unsigned long prng(unsigned long state)
{
	return (state * 0x0019660dL + 0x3c6ef35fL) & 0xffffffffL;
}

static mpd_sint16 audio_linear_dither(unsigned int bits, mad_fixed_t sample,
				      struct audio_dither *dither)
{
	unsigned int scalebits;
	mad_fixed_t output, mask, rnd;

	enum {
		MIN = -MAD_F_ONE,
		MAX = MAD_F_ONE - 1
	};

	sample += dither->error[0] - dither->error[1] + dither->error[2];

	dither->error[2] = dither->error[1];
	dither->error[1] = dither->error[0] / 2;

	output = sample + (1L << (MAD_F_FRACBITS + 1 - bits - 1));

	scalebits = MAD_F_FRACBITS + 1 - bits;
	mask = (1L << scalebits) - 1;

	rnd = prng(dither->random);
	output += (rnd & mask) - (dither->random & mask);

	dither->random = rnd;

	if (output > MAX) {
		output = MAX;

		if (sample > MAX)
			sample = MAX;
	} else if (output < MIN) {
		output = MIN;

		if (sample < MIN)
			sample = MIN;
	}

	output &= ~mask;

	dither->error[0] = sample - output;

	return (mpd_sint16)(output >> scalebits);
}

static unsigned dither_buffer(mpd_sint16 *dest0, const struct mad_synth *synth,
			      struct audio_dither *dither,
			      unsigned int start, unsigned int end,
			      unsigned int num_channels)
{
	mpd_sint16 *dest = dest0;
	unsigned int i;

	for (i = start; i < end; ++i) {
		*dest++ = audio_linear_dither(16,
					      synth->pcm.samples[0][i],
					      dither);

		if (num_channels == 2)
			*dest++ = audio_linear_dither(16,
						      synth->pcm.samples[1][i],
						      dither);
	}

	return dest - dest0;
}

/* end of stolen stuff from mpg321 */

static int mp3_plugin_init(void)
{
	gaplessPlaybackEnabled = getBoolConfigParam(CONF_GAPLESS_MP3_PLAYBACK,
	                                            1);
	if (gaplessPlaybackEnabled == CONF_BOOL_UNSET)
		gaplessPlaybackEnabled = DEFAULT_GAPLESS_MP3_PLAYBACK;
	return 1;
}

/* decoder stuff is based on madlld */

#define MP3_DATA_OUTPUT_BUFFER_SIZE 2048

typedef struct _mp3DecodeData {
	struct mad_stream stream;
	struct mad_frame frame;
	struct mad_synth synth;
	mad_timer_t timer;
	unsigned char readBuffer[READ_BUFFER_SIZE];
	mpd_sint16 outputBuffer[MP3_DATA_OUTPUT_BUFFER_SIZE];
	float totalTime;
	float elapsedTime;
	enum muteframe muteFrame;
	long *frameOffset;
	mad_timer_t *times;
	unsigned long highestFrame;
	unsigned long maxFrames;
	unsigned long currentFrame;
	unsigned int dropFramesAtStart;
	unsigned int dropFramesAtEnd;
	unsigned int dropSamplesAtStart;
	unsigned int dropSamplesAtEnd;
	int foundXing;
	int foundFirstFrame;
	int decodedFirstFrame;
	unsigned long bitRate;
	InputStream *inStream;
	struct audio_dither dither;
	enum mad_layer layer;
} mp3DecodeData;

static void initMp3DecodeData(mp3DecodeData * data, InputStream * inStream)
{
	data->muteFrame = MUTEFRAME_NONE;
	data->highestFrame = 0;
	data->maxFrames = 0;
	data->frameOffset = NULL;
	data->times = NULL;
	data->currentFrame = 0;
	data->dropFramesAtStart = 0;
	data->dropFramesAtEnd = 0;
	data->dropSamplesAtStart = 0;
	data->dropSamplesAtEnd = 0;
	data->foundXing = 0;
	data->foundFirstFrame = 0;
	data->decodedFirstFrame = 0;
	data->inStream = inStream;
	data->layer = 0;
	memset(&(data->dither), 0, sizeof(struct audio_dither));

	mad_stream_init(&data->stream);
	mad_stream_options(&data->stream, MAD_OPTION_IGNORECRC);
	mad_frame_init(&data->frame);
	mad_synth_init(&data->synth);
	mad_timer_reset(&data->timer);
}

static int seekMp3InputBuffer(mp3DecodeData * data, long offset)
{
	if (seekInputStream(data->inStream, offset, SEEK_SET) < 0) {
		return -1;
	}

	mad_stream_buffer(&data->stream, data->readBuffer, 0);
	(data->stream).error = 0;

	return 0;
}

static int fillMp3InputBuffer(mp3DecodeData * data)
{
	size_t readSize;
	size_t remaining;
	size_t readed;
	unsigned char *readStart;

	if ((data->stream).next_frame != NULL) {
		remaining = (data->stream).bufend - (data->stream).next_frame;
		memmove(data->readBuffer, (data->stream).next_frame, remaining);
		readStart = (data->readBuffer) + remaining;
		readSize = READ_BUFFER_SIZE - remaining;
	} else {
		readSize = READ_BUFFER_SIZE;
		readStart = data->readBuffer, remaining = 0;
	}

	/* we've exhausted the read buffer, so give up!, these potential
	 * mp3 frames are way too big, and thus unlikely to be mp3 frames */
	if (readSize == 0)
		return -1;

	readed = readFromInputStream(data->inStream, readStart, (size_t) 1,
				     readSize);
	if (readed <= 0 && inputStreamAtEOF(data->inStream))
		return -1;
	/* sleep for a fraction of a second! */
	else if (readed <= 0) {
		readed = 0;
		my_usleep(10000);
	}

	mad_stream_buffer(&data->stream, data->readBuffer, readed + remaining);
	(data->stream).error = 0;

	return 0;
}

#ifdef HAVE_ID3TAG
static ReplayGainInfo *parseId3ReplayGainInfo(struct id3_tag *tag)
{
	int i;
	char *key;
	char *value;
	struct id3_frame *frame;
	int found = 0;
	ReplayGainInfo *replayGainInfo;

	replayGainInfo = newReplayGainInfo();

	for (i = 0; (frame = id3_tag_findframe(tag, "TXXX", i)); i++) {
		if (frame->nfields < 3)
			continue;

		key = (char *)
		    id3_ucs4_latin1duplicate(id3_field_getstring
					     (&frame->fields[1]));
		value = (char *)
		    id3_ucs4_latin1duplicate(id3_field_getstring
					     (&frame->fields[2]));

		if (strcasecmp(key, "replaygain_track_gain") == 0) {
			replayGainInfo->trackGain = atof(value);
			found = 1;
		} else if (strcasecmp(key, "replaygain_album_gain") == 0) {
			replayGainInfo->albumGain = atof(value);
			found = 1;
		} else if (strcasecmp(key, "replaygain_track_peak") == 0) {
			replayGainInfo->trackPeak = atof(value);
			found = 1;
		} else if (strcasecmp(key, "replaygain_album_peak") == 0) {
			replayGainInfo->albumPeak = atof(value);
			found = 1;
		}

		free(key);
		free(value);
	}

	if (found)
		return replayGainInfo;
	freeReplayGainInfo(replayGainInfo);
	return NULL;
}
#endif

#ifdef HAVE_ID3TAG
static void mp3_parseId3Tag(mp3DecodeData * data, size_t tagsize,
			    struct mpd_tag ** mpdTag, ReplayGainInfo ** replayGainInfo)
{
	struct id3_tag *id3Tag = NULL;
	id3_length_t count;
	id3_byte_t const *id3_data;
	id3_byte_t *allocated = NULL;
	struct mpd_tag *tmpMpdTag;
	ReplayGainInfo *tmpReplayGainInfo;

	count = data->stream.bufend - data->stream.this_frame;

	if (tagsize <= count) {
		id3_data = data->stream.this_frame;
		mad_stream_skip(&(data->stream), tagsize);
	} else {
		allocated = xmalloc(tagsize);
		if (!allocated)
			goto fail;

		memcpy(allocated, data->stream.this_frame, count);
		mad_stream_skip(&(data->stream), count);

		while (count < tagsize) {
			size_t len;

			len = readFromInputStream(data->inStream,
						  allocated + count, (size_t) 1,
						  tagsize - count);
			if (len <= 0 && inputStreamAtEOF(data->inStream))
				break;
			else
				count += len;
		}

		if (count != tagsize) {
			DEBUG("mp3_decode: error parsing ID3 tag\n");
			goto fail;
		}

		id3_data = allocated;
	}

	id3Tag = id3_tag_parse(id3_data, tagsize);
	if (!id3Tag)
		goto fail;

	if (mpdTag) {
		tmpMpdTag = tag_id3_import(id3Tag);
		if (tmpMpdTag) {
			if (*mpdTag)
				tag_free(*mpdTag);
			*mpdTag = tmpMpdTag;
		}
	}

	if (replayGainInfo) {
		tmpReplayGainInfo = parseId3ReplayGainInfo(id3Tag);
		if (tmpReplayGainInfo) {
			if (*replayGainInfo)
				freeReplayGainInfo(*replayGainInfo);
			*replayGainInfo = tmpReplayGainInfo;
		}
	}

	id3_tag_delete(id3Tag);
fail:
	if (allocated)
		free(allocated);
}
#endif

static enum mp3_action
decodeNextFrameHeader(mp3DecodeData * data, struct mpd_tag ** tag,
		      ReplayGainInfo ** replayGainInfo)
{
	enum mad_layer layer;

	if ((data->stream).buffer == NULL
	    || (data->stream).error == MAD_ERROR_BUFLEN) {
		if (fillMp3InputBuffer(data) < 0) {
			return DECODE_BREAK;
		}
	}
	if (mad_header_decode(&data->frame.header, &data->stream)) {
#ifdef HAVE_ID3TAG
		if ((data->stream).error == MAD_ERROR_LOSTSYNC &&
		    (data->stream).this_frame) {
			signed long tagsize = id3_tag_query((data->stream).
							    this_frame,
							    (data->stream).
							    bufend -
							    (data->stream).
							    this_frame);

			if (tagsize > 0) {
				if (tag && !(*tag)) {
					mp3_parseId3Tag(data, (size_t)tagsize,
							tag, replayGainInfo);
				} else {
					mad_stream_skip(&(data->stream),
							tagsize);
				}
				return DECODE_CONT;
			}
		}
#endif
		if (MAD_RECOVERABLE((data->stream).error)) {
			return DECODE_SKIP;
		} else {
			if ((data->stream).error == MAD_ERROR_BUFLEN)
				return DECODE_CONT;
			else {
				ERROR("unrecoverable frame level error "
				      "(%s).\n",
				      mad_stream_errorstr(&data->stream));
				return DECODE_BREAK;
			}
		}
	}

	layer = data->frame.header.layer;
	if (!data->layer) {
		if (layer != MAD_LAYER_II && layer != MAD_LAYER_III) {
			/* Only layer 2 and 3 have been tested to work */
			return DECODE_SKIP;
		}
		data->layer = layer;
	} else if (layer != data->layer) {
		/* Don't decode frames with a different layer than the first */
		return DECODE_SKIP;
	}

	return DECODE_OK;
}

static enum mp3_action
decodeNextFrame(mp3DecodeData * data)
{
	if ((data->stream).buffer == NULL
	    || (data->stream).error == MAD_ERROR_BUFLEN) {
		if (fillMp3InputBuffer(data) < 0) {
			return DECODE_BREAK;
		}
	}
	if (mad_frame_decode(&data->frame, &data->stream)) {
#ifdef HAVE_ID3TAG
		if ((data->stream).error == MAD_ERROR_LOSTSYNC) {
			signed long tagsize = id3_tag_query((data->stream).
							    this_frame,
							    (data->stream).
							    bufend -
							    (data->stream).
							    this_frame);
			if (tagsize > 0) {
				mad_stream_skip(&(data->stream), tagsize);
				return DECODE_CONT;
			}
		}
#endif
		if (MAD_RECOVERABLE((data->stream).error)) {
			return DECODE_SKIP;
		} else {
			if ((data->stream).error == MAD_ERROR_BUFLEN)
				return DECODE_CONT;
			else {
				ERROR("unrecoverable frame level error "
				      "(%s).\n",
				      mad_stream_errorstr(&data->stream));
				return DECODE_BREAK;
			}
		}
	}

	return DECODE_OK;
}

/* xing stuff stolen from alsaplayer, and heavily modified by jat */
#define XI_MAGIC (('X' << 8) | 'i')
#define NG_MAGIC (('n' << 8) | 'g')
#define IN_MAGIC (('I' << 8) | 'n')
#define FO_MAGIC (('f' << 8) | 'o')

enum xing_magic {
	XING_MAGIC_XING, /* VBR */
	XING_MAGIC_INFO  /* CBR */
};

struct xing {
	long flags;             /* valid fields (see below) */
	unsigned long frames;   /* total number of frames */
	unsigned long bytes;    /* total number of bytes */
	unsigned char toc[100]; /* 100-point seek table */
	long scale;             /* VBR quality */
	enum xing_magic magic;  /* header magic */
};

enum {
	XING_FRAMES = 0x00000001L,
	XING_BYTES  = 0x00000002L,
	XING_TOC    = 0x00000004L,
	XING_SCALE  = 0x00000008L
};

struct version {
	unsigned major;
	unsigned minor;
};

struct lame {
	char encoder[10];       /* 9 byte encoder name/version ("LAME3.97b") */
	struct version version; /* struct containing just the version */
	float peak;             /* replaygain peak */
	float trackGain;        /* replaygain track gain */
	float albumGain;        /* replaygain album gain */
	int encoderDelay;       /* # of added samples at start of mp3 */
	int encoderPadding;     /* # of added samples at end of mp3 */
	int crc;                /* CRC of the first 190 bytes of this frame */
};

static int parse_xing(struct xing *xing, struct mad_bitptr *ptr, int *oldbitlen)
{
	unsigned long bits;
	int bitlen;
	int bitsleft;
	int i;

	bitlen = *oldbitlen;

	if (bitlen < 16) goto fail;
	bits = mad_bit_read(ptr, 16);
	bitlen -= 16;

	if (bits == XI_MAGIC) {
		if (bitlen < 16) goto fail;
		if (mad_bit_read(ptr, 16) != NG_MAGIC) goto fail;
		bitlen -= 16;
		xing->magic = XING_MAGIC_XING;
	} else if (bits == IN_MAGIC) {
		if (bitlen < 16) goto fail;
		if (mad_bit_read(ptr, 16) != FO_MAGIC) goto fail;
		bitlen -= 16;
		xing->magic = XING_MAGIC_INFO;
	}
	else if (bits == NG_MAGIC) xing->magic = XING_MAGIC_XING;
	else if (bits == FO_MAGIC) xing->magic = XING_MAGIC_INFO;
	else goto fail;

	if (bitlen < 32) goto fail;
	xing->flags = mad_bit_read(ptr, 32);
	bitlen -= 32;

	if (xing->flags & XING_FRAMES) {
		if (bitlen < 32) goto fail;
		xing->frames = mad_bit_read(ptr, 32);
		bitlen -= 32;
	}

	if (xing->flags & XING_BYTES) {
		if (bitlen < 32) goto fail;
		xing->bytes = mad_bit_read(ptr, 32);
		bitlen -= 32;
	}

	if (xing->flags & XING_TOC) {
		if (bitlen < 800) goto fail;
		for (i = 0; i < 100; ++i) xing->toc[i] = mad_bit_read(ptr, 8);
		bitlen -= 800;
	}

	if (xing->flags & XING_SCALE) {
		if (bitlen < 32) goto fail;
		xing->scale = mad_bit_read(ptr, 32);
		bitlen -= 32;
	}

	/* Make sure we consume no less than 120 bytes (960 bits) in hopes that
	 * the LAME tag is found there, and not right after the Xing header */
	bitsleft = 960 - ((*oldbitlen) - bitlen);
	if (bitsleft < 0) goto fail;
	else if (bitsleft > 0) {
		mad_bit_read(ptr, bitsleft);
		bitlen -= bitsleft;
	}

	*oldbitlen = bitlen;

	return 1;
fail:
	xing->flags = 0;
	return 0;
}

static int parse_lame(struct lame *lame, struct mad_bitptr *ptr, int *bitlen)
{
	int adj = 0;
	int name;
	int orig;
	int sign;
	int gain;
	int i;

	/* Unlike the xing header, the lame tag has a fixed length.  Fail if
	 * not all 36 bytes (288 bits) are there. */
	if (*bitlen < 288)
		return 0;

	for (i = 0; i < 9; i++)
		lame->encoder[i] = (char)mad_bit_read(ptr, 8);
	lame->encoder[9] = '\0';

	*bitlen -= 72;

	/* This is technically incorrect, since the encoder might not be lame.
	 * But there's no other way to determine if this is a lame tag, and we
	 * wouldn't want to go reading a tag that's not there. */
	if (strncmp(lame->encoder, "LAME", 4) != 0)
		return 0;

	if (sscanf(lame->encoder+4, "%u.%u",
	           &lame->version.major, &lame->version.minor) != 2)
		return 0;

	DEBUG("detected LAME version %i.%i (\"%s\")\n",
	      lame->version.major, lame->version.minor, lame->encoder);

	/* The reference volume was changed from the 83dB used in the
	 * ReplayGain spec to 89dB in lame 3.95.1.  Bump the gain for older
	 * versions, since everyone else uses 89dB instead of 83dB.
	 * Unfortunately, lame didn't differentiate between 3.95 and 3.95.1, so
	 * it's impossible to make the proper adjustment for 3.95.
	 * Fortunately, 3.95 was only out for about a day before 3.95.1 was
	 * released. -- tmz */
	if (lame->version.major < 3 ||
	    (lame->version.major == 3 && lame->version.minor < 95))
		adj = 6;

	mad_bit_read(ptr, 16);

	lame->peak = mad_f_todouble(mad_bit_read(ptr, 32) << 5); /* peak */
	DEBUG("LAME peak found: %f\n", lame->peak);

	lame->trackGain = 0;
	name = mad_bit_read(ptr, 3); /* gain name */
	orig = mad_bit_read(ptr, 3); /* gain originator */
	sign = mad_bit_read(ptr, 1); /* sign bit */
	gain = mad_bit_read(ptr, 9); /* gain*10 */
	if (gain && name == 1 && orig != 0) {
		lame->trackGain = ((sign ? -gain : gain) / 10.0) + adj;
		DEBUG("LAME track gain found: %f\n", lame->trackGain);
	}

	/* tmz reports that this isn't currently written by any version of lame
	 * (as of 3.97).  Since we have no way of testing it, don't use it.
	 * Wouldn't want to go blowing someone's ears just because we read it
	 * wrong. :P -- jat */
	lame->albumGain = 0;
#if 0
	name = mad_bit_read(ptr, 3); /* gain name */
	orig = mad_bit_read(ptr, 3); /* gain originator */
	sign = mad_bit_read(ptr, 1); /* sign bit */
	gain = mad_bit_read(ptr, 9); /* gain*10 */
	if (gain && name == 2 && orig != 0) {
		lame->albumGain = ((sign ? -gain : gain) / 10.0) + adj;
		DEBUG("LAME album gain found: %f\n", lame->trackGain);
	}
#else
	mad_bit_read(ptr, 16);
#endif

	mad_bit_read(ptr, 16);

	lame->encoderDelay = mad_bit_read(ptr, 12);
	lame->encoderPadding = mad_bit_read(ptr, 12);

	DEBUG("encoder delay is %i, encoder padding is %i\n",
	      lame->encoderDelay, lame->encoderPadding);

	mad_bit_read(ptr, 80);

	lame->crc = mad_bit_read(ptr, 16);

	*bitlen -= 216;

	return 1;
}

static int decodeFirstFrame(mp3DecodeData * data,
                            struct mpd_tag ** tag, ReplayGainInfo ** replayGainInfo)
{
	struct xing xing;
	struct lame lame;
	struct mad_bitptr ptr;
	int bitlen;
	int ret;

	/* stfu gcc */
	memset(&xing, 0, sizeof(struct xing));
	xing.flags = 0;

	while (1) {
		while ((ret = decodeNextFrameHeader(data, tag, replayGainInfo)) == DECODE_CONT &&
		       !dc_intr());
		if (ret == DECODE_BREAK || dc_intr()) return -1;
		if (ret == DECODE_SKIP) continue;

		while ((ret = decodeNextFrame(data)) == DECODE_CONT &&
		       !dc_intr());
		if (ret == DECODE_BREAK || dc_intr()) return -1;
		if (ret == DECODE_OK) break;
	}

	ptr = data->stream.anc_ptr;
	bitlen = data->stream.anc_bitlen;

	/*
	 * Attempt to calulcate the length of the song from filesize
	 */
	{
		size_t offset = data->inStream->offset;
		mad_timer_t duration = data->frame.header.duration;
		float frameTime = ((float)mad_timer_count(duration,
		                   MAD_UNITS_MILLISECONDS)) / 1000;

		if (data->stream.this_frame != NULL)
			offset -= data->stream.bufend - data->stream.this_frame;
		else
			offset -= data->stream.bufend - data->stream.buffer;

		if (data->inStream->size >= offset) {
			data->totalTime = ((data->inStream->size - offset) *
			                   8.0) / (data->frame).header.bitrate;
			data->maxFrames = data->totalTime / frameTime +
			                  FRAMES_CUSHION;
		} else {
			data->maxFrames = FRAMES_CUSHION;
			data->totalTime = 0;
		}
	}
	/*
	 * if an xing tag exists, use that!
	 */
	if (parse_xing(&xing, &ptr, &bitlen)) {
		data->foundXing = 1;
		data->muteFrame = MUTEFRAME_SKIP;

		if ((xing.flags & XING_FRAMES) && xing.frames) {
			mad_timer_t duration = data->frame.header.duration;
			mad_timer_multiply(&duration, xing.frames);
			data->totalTime = ((float)mad_timer_count(duration, MAD_UNITS_MILLISECONDS)) / 1000;
			data->maxFrames = xing.frames;
		}

		if (parse_lame(&lame, &ptr, &bitlen)) {
			if (gaplessPlaybackEnabled &&
			    data->inStream->seekable) {
				data->dropSamplesAtStart = lame.encoderDelay +
				                           DECODERDELAY;
				data->dropSamplesAtEnd = lame.encoderPadding;
			}

			/* Album gain isn't currently used.  See comment in
			 * parse_lame() for details. -- jat */
			if (replayGainInfo && !*replayGainInfo &&
			    lame.trackGain) {
				*replayGainInfo = newReplayGainInfo();
				(*replayGainInfo)->trackGain = lame.trackGain;
				(*replayGainInfo)->trackPeak = lame.peak;
			}
		}
	} 

	if (!data->maxFrames) return -1;

	if (data->maxFrames > 8 * 1024 * 1024) {
		ERROR("mp3 file header indicates too many frames: %lu",
		      data->maxFrames);
		return -1;
	}

	data->frameOffset = xmalloc(sizeof(long) * data->maxFrames);
	data->times = xmalloc(sizeof(mad_timer_t) * data->maxFrames);

	return 0;
}

static void mp3DecodeDataFinalize(mp3DecodeData * data)
{
	mad_synth_finish(&data->synth);
	mad_frame_finish(&data->frame);
	mad_stream_finish(&data->stream);

	if (data->frameOffset) free(data->frameOffset);
	if (data->times) free(data->times);
}

/* this is primarily used for getting total time for tags */
static int getMp3TotalTime(char *file)
{
	InputStream inStream;
	mp3DecodeData data;
	int ret;

	if (openInputStream(&inStream, file) < 0)
		return -1;
	initMp3DecodeData(&data, &inStream);
	if (decodeFirstFrame(&data, NULL, NULL) < 0)
		ret = -1;
	else
		ret = data.totalTime + 0.5;
	mp3DecodeDataFinalize(&data);
	closeInputStream(&inStream);

	return ret;
}

static int openMp3FromInputStream(InputStream * inStream, mp3DecodeData * data,
				  struct mpd_tag ** tag,
				  ReplayGainInfo ** replayGainInfo)
{
	initMp3DecodeData(data, inStream);
	*tag = NULL;
	if (decodeFirstFrame(data, tag, replayGainInfo) < 0) {
		mp3DecodeDataFinalize(data);
		if (tag && *tag)
			tag_free(*tag);
		return -1;
	}

	return 0;
}

static float frame_time(mp3DecodeData * data, long j)
{
	return (((float)mad_timer_count(data->times[j],
	                                MAD_UNITS_MILLISECONDS)) / 1000);
}

static void mp3Read_seek(mp3DecodeData * data)
{
	unsigned long j = 0;
	data->muteFrame = MUTEFRAME_SEEK;

	assert(pthread_equal(pthread_self(), dc.thread));
	assert(dc.action == DC_ACTION_SEEK);

	while (j < data->highestFrame && dc.seek_where > frame_time(data, j))
		j++;
	if (j < data->highestFrame) {
		dc_action_begin();
		if (seekMp3InputBuffer(data, data->frameOffset[j]) < 0)
			dc.seek_where = DC_SEEK_ERROR;
		else
			data->currentFrame = j;
		data->muteFrame = MUTEFRAME_NONE;
		dc_action_end();
	}
}

static enum mp3_action
mp3Read(mp3DecodeData * data, ReplayGainInfo ** replayGainInfo)
{
	unsigned int pcm_length, max_samples;
	unsigned int i;
	int ret;
	int skip;

	assert(pthread_equal(pthread_self(), dc.thread));

	if (data->currentFrame >= data->highestFrame) {
		mad_timer_add(&data->timer, (data->frame).header.duration);
		data->bitRate = (data->frame).header.bitrate;
		if (data->currentFrame >= data->maxFrames) {
			data->currentFrame = data->maxFrames - 1;
		} else {
			data->highestFrame++;
		}
		data->frameOffset[data->currentFrame] = data->inStream->offset;
		if (data->stream.this_frame != NULL) {
			data->frameOffset[data->currentFrame] -=
			    data->stream.bufend - data->stream.this_frame;
		} else {
			data->frameOffset[data->currentFrame] -=
			    data->stream.bufend - data->stream.buffer;
		}
		data->times[data->currentFrame] = data->timer;
	} else {
		data->timer = data->times[data->currentFrame];
	}
	data->currentFrame++;
	data->elapsedTime =
	    ((float)mad_timer_count(data->timer, MAD_UNITS_MILLISECONDS)) /
	    1000;

	switch (data->muteFrame) {
	case MUTEFRAME_SKIP:
		data->muteFrame = MUTEFRAME_NONE;
		break;
	case MUTEFRAME_SEEK:
		if (dc.seek_where <= data->elapsedTime) {
			dc_action_begin();
			assert(dc.action == DC_ACTION_SEEK);
			data->muteFrame = MUTEFRAME_NONE;
			dc_action_end();
		}
		break;
	case MUTEFRAME_NONE:
		mad_synth_frame(&data->synth, &data->frame);

		if (!data->foundFirstFrame) {
			unsigned int samplesPerFrame = (data->synth).pcm.length;
			data->dropFramesAtStart = data->dropSamplesAtStart / samplesPerFrame;
			data->dropFramesAtEnd = data->dropSamplesAtEnd / samplesPerFrame;
			data->dropSamplesAtStart = data->dropSamplesAtStart % samplesPerFrame;
			data->dropSamplesAtEnd = data->dropSamplesAtEnd % samplesPerFrame;
			data->foundFirstFrame = 1;
		}

		if (data->dropFramesAtStart > 0) {
			data->dropFramesAtStart--;
			break;
		} else if ((data->dropFramesAtEnd > 0) && 
		           (data->currentFrame == (data->maxFrames + 1 - data->dropFramesAtEnd))) {
			/* stop decoding, effectively dropping all remaining
			 * frames */
			return DECODE_BREAK;
		}

		if (data->inStream->metaTitle) {
			struct mpd_tag *tag = tag_new();
			if (data->inStream->metaName) {
				tag_add_item(tag, TAG_ITEM_NAME,
					     data->inStream->metaName);
			}
			tag_add_item(tag, TAG_ITEM_TITLE,
					data->inStream->metaTitle);
			free(data->inStream->metaTitle);
			data->inStream->metaTitle = NULL;
			metadata_pipe_send(tag, data->elapsedTime);
		}

		if (!data->decodedFirstFrame) {
			i = data->dropSamplesAtStart;
			data->decodedFirstFrame = 1;
		} else
			i = 0;

		pcm_length = data->synth.pcm.length;
		if (data->dropSamplesAtEnd &&
		    (data->currentFrame == data->maxFrames - data->dropFramesAtEnd)) {
			if (data->dropSamplesAtEnd >= pcm_length)
				pcm_length = 0;
			else
				pcm_length -= data->dropSamplesAtEnd;
		}

		max_samples = sizeof(data->outputBuffer) /
			(2 * MAD_NCHANNELS(&(data->frame).header));

		while (i < pcm_length) {
			enum dc_action action;
			unsigned int num_samples = pcm_length - i;

			if (num_samples > max_samples)
				num_samples = max_samples;
			i += num_samples;

			num_samples = dither_buffer(data->outputBuffer,
						    &data->synth, &data->dither,
						    i - num_samples, i,
						    MAD_NCHANNELS(
						        &(data->frame).header));

			action = ob_send(data->outputBuffer,
				      2 * num_samples,
				      data->elapsedTime,
				      data->bitRate / 1000,
				      replayGainInfo ? *replayGainInfo : NULL);

			if (action == DC_ACTION_STOP)
				return DECODE_BREAK;

			if (action == DC_ACTION_SEEK)
				break;
		}

		if (data->dropSamplesAtEnd &&
		    (data->currentFrame ==
		     (data->maxFrames - data->dropFramesAtEnd)))
			/* stop decoding, effectively dropping
			 * all remaining samples */
			return DECODE_BREAK;

		if (dc_seek()) {
			if (data->inStream->seekable)
				mp3Read_seek(data);
			else
				dc_action_seek_fail(DC_SEEK_ERROR);
		}
	}

	while (1) {
		skip = 0;
		while ((ret =
			decodeNextFrameHeader(data, NULL,
					      replayGainInfo)) == DECODE_CONT
		       && dc_intr()) ;
		if (ret == DECODE_BREAK || dc_intr() || dc_seek())
			break;
		else if (ret == DECODE_SKIP)
			skip = 1;
		if (data->muteFrame == MUTEFRAME_NONE) {
			while ((ret = decodeNextFrame(data)) == DECODE_CONT &&
			       !dc_intr() && dc_seek()) ;
			if (ret == DECODE_BREAK || dc_intr() || dc_seek())
				break;
		}
		if (!skip && ret == DECODE_OK)
			break;
	}

	if (dc_intr())
		return DECODE_BREAK;

	return ret;
}

static void initAudioFormatFromMp3DecodeData(mp3DecodeData * data,
					     AudioFormat * af)
{
	af->bits = 16;
	af->sampleRate = (data->frame).header.samplerate;
	af->channels = MAD_NCHANNELS(&(data->frame).header);
}

static int mp3_decode(InputStream * inStream)
{
	mp3DecodeData data;
	struct mpd_tag *tag = NULL;
	ReplayGainInfo *replayGainInfo = NULL;

	if (openMp3FromInputStream(inStream, &data, &tag, &replayGainInfo) < 0) {
		if (!dc_intr()) {
			ERROR
			    ("Input does not appear to be a mp3 bit stream.\n");
			return -1;
		}
		return 0;
	}

	initAudioFormatFromMp3DecodeData(&data, &(dc.audio_format));

	dc.total_time = data.totalTime;

	if (inStream->metaTitle) {
		if (tag)
			tag_free(tag);
		tag = tag_new();
		tag_add_item(tag, TAG_ITEM_TITLE, inStream->metaTitle);
		free(inStream->metaTitle);
		inStream->metaTitle = NULL;
		if (inStream->metaName) {
			tag_add_item(tag, TAG_ITEM_NAME, inStream->metaName);
		}
	} else if (tag) {
		if (inStream->metaName) {
			tag_clear_items_by_type(tag, TAG_ITEM_NAME);
			tag_add_item(tag, TAG_ITEM_NAME, inStream->metaName);
		}
	} else if (inStream->metaName) {
		tag = tag_new();
		if (inStream->metaName) {
			tag_add_item(tag, TAG_ITEM_NAME, inStream->metaName);
		}
	}
	if (tag)
		metadata_pipe_send(tag, 0);

	while (mp3Read(&data, &replayGainInfo) != DECODE_BREAK) ;

	if (replayGainInfo)
		freeReplayGainInfo(replayGainInfo);
	mp3DecodeDataFinalize(&data);
	return 0;
}

static struct mpd_tag *mp3_tagDup(char *file)
{
	struct mpd_tag *ret = NULL;
	int total_time;

	ret = tag_id3_load(file);

	total_time = getMp3TotalTime(file);

	if (total_time >= 0) {
		if (!ret)
			ret = tag_new();
		ret->time = total_time;
	} else {
		DEBUG("mp3_tagDup: Failed to get total song time from: %s\n",
		      file);
	}

	return ret;
}

static const char *mp3_suffixes[] = { "mp3", "mp2", NULL };
static const char *mp3_mimeTypes[] = { "audio/mpeg", NULL };

InputPlugin mp3Plugin = {
	"mp3",
	mp3_plugin_init,
	NULL,
	NULL,
	mp3_decode,
	NULL,
	mp3_tagDup,
	INPUT_PLUGIN_STREAM_FILE | INPUT_PLUGIN_STREAM_URL,
	mp3_suffixes,
	mp3_mimeTypes
};
#else

InputPlugin mp3Plugin;

#endif /* HAVE_MAD */