PageRenderTime 133ms CodeModel.GetById 3ms app.highlight 119ms RepoModel.GetById 1ms app.codeStats 0ms

/decoders/audio/mp2.d

http://github.com/wilkie/djehuty
D | 1722 lines | 1145 code | 324 blank | 253 comment | 270 complexity | e2021bad8e7ca63a0359f1d085053f61 MD5 | raw file
   1/*
   2 * mp2.d
   3 *
   4 * This file implements the MP2 audio standard.
   5 *
   6 * Author: Dave Wilkinson
   7 *
   8 */
   9
  10module decoders.audio.mp2;
  11
  12import decoders.audio.decoder;
  13import decoders.decoder;
  14
  15import core.stream;
  16import core.time;
  17import core.string;
  18import core.definitions;
  19
  20import io.wavelet;
  21import io.audio;
  22import io.console;
  23
  24// initialize the array to zero
  25typedef double zerodouble = 0.0;
  26
  27// 2
  28template FromBigEndian(uint input) {
  29	version (LittleEndian) {
  30		const auto FromBigEndian = (input >> 24) | ((input >> 8) & 0x0000FF00) | ((input << 8) & 0x00FF0000) | ((input << 24) & 0xFF000000);
  31	}
  32	else {
  33		const auto FromBigEndian = input;
  34	}
  35}
  36
  37template FromBigEndianBitIndex32(uint index) {
  38	version (LittleEndian) {
  39		const auto FromBigEndianBitIndex32 = ((3 - cast(uint)(index/8)) * 8) + (index % 8);
  40	}
  41	else {
  42		const auto FromBigEndianBitIndex32 = index;
  43	}
  44}
  45
  46private {
  47	// for the classes of quantization table
  48	struct QuantizationClass {
  49		uint numberOfSteps;
  50		double C;
  51		double D;
  52		bool grouping;
  53		uint samplesPerCodeword;
  54		uint bitsPerCodeword;
  55	}
  56
  57	static const uint bitMasks[] = [
  58		0,
  59		1 << 0,
  60		1 << 1,
  61		1 << 2,
  62		1 << 3,
  63		1 << 4,
  64		1 << 5,
  65		1 << 6,
  66		1 << 7,
  67		1 << 8,
  68		1 << 9,
  69		1 << 10,
  70		1 << 11,
  71		1 << 12,
  72		1 << 13,
  73		1 << 14,
  74		1 << 15,
  75		1 << 16,
  76		1 << 17,
  77		1 << 18,
  78		1 << 19,
  79		1 << 20,
  80		1 << 21,
  81		1 << 22,
  82		1 << 23,
  83		1 << 24,
  84		1 << 25,
  85		1 << 26,
  86		1 << 27,
  87		1 << 28,
  88		1 << 29,
  89		1 << 30,
  90		1 << 31,
  91	];
  92
  93	static const uint bitFills[] = [
  94		0,
  95		(1 << 0) - 1,
  96		(1 << 1) - 1,
  97		(1 << 2) - 1,
  98		(1 << 3) - 1,
  99		(1 << 4) - 1,
 100		(1 << 5) - 1,
 101		(1 << 6) - 1,
 102		(1 << 7) - 1,
 103		(1 << 8) - 1,
 104		(1 << 9) - 1,
 105		(1 << 10) - 1,
 106		(1 << 11) - 1,
 107		(1 << 12) - 1,
 108		(1 << 13) - 1,
 109		(1 << 14) - 1,
 110		(1 << 15) - 1,
 111		(1 << 16) - 1,
 112		(1 << 17) - 1,
 113		(1 << 18) - 1,
 114		(1 << 19) - 1,
 115		(1 << 20) - 1,
 116		(1 << 21) - 1,
 117		(1 << 22) - 1,
 118		(1 << 23) - 1,
 119		(1 << 24) - 1,
 120		(1 << 25) - 1,
 121		(1 << 26) - 1,
 122		(1 << 27) - 1,
 123		(1 << 28) - 1,
 124		(1 << 29) - 1,
 125		(1 << 30) - 1,
 126		(1 << 31) - 1,
 127	];
 128
 129	/+
 130		/* 0 */		{ 3, 1.33333333333, 0.50000000000,  true, 3, 5 },
 131		/* 1 */		{ 5, 1.60000000000, 0.50000000000,  true, 3, 7 },
 132		/* 2 */		{ 7, 1.14285714286, 0.25000000000, false, 1, 3 },
 133		/* 3 */		{ 9, 1.77777777777, 0.50000000000,  true, 3, 10},
 134		/* 4 */		{15, 1.06666666666, 0.12500000000, false, 1, 4 },
 135		/* 5 */		{31, 1.03225806452, 0.06250000000, false, 1, 5 },
 136		/* 6 */		{63, 1.01587301587, 0.03125000000, false, 1, 6 },
 137		/* 7 */		{127, 1.00787401575, 0.01562500000, false, 1, 7 },
 138		/* 8 */		{255, 1.00392156863, 0.00781250000, false, 1, 8 },
 139		/* 9 */		{511, 1.00195694716, 0.00390625000, false, 1, 9 },
 140		/* 10 */	{1023, 1.00097751711, 0.00195312500, false, 1, 10 },
 141		/* 11 */	{2047, 1.00048851979, 0.00097656250, false, 1, 11 },
 142		/* 12 */	{4095, 1.00024420024, 0.00048828125, false, 1, 12 },
 143		/* 13 */	{8191, 1.00012208522, 0.00024414063, false, 1, 13 },
 144		/* 14 */	{16383, 1.00006103888, 0.00012207031, false, 1, 14 },
 145		/* 15 */	{32767, 1.00003051851, 0.00006103516, false, 1, 15 },
 146		/* 16 */	{65535, 1.00001525902, 0.00003051758, false, 1, 16 },
 147		/* 17 */	{ 0, 1.33333333333, 0.50000000000,  true, 3, 5 },
 148
 149	struct QuantizationClass
 150	{
 151		uint numberOfSteps;
 152		double C;
 153		double D;
 154		bool grouping;
 155		uint samplesPerCodeword;
 156		uint bitsPerCodeword;
 157	}
 158
 159	+/
 160
 161	// GDC doesn't like a static array of the QuantizationClass struct
 162	// I dunno why
 163
 164	static const QuantizationClass quantizationClass0 = { 3, 1.33333333333, 0.50000000000,  true, 3, 5 };
 165	static const QuantizationClass quantizationClass1 = { 5, 1.60000000000, 0.50000000000,  true, 3, 7 };
 166	static const QuantizationClass quantizationClass2 = { 7, 1.14285714286, 0.25000000000, false, 1, 3 };
 167	static const QuantizationClass quantizationClass3 = { 9, 1.77777777777, 0.50000000000,  true, 3, 10};
 168	static const QuantizationClass quantizationClass4 = {15, 1.06666666666, 0.12500000000, false, 1, 4 };
 169	static const QuantizationClass quantizationClass5 = {31, 1.03225806452, 0.06250000000, false, 1, 5 };
 170	static const QuantizationClass quantizationClass6 = {63, 1.01587301587, 0.03125000000, false, 1, 6 };
 171	static const QuantizationClass quantizationClass7 = {127, 1.00787401575, 0.01562500000, false, 1, 7 };
 172	static const QuantizationClass quantizationClass8 = {255, 1.00392156863, 0.00781250000, false, 1, 8 };
 173	static const QuantizationClass quantizationClass9 = {511, 1.00195694716, 0.00390625000, false, 1, 9 };
 174	static const QuantizationClass quantizationClass10 = {1023, 1.00097751711, 0.00195312500, false, 1, 10 };
 175	static const QuantizationClass quantizationClass11 = {2047, 1.00048851979, 0.00097656250, false, 1, 11 };
 176	static const QuantizationClass quantizationClass12 = {4095, 1.00024420024, 0.00048828125, false, 1, 12 };
 177	static const QuantizationClass quantizationClass13 = {8191, 1.00012208522, 0.00024414063, false, 1, 13 };
 178	static const QuantizationClass quantizationClass14 = {16383, 1.00006103888, 0.00012207031, false, 1, 14 };
 179	static const QuantizationClass quantizationClass15 = {32767, 1.00003051851, 0.00006103516, false, 1, 15 };
 180	static const QuantizationClass quantizationClass16 = {65535, 1.00001525902, 0.00003051758, false, 1, 16 };
 181	static const QuantizationClass quantizationClass17 = { 0, 1.33333333333, 0.50000000000,  false, 3, 5 };
 182
 183
 184	// A and B
 185
 186	// sb0 .. 2 (4 bits)
 187	const QuantizationClass allocationToQuantA1[] = [ quantizationClass17, quantizationClass0, quantizationClass2, quantizationClass4,
 188					quantizationClass5, quantizationClass6, quantizationClass7, quantizationClass8, quantizationClass9,
 189					quantizationClass10, quantizationClass11, quantizationClass12, quantizationClass13, quantizationClass14,
 190					quantizationClass15, quantizationClass16 ];
 191
 192	// sb3 .. 10 (4 bits)
 193	const QuantizationClass allocationToQuantA2[] = [ quantizationClass17, quantizationClass0, quantizationClass1, quantizationClass2, quantizationClass3, quantizationClass4,
 194					quantizationClass5, quantizationClass6, quantizationClass7, quantizationClass8, quantizationClass9,
 195					quantizationClass10, quantizationClass11, quantizationClass12, quantizationClass13, quantizationClass16 ];
 196	// sb11 .. 22 (3 bits)
 197	const QuantizationClass allocationToQuantA3[] = [ quantizationClass17, quantizationClass0, quantizationClass1, quantizationClass2, quantizationClass3, quantizationClass4,
 198					quantizationClass5, quantizationClass6, quantizationClass7, quantizationClass8, quantizationClass9,
 199					quantizationClass10, quantizationClass11, quantizationClass12, quantizationClass13, quantizationClass16 ];
 200	// sb23 .. sb26 or sb29 (2 bits)
 201	const QuantizationClass allocationToQuantA4[] = [ quantizationClass17, quantizationClass0, quantizationClass1, quantizationClass16 ];
 202
 203	// sblimit = 27 (A)
 204	// sblimit = 30 (B)
 205
 206	// C and D
 207
 208	// sb0 .. sb1 (4 bits)
 209	const QuantizationClass allocationToQuantC1[] = [ quantizationClass17, quantizationClass0, quantizationClass1, quantizationClass3,
 210					quantizationClass4,
 211					quantizationClass5, quantizationClass6, quantizationClass7, quantizationClass8, quantizationClass9,
 212					quantizationClass10, quantizationClass11, quantizationClass12, quantizationClass13, quantizationClass14,
 213					quantizationClass15 ];
 214
 215	// sb2 .. sb7 or sb11 (3 bits)
 216	//const uint allocationTableC2[] = [ 0, 3, 5, 9, 15, 31, 63, 127 ]; // can refer to above table
 217	// sblimit = 8 (C)
 218	// sblimit = 12 (D)
 219
 220
 221	// Scalefactors
 222	const double scaleFactors[] = [ 2.00000000000000,	1.58740105196820,
 223									1.25992104989487,	1.00000000000000,
 224									0.79370052598410,	0.62996052494744,
 225									0.50000000000000,	0.39685026299205,
 226									0.31498026247372,	0.25000000000000,
 227									0.19842513149602,	0.15749013123686,
 228									0.12500000000000,	0.09921256574801,
 229									0.07874506561843,	0.06250000000000,
 230									0.04960628287401,	0.03937253280921,
 231									0.03125000000000,	0.02480314143700,
 232									0.01968626640461,	0.01562500000000,
 233									0.01240157071850,	0.00984313320230,
 234									0.00781250000000,	0.00620078535925,
 235									0.00492156660115,	0.00390625000000,
 236									0.00310039267963,	0.00246078330058,
 237									0.00195312500000,	0.00155019633981,
 238									0.00123039165029,	0.00097656250000,
 239									0.00077509816991,	0.00061519582514,
 240									0.00048828125000,	0.00038754908495,
 241									0.00030759791257,	0.00024414062500,
 242									0.00019377454248,	0.00015379895629,
 243									0.00012207031250,	0.00009688727124,
 244									0.00007689947814,	0.00006103515625,
 245									0.00004844363562,	0.00003844973907,
 246									0.00003051757813,	0.00002422181781,
 247									0.00001922486954,	0.00001525878906,
 248									0.00001211090890,	0.00000961243477,
 249									0.00000762939453,	0.00000605545445,
 250									0.00000480621738,	0.00000381469727,
 251									0.00000302772723,	0.00000240310869,
 252									0.00000190734863,	0.00000151386361,
 253									0.00000120155435,	1e-20	];
 254
 255	const auto MPEG_SYNC_BITS 		= FromBigEndian!(0xFFF00000);
 256	const auto MPEG_ID_BIT    		= FromBigEndian!(0x00080000);
 257	const auto MPEG_LAYER			= FromBigEndian!(0x00060000);
 258	const auto MPEG_LAYER_SHIFT				= FromBigEndianBitIndex32!(17);
 259	const auto MPEG_PROTECTION_BIT	= FromBigEndian!(0x00010000);
 260	const auto MPEG_BITRATE_INDEX	= FromBigEndian!(0x0000F000);
 261	const auto MPEG_BITRATE_INDEX_SHIFT 	= FromBigEndianBitIndex32!(12);
 262	const auto MPEG_SAMPLING_FREQ	= FromBigEndian!(0x00000C00);
 263	const auto MPEG_SAMPLING_FREQ_SHIFT 	= FromBigEndianBitIndex32!(10);
 264	const auto MPEG_PADDING_BIT		= FromBigEndian!(0x00000200);
 265	const auto MPEG_PRIVATE_BIT		= FromBigEndian!(0x00000100);
 266	const auto MPEG_MODE			= FromBigEndian!(0x000000C0);
 267	const auto MPEG_MODE_SHIFT				= FromBigEndianBitIndex32!(6);
 268	const auto MPEG_MODE_EXTENSION	= FromBigEndian!(0x00000030);
 269	const auto MPEG_MODE_EXTENSION_SHIFT 	= FromBigEndianBitIndex32!(4);
 270	const auto MPEG_COPYRIGHT		= FromBigEndian!(0x00000008);
 271	const auto MPEG_ORIGINAL		= FromBigEndian!(0x00000004);
 272	const auto MPEG_EMPHASIS		= FromBigEndian!(0x00000003);
 273	const auto MPEG_EMPHASIS_SHIFT = 0;
 274
 275	// modes
 276
 277	const auto MPEG_MODE_STEREO			= 0;
 278	const auto MPEG_MODE_JOINT_STEREO	= 1;
 279	const auto MPEG_MODE_DUAL_CHANNEL	= 2;
 280	const auto MPEG_MODE_SINGLE_CHANNEL = 3;
 281
 282	// layer 1
 283	//const auto bitRates[] = [ 0, 32, 64, 96, 128, 160, 192, 224, 256, 288, 320, 352, 384, 416, 448 ];
 284
 285	// layer 2
 286	const uint[] bitRates = [ 0, 32, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384, 0 ]; // the first entry is the 'free' bitrate
 287	const double[] samplingFrequencies = [ 44.1, 48.0, 32.0, 1.0 ]; // the final entry is reserved, but set to 1.0 due to being used in division
 288
 289	const uint byteMasks[9][] = [
 290		[0x00, 0x00, 0x00, 0x00, 0x0, 0x0, 0x0, 0x0],		// 0 bit
 291		[0x80, 0x40, 0x20, 0x10, 0x8, 0x4, 0x2, 0x1],		// 1 bit
 292		[0xC0, 0x60, 0x30, 0x18, 0xC, 0x6, 0x3, 0x1],		// 2 bits
 293		[0xE0, 0x70, 0x38, 0x1C, 0xE, 0x7, 0x3, 0x1],		// 3 bits
 294		[0xF0, 0x78, 0x3C, 0x1E, 0xF, 0x7, 0x3, 0x1],		// 4 bits
 295		[0xF8, 0x7C, 0x3E, 0x1F, 0xF, 0x7, 0x3, 0x1],		// 5 bits
 296		[0xFC, 0x7E, 0x3F, 0x1F, 0xF, 0x7, 0x3, 0x1],		// 6 bits
 297		[0xFE, 0x7F, 0x3F, 0x1F, 0xF, 0x7, 0x3, 0x1],		// 7 bits
 298		[0xFF, 0x7F, 0x3F, 0x1F, 0xF, 0x7, 0x3, 0x1]		// 8 bits
 299	];
 300
 301	struct MP2HeaderInformation {
 302		uint ID;
 303		uint Layer;
 304		uint Protected;
 305		uint BitrateIndex;
 306		uint SamplingFrequency;
 307		uint Padding;
 308		uint Private;
 309		uint Mode;
 310		uint ModeExtension;
 311		uint Copyright;
 312		uint Original;
 313		uint Emphasis;
 314	}
 315
 316	const auto MP2_STATE_INIT 						= 0;
 317	const auto MP2_READ_HEADER						= 1;
 318	const auto MP2_AMBIGUOUS_SYNC					= 2;
 319	const auto MP2_READ_CRC							= 3;
 320	const auto MP2_READ_AUDIO_DATA					= 4;
 321
 322	const auto MP2_BUFFER_AUDIO						= 5;
 323
 324	const auto MP2_READ_AUDIO_DATA_DUAL_CHANNEL 	= 7;
 325	const auto MP2_READ_AUDIO_DATA_SINGLE_CHANNEL	= 8;
 326	const auto MP2_READ_AUDIO_DATA_JOINT_STEREO		= 9;
 327
 328
 329
 330
 331	// number of blocks (of 1152 samples) to buffer
 332	const auto NUM_BLOCKS = 80;
 333}
 334
 335
 336
 337// Section: Codecs/Audio
 338
 339// Description: This is the MPEG Layer 2 audio codec.
 340class MP2Decoder : AudioDecoder {
 341	override string name() {
 342		return "MPEG Layer 2";
 343	}
 344
 345	override string extension() {
 346		return "mp2";
 347	}
 348
 349	StreamData decode(Stream stream, Wavelet toBuffer, ref AudioInfo wi) {
 350		for (;;) {
 351			switch (decoderState) {
 352				case MP2_STATE_INIT:
 353					//initial stuff
 354
 355					decoderState = MP2_BUFFER_AUDIO;
 356
 357					posOfFirstFrame = cast(long)stream.position;
 358
 359					SeekPointer sptr = {Time.init, cast(ulong)posOfFirstFrame, null};
 360					seekLUT ~= sptr;
 361
 362					// *** fall through *** //
 363
 364					// attempts to find the 12-16 sync bits
 365					// if it is unsure of the filetype, it will
 366					// look for only 12 bits (b 1111 1111 1111)
 367					// if it knows its layer it will search for
 368					// the sync bits plus that part of the header
 369
 370					// entry for getting another audio buffer
 371				case MP2_BUFFER_AUDIO:
 372
 373					samplesLeft = 1152 * NUM_BLOCKS;
 374
 375					bufferSize = samplesLeft * 2;
 376
 377					if (isSeek && !isSeekBack && (toSeek < (curTime + bufferTime))) {
 378						// seeking
 379						Console.putln("seek no more");
 380						isSeek = false;
 381						return StreamData.Accepted;
 382					}
 383					else if (isSeek && isSeekBack && (toSeek >= curTime)) {
 384						// seeking
 385						Console.putln("seek no more");
 386						isSeek = false;
 387						return StreamData.Accepted;
 388					}
 389
 390					decoderState = MP2_READ_HEADER;
 391
 392					// *** fall through *** //
 393
 394				case MP2_READ_HEADER:
 395
 396					if (!stream.read(mpeg_header)) {
 397						if (accepted) {
 398							return StreamData.Accepted;
 399						}
 400						return StreamData.Required;
 401					}
 402
 403					decoderState = MP2_AMBIGUOUS_SYNC;
 404
 405
 406					// *** fall through *** //
 407
 408					// look at the sync bits of the header
 409					// if they are not correct, shift the header
 410					// 8 bits and read another byte until the
 411					// sync bits match
 412
 413				case MP2_AMBIGUOUS_SYNC:
 414
 415     				if ((mpeg_header & FromBigEndian!(0xFFFFFF00)) == FromBigEndian!(0x49443300)) {
 416
 417     					if (id3.signature[0] != 0x49) {
 418							if (!stream.read((cast(ubyte*)&id3) + 4, id3.sizeof - 4)) {
 419								return StreamData.Required;
 420							}
 421
 422							id3.signature[0] = 0x49;
 423
 424							id3.ver[0] = cast(ubyte)(mpeg_header & 0xFF);
 425
 426							// skip the ID3 section
 427							foreach(b; id3.len) {
 428								id3length <<= 7;
 429								b &= 0x7f;
 430								id3length |= b;
 431							}
 432
 433							//Console.putln("id3 length: ", new String("%x", id3length));
 434						}
 435
 436						if (!stream.skip(id3length)) {
 437							return StreamData.Required;
 438						}
 439
 440						decoderState = MP2_READ_HEADER;
 441						continue;
 442					}
 443
 444					if ((mpeg_header & MPEG_SYNC_BITS) == MPEG_SYNC_BITS) {
 445						// sync bits found
 446						//writeln("sync bits found ", stream.getPosition() - 4);
 447
 448						// pull apart header
 449
 450						// the header looks like this:
 451
 452						// SYNCWORD			12 bits
 453						// ID				1 bit
 454						// LAYER			2 bits
 455						// PROTECTION BIT	1 bit
 456						// BITRATE INDEX	4 bits
 457						// SAMPLING FREQ	2 bits
 458						// PADDING BIT		1 bit
 459						// PRIVATE BIT		1 bit
 460						// MODE				2 bits
 461						// MODE EXTENSION	2 bits
 462						// COPYRIGHT		1 bit
 463						// ORIGINAL/HOME	1 bit
 464						// EMPHASIS			2 bits
 465
 466						header.ID = (mpeg_header & MPEG_ID_BIT ? 1 : 0);
 467						header.Layer = (mpeg_header & MPEG_LAYER) >> MPEG_LAYER_SHIFT;
 468
 469						if (header.Layer != 2) {
 470							return StreamData.Invalid;
 471						}
 472
 473						header.Protected = (mpeg_header & MPEG_PROTECTION_BIT ? 1 : 0);
 474						header.BitrateIndex = (mpeg_header & MPEG_BITRATE_INDEX) >> MPEG_BITRATE_INDEX_SHIFT;
 475						header.SamplingFrequency = (mpeg_header & MPEG_SAMPLING_FREQ) >> MPEG_SAMPLING_FREQ_SHIFT;
 476						header.Padding = (mpeg_header & MPEG_PADDING_BIT ? 1 : 0);
 477						header.Private = (mpeg_header & MPEG_PRIVATE_BIT ? 1 : 0);
 478						header.Mode = (mpeg_header & MPEG_MODE) >> MPEG_MODE_SHIFT;
 479						header.ModeExtension = (mpeg_header & MPEG_MODE_EXTENSION) >> MPEG_MODE_EXTENSION_SHIFT;
 480						header.Copyright = (mpeg_header & MPEG_COPYRIGHT ? 1 : 0);
 481						header.Original = (mpeg_header & MPEG_ORIGINAL ? 1 : 0);
 482						header.Emphasis = (mpeg_header & MPEG_EMPHASIS) >> MPEG_EMPHASIS_SHIFT;
 483
 484						Console.putln("Header: ", mpeg_header & MPEG_SYNC_BITS, "\n",
 485								"ID: ", header.ID, "\n",
 486								"Layer: ", header.Layer, "\n",
 487								"Protected: ", header.Protected, "\n",
 488								"BitrateIndex: ", header.BitrateIndex, "\n",
 489								"SamplingFrequency: ", header.SamplingFrequency, "\n",
 490								"Padding: ", header.Padding, "\n",
 491								"Private: ", header.Private, "\n",
 492								"Mode: ", header.Mode, "\n",
 493								"ModeExtension: ", header.ModeExtension, "\n",
 494								"Copyright: ", header.Copyright, "\n",
 495								"Original: ", header.Original, "\n",
 496								"Emphasis: ", header.Emphasis);
 497
 498
 499						// Calculate the length of the Audio Data
 500						audioDataLength = cast(uint)(144 * (cast(double)bitRates[header.BitrateIndex] / cast(double)samplingFrequencies[header.SamplingFrequency]));
 501						if (header.Padding) { audioDataLength++; }
 502
 503						// subtract the size of the header
 504						audioDataLength -= 4;
 505
 506						// allocate the buffer
 507						audioData = new ubyte[audioDataLength];
 508
 509					//	writeln("Audio Data Length: ", audioDataLength);
 510					//	writeln("curByte: ", audioData.ptr);
 511
 512
 513						// set the format of the wave buffer
 514
 515						if (header.SamplingFrequency == 0) {
 516							// 44.1 kHz
 517							wf.samplesPerSecond = 44100;
 518						}
 519						else if (header.SamplingFrequency == 1) {
 520							// 48 kHz
 521							wf.samplesPerSecond = 48000;
 522						}
 523						else {
 524							// 32 kHz
 525							wf.samplesPerSecond = 32000;
 526						}
 527
 528						wf.compressionType = 1;
 529
 530						switch(header.Mode) {
 531							case MPEG_MODE_STEREO:
 532							case MPEG_MODE_DUAL_CHANNEL:
 533								wf.numChannels = 2;
 534								break;
 535
 536							case MPEG_MODE_SINGLE_CHANNEL:
 537								wf.numChannels = 1;
 538								break;
 539
 540							case MPEG_MODE_JOINT_STEREO:
 541								wf.numChannels = 2;
 542								break;
 543
 544							default: // impossible!
 545								return StreamData.Invalid;
 546						}
 547
 548
 549						wf.averageBytesPerSecond = wf.samplesPerSecond * 2 * wf.numChannels;
 550						wf.blockAlign = 2 * wf.numChannels;
 551						wf.bitsPerSample = 16;
 552
 553						// set the wavelet's audio format
 554						if (toBuffer !is null) {
 555							toBuffer.setAudioFormat(wf);
 556							bufferTime = toBuffer.time;
 557						}
 558
 559						if (header.Protected == 0) {
 560							decoderState = MP2_READ_CRC;
 561						}
 562						else {
 563							decoderState = MP2_READ_AUDIO_DATA;
 564						}
 565
 566						if (!accepted) {
 567							if (toBuffer !is null) {
 568								if (toBuffer.length() != bufferSize) {
 569									Console.putln("resize ", bufferSize, " from ", toBuffer.length());
 570									toBuffer.resize(bufferSize);
 571								}
 572								toBuffer.rewind();
 573							}
 574
 575							if (toBuffer is null && isSeek == false) {
 576								return StreamData.Accepted;
 577							}
 578						}
 579						
 580						accepted = true;
 581
 582						continue;
 583					}
 584					else {
 585//						Console.putln("cur test ", mpeg_header & MPEG_SYNC_BITS, " @ ", stream.position - 4);
 586						ubyte curByte;
 587						if (!stream.read(curByte)) {
 588							return StreamData.Required;
 589						}
 590
 591						mpeg_header <<= 8;
 592						mpeg_header |= (cast(uint)curByte);
 593					}
 594
 595					continue;
 596
 597				case MP2_READ_CRC:
 598
 599					if (!stream.read(crc)) {
 600						return StreamData.Required;
 601					}
 602
 603					decoderState = MP2_READ_AUDIO_DATA;
 604
 605
 606					// *** falls through *** //
 607
 608				case MP2_READ_AUDIO_DATA:
 609
 610					// read in the audio data to a buffer
 611					// then use that buffer to gather the useful information
 612
 613					if (isSeek) {
 614						// skip over audio data
 615						if (!stream.skip(audioData.length)) {
 616							return StreamData.Required;
 617						}
 618
 619						switch(header.Mode) {
 620							case MPEG_MODE_STEREO:
 621							case MPEG_MODE_DUAL_CHANNEL:
 622								channels = 2;
 623								break;
 624
 625							case MPEG_MODE_SINGLE_CHANNEL:
 626								channels = 1;
 627								break;
 628
 629							case MPEG_MODE_JOINT_STEREO:
 630								break;
 631
 632							default: // impossible!
 633								return StreamData.Invalid;
 634						}
 635
 636						// do not decode
 637						samplesLeft -= (12*32*3*channels);
 638
 639						if (samplesLeft <= 0) {
 640							decoderState = MP2_BUFFER_AUDIO;
 641							curTime += bufferTime;
 642							curTime.toString();
 643						}
 644						else {
 645							decoderState = MP2_READ_HEADER;
 646						}
 647						continue;
 648					}
 649
 650					if (!stream.read(audioData)) {
 651						return StreamData.Required;
 652					}
 653//					toBuffer.setAudioFormat(wf);
 654
 655					//writeln("curByte: ", audioData.length);
 656					curByte = audioData.ptr;
 657					curPos = 0;
 658
 659					switch(header.Mode) {
 660						case MPEG_MODE_STEREO:
 661						case MPEG_MODE_DUAL_CHANNEL:
 662							channels = 2;
 663							decoderState = MP2_READ_AUDIO_DATA_SINGLE_CHANNEL;
 664							break;
 665
 666						case MPEG_MODE_SINGLE_CHANNEL:
 667							channels = 1;
 668							decoderState = MP2_READ_AUDIO_DATA_SINGLE_CHANNEL;
 669							break;
 670
 671						case MPEG_MODE_JOINT_STEREO:
 672							decoderState = MP2_READ_AUDIO_DATA_JOINT_STEREO;
 673							break;
 674
 675						default: // impossible!
 676							return StreamData.Invalid;
 677					}
 678
 679					continue;
 680
 681				case MP2_READ_AUDIO_DATA_SINGLE_CHANNEL:
 682
 683					// read in allocation bits
 684
 685					// Determine which allocation table to use
 686					//   depending on the sample frequency and bitrate
 687
 688					// Table A:
 689					//    48 kHz 	: 56, 64, 80, 96, 112, 128, 160, 192 kbits/s
 690					//    44.1		: 56, 64, 80
 691					//    32		: 56, 64, 80
 692
 693					// Table B:
 694					//    48		: N/A
 695					//    44.1		: 96, 112, 128, 160, 192
 696					//    32		: 96, 112, 128, 160, 192
 697
 698					// Table C:
 699					//    48		: 32, 48
 700					//    44.1		: 32, 48
 701					//    32		: N/A
 702
 703					// Table D:
 704					//    48		: N/A
 705					//    44.1		: N/A
 706					//    32		: 32, 48
 707
 708					uint tableType;
 709					uint sblimit;
 710
 711					if (header.SamplingFrequency == 0) {
 712						// 44.1 kHz
 713
 714						if (header.BitrateIndex >= 3 && header.BitrateIndex <= 5) {
 715							// TABLE A
 716							tableType = 0;
 717							sblimit = 27;
 718						}
 719						else if (header.BitrateIndex >= 6) {
 720							// TABLE B
 721							tableType = 0;
 722							sblimit = 30;
 723						}
 724						else {
 725							// TABLE C
 726							tableType = 1;
 727							sblimit = 8;
 728						}
 729					}
 730					else if (header.SamplingFrequency == 1) {
 731						// 48 kHz
 732
 733						if (header.BitrateIndex >= 3) {
 734							// TABLE A
 735							tableType = 0;
 736							sblimit = 27;
 737						}
 738						else {
 739							// TABLE C
 740							tableType = 1;
 741							sblimit = 8;
 742						}
 743					}
 744					else {
 745						// 32 kHz
 746
 747						if (header.BitrateIndex >= 3 && header.BitrateIndex <= 5) {
 748							// TABLE A
 749							tableType = 0;
 750							sblimit = 27;
 751						}
 752						else if (header.BitrateIndex >= 6) {
 753							// TABLE B
 754							tableType = 0;
 755							sblimit = 30;
 756						}
 757						else {
 758							// TABLE D
 759							tableType = 1;
 760							sblimit = 12;
 761						}
 762					}
 763
 764					uint sb, channel;
 765
 766					if (tableType == 0) {
 767						// TABLE A/B
 768
 769						// length: 4 bits
 770						uint idx;
 771
 772						for ( ; sb < 3; sb++) {
 773							for (channel=0; channel<channels; channel++) {
 774								idx = readBits(4);
 775								allocClass[channel][sb] = cast(QuantizationClass*)&allocationToQuantA1[idx];
 776							}
 777						}
 778
 779						for ( ; sb < 11; sb++) {
 780							for (channel=0; channel<channels; channel++) {
 781								idx = readBits(4);
 782								allocClass[channel][sb] = cast(QuantizationClass*)&allocationToQuantA2[idx];
 783							}
 784						}
 785
 786						for ( ; sb < 23; sb++) {
 787							for (channel=0; channel<channels; channel++) {
 788								idx = readBits(3);
 789								allocClass[channel][sb] = cast(QuantizationClass*)&allocationToQuantA3[idx];
 790							}
 791						}
 792
 793						for ( ; sb < sblimit; sb++) {
 794							for (channel=0; channel<channels; channel++)
 795							{
 796								idx = readBits(2);
 797								allocClass[channel][sb] = cast(QuantizationClass*)&allocationToQuantA4[idx];
 798							}
 799						}
 800					}
 801					else {
 802						// TABLE C/D
 803
 804						uint idx;
 805
 806						for ( ; sb < 2; sb++) {
 807							for (channel=0; channel<channels; channel++) {
 808								idx = readBits(4);
 809								allocClass[channel][sb] = cast(QuantizationClass*)&allocationToQuantC1[idx];
 810							}
 811						}
 812
 813						for ( ; sb < sblimit; sb++) {
 814							for (channel=0; channel<channels; channel++) {
 815								idx = readBits(3);
 816								allocClass[channel][sb] = cast(QuantizationClass*)&allocationToQuantC1[idx];
 817							}
 818						}
 819					}
 820
 821					// Read Scalefactor Selection Information
 822
 823					for (sb=0; sb<sblimit; sb++) {
 824						for (channel=0; channel<channels; channel++) {
 825							if (allocClass[channel][sb].numberOfSteps!=0) {
 826								scfsi[channel][sb] = readBits(2);
 827							}
 828						}
 829					}
 830
 831					// Read Scalefactor Indices
 832
 833					for (sb=0; sb<sblimit; sb++) {
 834						for (channel=0; channel<channels; channel++) {
 835							if (allocClass[channel][sb].numberOfSteps!=0) {
 836								if (scfsi[channel][sb]==0) {
 837									scalefactor[channel][0][sb] = readBits(6); 	// 6	bits	uimsbf
 838									scalefactor[channel][1][sb] = readBits(6);	// 6	bits	uimsbf
 839									scalefactor[channel][2][sb] = readBits(6);  // 6	bits	uimsbf
 840								}
 841								else if ((scfsi[channel][sb]==1) || (scfsi[channel][sb]==3)) {
 842									scalefactor[channel][0][sb] = readBits(6); 	// 6	bits	uimsbf
 843									scalefactor[channel][2][sb] = readBits(6);	// 6	bits	uimsbf
 844
 845									// scale factors are paired differently:
 846									if (scfsi[channel][sb] == 1) {
 847										scalefactor[channel][1][sb] = scalefactor[channel][0][sb];
 848									}
 849									else {
 850										scalefactor[channel][1][sb] = scalefactor[channel][2][sb];
 851									}
 852								}
 853								else if (scfsi[channel][sb]==2) {
 854									scalefactor[channel][0][sb] = readBits(6);  // 6	bits	uimsbf
 855									scalefactor[channel][1][sb] = scalefactor[channel][0][sb];
 856									scalefactor[channel][2][sb] = scalefactor[channel][0][sb];
 857								}
 858							}
 859							else {
 860								scalefactor[channel][0][sb] = 63;
 861								scalefactor[channel][1][sb] = 63;
 862								scalefactor[channel][2][sb] = 63;
 863							}
 864						}
 865					}
 866
 867					uint gr, s;
 868
 869					for (gr=0; gr<12; gr++) {
 870						for (sb=0; sb<sblimit; sb++) {
 871							for (channel=0; channel<channels; channel++) {
 872								if (allocClass[channel][sb].numberOfSteps!=0) {
 873									if (allocClass[channel][sb].grouping) {
 874										samplecode = readBits(allocClass[channel][sb].bitsPerCodeword);	// 5..10	bits	uimsbf
 875											//writeln(samplecode[sb][gr], " bit");
 876										assert((allocClass[channel][sb].bitsPerCodeword > 4) && (allocClass[channel][sb].bitsPerCodeword < 11));
 877
 878										// ungroup
 879
 880										for (s=0; s<3; s++) {
 881											sample[channel][s][sb] = samplecode % allocClass[channel][sb].numberOfSteps;
 882											samplecode /= allocClass[channel][sb].numberOfSteps;
 883
 884											// requantize
 885										}
 886									}
 887									else {
 888										for (s=0; s<3; s++) {
 889											sample[channel][s][sb] = readBits(allocClass[channel][sb].bitsPerCodeword); // 2..16	bits	uimsbf
 890												//writeln(sample[sb][s], " bit");
 891											assert((allocClass[channel][sb].bitsPerCodeword > 1) && (allocClass[channel][sb].bitsPerCodeword < 17));
 892
 893										}
 894									}
 895								}
 896								else {
 897									sample[channel][0][sb] = 0;
 898									sample[channel][1][sb] = 0;
 899									sample[channel][2][sb] = 0;
 900								}
 901							}
 902						}
 903
 904						for ( ; sb<32; sb++) {
 905							for (s=0; s<3; s++) {
 906								quantSample[0][s][sb] = 0.0;
 907								quantSample[1][s][sb] = 0.0;
 908							}
 909						}
 910
 911						// Now, pass these subband samples to
 912						// the Synthesis Subband Filter
 913
 914						for ( sb =0; sb<sblimit; sb++) {
 915							for (channel=0; channel<channels; channel++) {
 916								for (s=0; s<3; s++) {
 917									// dequantize
 918									uint x = 0;
 919
 920									while ((1<<x) < allocClass[channel][sb].numberOfSteps)
 921										{ x++; }
 922
 923									if ((sample[channel][s][sb] >> (x-1)) == 1) {
 924										quantSample[channel][s][sb] = 0.0;
 925									}
 926									else {
 927										quantSample[channel][s][sb] = -1.0;
 928									}
 929
 930									if (x > 0) {
 931										quantSample[channel][s][sb] += cast(double)(sample[channel][s][sb] & bitFills[x]) /
 932																			cast(double)(1<<x-1);
 933									}
 934
 935									// s'' = ( s''' + D ) * C
 936									quantSample[channel][s][sb] += allocClass[channel][sb].D;
 937									quantSample[channel][s][sb] *= allocClass[channel][sb].C;
 938
 939									// rescale
 940									// s' = factor * s''
 941
 942									quantSample[channel][s][sb] *= scaleFactors[scalefactor[channel][gr >> 2][sb]];
 943
 944									//printf("[%d][%d][%d] = %f\n", channel,s,sb, quantSample[channel][s][sb]);
 945								}
 946							}
 947						}
 948
 949						double sum;
 950
 951						uint i,k,j;
 952
 953						int clip;
 954
 955						for (s=0; s<3; s++) {
 956							long foo;
 957
 958							double* bufOffsetPtr;
 959							double* bufOffsetPtr2;
 960
 961							if (channels == 1) {
 962								channel = 0;
 963
 964							    bufOffset[channel] = (bufOffset[channel] - 64) & 0x3ff;
 965							    bufOffsetPtr = cast(double*)&BB[channel][bufOffset[channel]];
 966
 967								for (i=0; i<64; i++) {
 968									sum = 0;
 969									for (k=0; k<32; k++) {
 970										sum += quantSample[channel][s][k] * nCoefficients[i][k];
 971									}
 972									bufOffsetPtr[i] = sum;
 973								}
 974
 975								for (j=0; j<32; j++) {
 976									sum = 0;
 977									for (i=0; i<16; i++) {
 978										k = j + (i << 5);
 979
 980										sum += windowCoefficients[k] * BB[channel][( (k + ( ((i+1)>>1) << 6) ) + bufOffset[channel]) & 0x3ff];
 981									}
 982
 983							        if(sum > 0) {
 984										foo = cast(long)(sum * cast(double)32768 + cast(double)0.5);
 985							        }
 986							        else {
 987										foo = cast(long)(sum * cast(double)32768 - cast(double)0.5);
 988							        }
 989
 990									if (foo >= cast(long)32768) {
 991										toBuffer.write(cast(short)(32768-1));
 992										//++clip;
 993									}
 994									else if (foo < cast(long)-32768) {
 995										toBuffer.write(cast(short)(-32768));
 996										//++clip;
 997									}
 998									else {
 999										toBuffer.write(cast(short)foo);
1000									}
1001
1002									//printf("%d\n", foo);
1003								}
1004							}
1005							else {
1006								// INTERLEAVE CHANNELS!
1007
1008							    bufOffset[0] = (bufOffset[0] - 64) & 0x3ff;
1009							    bufOffsetPtr = cast(double*)&BB[0][bufOffset[0]];
1010
1011							    bufOffset[1] = (bufOffset[1] - 64) & 0x3ff;
1012							    bufOffsetPtr2 = cast(double*)&BB[1][bufOffset[1]];
1013
1014							    double sum2;
1015
1016								for (i=0; i<64; i++) {
1017									sum = 0;
1018									sum2 = 0;
1019									for (k=0; k<32; k++) {
1020										sum += quantSample[0][s][k] * nCoefficients[i][k];
1021										sum2 += quantSample[1][s][k] * nCoefficients[i][k];
1022									}
1023									bufOffsetPtr[i] = sum;
1024									bufOffsetPtr2[i] = sum2;
1025								}
1026
1027								for (j=0; j<32; j++) {
1028									sum = 0;
1029									sum2 = 0;
1030									for (i=0; i<16; i++) {
1031										k = j + (i << 5);
1032
1033										sum += windowCoefficients[k] * BB[0][( (k + ( ((i+1)>>1) << 6) ) + bufOffset[0]) & 0x3ff];
1034										sum2 += windowCoefficients[k] * BB[1][( (k + ( ((i+1)>>1) << 6) ) + bufOffset[1]) & 0x3ff];
1035									}
1036
1037							        if(sum > 0) {
1038										foo = cast(long)(sum * cast(double)32768 + cast(double)0.5);
1039							        }
1040							        else {
1041										foo = cast(long)(sum * cast(double)32768 - cast(double)0.5);
1042							        }
1043
1044									if (foo >= cast(long)32768) {
1045										toBuffer.write(cast(short)(32768-1));
1046										//++clip;
1047									}
1048									else if (foo < cast(long)-32768) {
1049										toBuffer.write(cast(short)(-32768));
1050										//++clip;
1051									}
1052									else {
1053										toBuffer.write(cast(short)foo);
1054									}
1055
1056							        if(sum2 > 0) {
1057										foo = cast(long)(sum2 * cast(double)32768 + cast(double)0.5);
1058							        }
1059							        else {
1060										foo = cast(long)(sum2 * cast(double)32768 - cast(double)0.5);
1061							        }
1062
1063									if (foo >= cast(long)32768) {
1064										toBuffer.write(cast(short)(32768-1));
1065										//++clip;
1066									}
1067									else if (foo < cast(long)-32768) {
1068										toBuffer.write(cast(short)(-32768));
1069										//++clip;
1070									}
1071									else {
1072										toBuffer.write(cast(short)foo);
1073									}
1074								}
1075							}
1076						}
1077					}
1078
1079					samplesLeft -= (12*32*3*channels);
1080
1081					if (samplesLeft <= 0) {
1082						decoderState = MP2_BUFFER_AUDIO;
1083						curTime += bufferTime;
1084							curTime.toString();
1085						return StreamData.Accepted;
1086					}
1087
1088					decoderState = MP2_READ_HEADER;
1089
1090					continue;
1091
1092				case MP2_READ_AUDIO_DATA_DUAL_CHANNEL:
1093
1094					// read in allocation bits
1095
1096					// Determine which allocation table to use
1097					//   depending on the sample frequency and bitrate
1098
1099					// Table A:
1100					//    48 kHz 	: 56, 64, 80, 96, 112, 128, 160, 192 kbits/s
1101					//    44.1		: 56, 64, 80
1102					//    32		: 56, 64, 80
1103
1104					// Table B:
1105					//    48		: N/A
1106					//    44.1		: 96, 112, 128, 160, 192
1107					//    32		: 96, 112, 128, 160, 192
1108
1109					// Table C:
1110					//    48		: 32, 48
1111					//    44.1		: 32, 48
1112					//    32		: N/A
1113
1114					// Table D:
1115					//    48		: N/A
1116					//    44.1		: N/A
1117					//    32		: 32, 48
1118
1119					uint tableType;
1120					uint sblimit;
1121
1122					if (header.SamplingFrequency == 0) {
1123						// 44.1 kHz
1124
1125						if (header.BitrateIndex >= 3 && header.BitrateIndex <= 5) {
1126							// TABLE A
1127							tableType = 0;
1128							sblimit = 27;
1129						}
1130						else if (header.BitrateIndex >= 6) {
1131							// TABLE B
1132							tableType = 0;
1133							sblimit = 30;
1134						}
1135						else {
1136							// TABLE C
1137							tableType = 1;
1138							sblimit = 8;
1139						}
1140					}
1141					else if (header.SamplingFrequency == 1) {
1142						// 48 kHz
1143
1144						if (header.BitrateIndex >= 3) {
1145							// TABLE A
1146							tableType = 0;
1147							sblimit = 27;
1148						}
1149						else {
1150							// TABLE C
1151							tableType = 1;
1152							sblimit = 8;
1153						}
1154					}
1155					else {
1156						// 32 kHz
1157
1158						if (header.BitrateIndex >= 3 && header.BitrateIndex <= 5) {
1159							// TABLE A
1160							tableType = 0;
1161							sblimit = 27;
1162						}
1163						else if (header.BitrateIndex >= 6) {
1164							// TABLE B
1165							tableType = 0;
1166							sblimit = 30;
1167						}
1168						else {
1169							// TABLE D
1170							tableType = 1;
1171							sblimit = 12;
1172						}
1173					}
1174
1175					uint sb;
1176
1177					if (tableType == 0) {
1178						// TABLE A/B
1179
1180						// length: 4 bits
1181						uint idx;
1182
1183						for ( ; sb < 3; sb++) {
1184							idx = readBits(4);
1185							allocClass[0][sb] = cast(QuantizationClass*)&allocationToQuantA1[idx];
1186							idx = readBits(4);
1187							allocClass[1][sb] = cast(QuantizationClass*)&allocationToQuantA1[idx];
1188						}
1189
1190						for ( ; sb < 11; sb++) {
1191							idx = readBits(4);
1192							allocClass[0][sb] = cast(QuantizationClass*)&allocationToQuantA2[idx];
1193							idx = readBits(4);
1194							allocClass[1][sb] = cast(QuantizationClass*)&allocationToQuantA2[idx];
1195						}
1196
1197						for ( ; sb < 23; sb++) {
1198							idx = readBits(3);
1199							allocClass[0][sb] = cast(QuantizationClass*)&allocationToQuantA3[idx];
1200							idx = readBits(3);
1201							allocClass[1][sb] = cast(QuantizationClass*)&allocationToQuantA3[idx];
1202						}
1203
1204						for ( ; sb < sblimit; sb++) {
1205							idx = readBits(2);
1206							allocClass[0][sb] = cast(QuantizationClass*)&allocationToQuantA4[idx];
1207							idx = readBits(2);
1208							allocClass[1][sb] = cast(QuantizationClass*)&allocationToQuantA4[idx];
1209						}
1210					}
1211					else {
1212						// TABLE C/D
1213
1214						uint idx;
1215
1216						for ( ; sb < 2; sb++) {
1217							idx = readBits(4);
1218							allocClass[0][sb] = cast(QuantizationClass*)&allocationToQuantC1[idx];
1219							idx = readBits(4);
1220							allocClass[1][sb] = cast(QuantizationClass*)&allocationToQuantC1[idx];
1221
1222						}
1223
1224						for ( ; sb < sblimit; sb++) {
1225							idx = readBits(3);
1226							allocClass[0][sb] = cast(QuantizationClass*)&allocationToQuantC1[idx];
1227							idx = readBits(3);
1228							allocClass[1][sb] = cast(QuantizationClass*)&allocationToQuantC1[idx];
1229						}
1230					}
1231
1232					// Read Scalefactor Selection Information
1233
1234					for (sb=0; sb<sblimit; sb++) {
1235						if (allocClass[0][sb].numberOfSteps!=0) {
1236							scfsi[0][sb] = readBits(2);
1237						}
1238
1239						if (allocClass[1][sb].numberOfSteps!=0) {
1240							scfsi[1][sb] = readBits(2);
1241						}
1242					}
1243
1244					// Read Scalefactor Indices
1245
1246					for (sb=0; sb<sblimit; sb++) {
1247						if (allocClass[0][sb].numberOfSteps!=0) {
1248							if (scfsi[0][sb]==0) {
1249								scalefactor[0][0][sb] = readBits(6); 	// 6	bits	uimsbf
1250								scalefactor[0][1][sb] = readBits(6);	// 6	bits	uimsbf
1251								scalefactor[0][2][sb] = readBits(6);  // 6	bits	uimsbf
1252							}
1253							else if ((scfsi[0][sb]==1) || (scfsi[0][sb]==3)) {
1254								scalefactor[0][0][sb] = readBits(6); 	// 6	bits	uimsbf
1255								scalefactor[0][2][sb] = readBits(6);	// 6	bits	uimsbf
1256
1257								// scale factors are paired differently:
1258								if (scfsi[0][sb] == 1) {
1259									scalefactor[0][1][sb] = scalefactor[0][0][sb];
1260								}
1261								else {
1262									scalefactor[0][1][sb] = scalefactor[0][2][sb];
1263								}
1264							}
1265							else if (scfsi[0][sb]==2) {
1266								scalefactor[0][0][sb] = readBits(6);  // 6	bits	uimsbf
1267								scalefactor[0][1][sb] = scalefactor[0][0][sb];
1268								scalefactor[0][2][sb] = scalefactor[0][0][sb];
1269							}
1270						}
1271						else {
1272							scalefactor[0][0][sb] = 63;
1273							scalefactor[0][1][sb] = 63;
1274							scalefactor[0][2][sb] = 63;
1275						}
1276
1277						if (allocClass[1][sb].numberOfSteps!=0) {
1278							if (scfsi[1][sb]==0) {
1279								scalefactor[1][0][sb] = readBits(6); 	// 6	bits	uimsbf
1280								scalefactor[1][1][sb] = readBits(6);	// 6	bits	uimsbf
1281								scalefactor[1][2][sb] = readBits(6);  // 6	bits	uimsbf
1282							}
1283							else if ((scfsi[1][sb]==1) || (scfsi[1][sb]==3)) {
1284								scalefactor[1][0][sb] = readBits(6); 	// 6	bits	uimsbf
1285								scalefactor[1][2][sb] = readBits(6);	// 6	bits	uimsbf
1286
1287								// scale factors are paired differently:
1288								if (scfsi[1][sb] == 1) {
1289									scalefactor[1][1][sb] = scalefactor[1][0][sb];
1290								}
1291								else {
1292									scalefactor[1][1][sb] = scalefactor[1][2][sb];
1293								}
1294							}
1295							else if (scfsi[1][sb]==2) {
1296								scalefactor[1][0][sb] = readBits(6);  // 6	bits	uimsbf
1297								scalefactor[1][1][sb] = scalefactor[1][0][sb];
1298								scalefactor[1][2][sb] = scalefactor[1][0][sb];
1299							}
1300						}
1301						else {
1302							scalefactor[1][0][sb] = 63;
1303							scalefactor[1][1][sb] = 63;
1304							scalefactor[1][2][sb] = 63;
1305						}
1306					}
1307
1308					uint gr, s, base;
1309
1310					for (gr=0, base=0; gr<12; gr++, base+=3) {
1311						for (sb=0; sb<sblimit; sb++) {
1312							if (allocClass[0][sb].numberOfSteps!=0) {
1313								if (allocClass[0][sb].grouping) {
1314									samplecode = readBits(allocClass[0][sb].bitsPerCodeword);	// 5..10	bits	uimsbf
1315										//writeln(samplecode, "@ bit");
1316									assert((allocClass[0][sb].bitsPerCodeword > 4) && (allocClass[0][sb].bitsPerCodeword < 11));
1317
1318									// ungroup
1319
1320									for (s=0; s<3; s++) {
1321										sample[0][base + s][sb] = samplecode % allocClass[0][sb].numberOfSteps;
1322										samplecode /= allocClass[0][sb].numberOfSteps;
1323
1324										// requantize
1325									}
1326								}
1327								else {
1328									for (s=0; s<3; s++) {
1329										sample[0][base + s][sb] = readBits(allocClass[0][sb].bitsPerCodeword); // 2..16	bits	uimsbf
1330											//writeln(sample[0][s][sb], "! bit ", allocClass[0][sb].bitsPerCodeword);
1331										assert((allocClass[0][sb].bitsPerCodeword > 1) && (allocClass[0][sb].bitsPerCodeword < 17));
1332
1333									}
1334								}
1335							}
1336							else {
1337								sample[0][base + 0][sb] = 0;
1338								sample[0][base + 1][sb] = 0;
1339								sample[0][base + 2][sb] = 0;
1340							}
1341
1342							if (allocClass[1][sb].numberOfSteps!=0) {
1343								if (allocClass[1][sb].grouping) {
1344									samplecode = readBits(allocClass[1][sb].bitsPerCodeword);	// 5..10	bits	uimsbf
1345										//writeln(samplecode, "+ bit");
1346									assert((allocClass[1][sb].bitsPerCodeword > 4) && (allocClass[1][sb].bitsPerCodeword < 11));
1347
1348									// ungroup
1349
1350									for (s=0; s<3; s++) {
1351										sample[1][base + s][sb] = samplecode % allocClass[1][sb].numberOfSteps;
1352										samplecode /= allocClass[1][sb].numberOfSteps;
1353
1354										// requantize
1355									}
1356								}
1357								else {
1358									for (s=0; s<3; s++) {
1359										sample[1][base + s][sb] = readBits(allocClass[1][sb].bitsPerCodeword); // 2..16	bits	uimsbf
1360											//writeln(sample[1][s][sb], "- bit");
1361										assert((allocClass[1][sb].bitsPerCodeword > 1) && (allocClass[1][sb].bitsPerCodeword < 17));
1362
1363									}
1364								}
1365							}
1366							else {
1367								sample[1][base + 0][sb] = 0;
1368								sample[1][base + 1][sb] = 0;
1369								sample[1][base + 2][sb] = 0;
1370							}
1371						}
1372
1373						for ( ; sb<32; sb++) {
1374							for (s=0; s<3; s++) {
1375								quantSample[0][base + s][sb] = 0.0;
1376								quantSample[1][base + s][sb] = 0.0;
1377							}
1378						}
1379
1380						// Now, pass these subband samples to
1381						// the Synthesis Subband Filter
1382
1383						for ( sb =0; sb<sblimit; sb++) {
1384							for (s=0; s<3; s++) {
1385								// dequantize
1386								uint x = 0;
1387
1388								while ((1<<x) < allocClass[0][sb].numberOfSteps) {
1389									x++;
1390								}
1391
1392								if ((sample[0][base + s][sb] >> (x-1)) == 1) {
1393									quantSample[0][base + s][sb] = 0.0;
1394								}
1395								else
1396								{
1397									quantSample[0][base + s][sb] = -1.0;
1398								}
1399
1400								if (x > 0) {
1401									quantSample[0][base + s][sb] += cast(double)(sample[0][base + s][sb] & bitFills[x])
1402										/ cast(double)(1<<x-1);
1403								}
1404
1405								// s'' = ( s''' + D ) * C
1406								quantSample[0][base + s][sb] += allocClass[0][sb].D;
1407								quantSample[0][base + s][sb] *= allocClass[0][sb].C;
1408
1409								// rescale
1410								// s' = factor * s''
1411
1412								quantSample[0][base + s][sb] *= scaleFactors[scalefactor[0][gr>>2][sb]];
1413
1414								//printf("sample = [%d][%d][%d] = %f\n", 0, s, sb, quantSample[0][s][sb]);
1415
1416
1417								x=0;
1418
1419								while ((1<<x) < allocClass[1][sb].numberOfSteps) {
1420									x++;
1421								}
1422
1423								if ((sample[1][base + s][sb] >> (x-1)) == 1) {
1424									quantSample[1][base + s][sb] = 0.0;
1425								}
1426								else {
1427									quantSample[1][base + s][sb] = -1.0;
1428								}
1429
1430								if (x > 0) {
1431									quantSample[1][base + s][sb] += cast(double)(sample[1][base + s][sb] & bitFills[x]) /
1432																		cast(double)(1<<x-1);
1433								}
1434
1435								// s'' = ( s''' + D ) * C
1436								quantSample[1][base + s][sb] += allocClass[1][sb].D;
1437								quantSample[1][base + s][sb] *= allocClass[1][sb].C;
1438
1439								// rescale
1440								// s' = factor * s''
1441
1442								quantSample[1][base + s][sb] *= scaleFactors[scalefactor[1][gr>>2][sb]];
1443
1444								//printf("sample = [%d][%d][%d] = %f\n", 1, s, sb, quantSample[1][s][sb]);
1445							}
1446						}
1447
1448						double sum;
1449
1450						uint i,k,j;
1451
1452						int clip;
1453
1454						for (s=0; s<3; s++) {
1455							for (uint channel = 0;channel<2;channel++) {
1456								long foo;
1457								static int bufOffset[2] = [64,64];
1458
1459								// initialize the array to zero
1460								typedef double zerodouble = 0.0;
1461
1462								static zerodouble BB[2][2*512];
1463
1464								double* bufOffsetPtr;
1465
1466								bufOffset[channel] = (bufOffset[channel] - 64) & 0x3ff;
1467								bufOffsetPtr = cast(double*)&BB[channel][bufOffset[channel]];
1468
1469								for (i=0; i<64; i++) {
1470									sum = 0;
1471									for (k=0; k<32; k++) {
1472										sum += quantSample[channel][base + s][k] * nCoefficients[i][k];
1473									}
1474									bufOffsetPtr[i] = sum;
1475								}
1476
1477
1478								for (j=0; j<32; j++) {
1479									sum = 0;
1480									for (i=0; i<16; i++) {
1481										k = j + (i << 5);
1482
1483										sum += windowCoefficients[k] * BB[channel][( (k + ( ((i+1)>>1) << 6) ) + bufOffset[channel]) & 0x3ff];
1484									}
1485
1486							        if(sum > 0) {
1487										foo = cast(long)(sum * cast(double)32768 + cast(double)0.5);
1488							        }
1489							        else {
1490										foo = cast(long)(sum * cast(double)32768 - cast(double)0.5);
1491							        }
1492
1493									if (foo >= cast(long)32768) {
1494										toBuffer.write(cast(short)(32768-1));
1495										//++clip;
1496									}
1497									else if (foo < cast(long)-32768) {
1498										toBuffer.write(cast(short)(-32768));
1499										//++clip;
1500									}
1501									else {
1502										toBuffer.write(cast(short)foo);
1503									}
1504
1505									//writeln(foo);
1506								}
1507							}
1508						}
1509					}
1510
1511					samplesLeft -= (12*32*3*2);
1512
1513					if (samplesLeft <= 0) {
1514						decoderState = MP2_BUFFER_AUDIO;
1515						curTime += bufferTime;
1516						return StreamData.Accepted;
1517					}
1518
1519					decoderState = MP2_READ_HEADER;
1520
1521					continue;
1522
1523				case MP2_READ_AUDIO_DATA_JOINT_STEREO:
1524
1525					continue;
1526
1527					// -- Default for corrupt files -- //
1528
1529				default:
1530					// invalid state
1531					break;
1532			}
1533			break;
1534		}
1535		return StreamData.Invalid;
1536	}
1537
1538	uint readBits(uint bits) {
1539		// read a byte, read bits, whatever necessary to get the value
1540		//writeln("reading, # bits:", bits, " curbyte:", *curByte);
1541
1542		uint curvalue;
1543		uint value = 0;
1544
1545		uint mask;
1546		uint maskbits;
1547
1548		int shift;
1549
1550		if (curByte >= audioData.ptr + audioData.length) {
1551			// We have consumed everything in our buffer
1552			return 0;
1553		}
1554
1555		for (;;) {
1556			if (bits == 0) { return value; }
1557
1558			if (bits > 8) {
1559				maskbits = 8;
1560			}
1561			else {
1562				maskbits = bits;
1563			}
1564			//writeln("curpos:", curPos, " for bits:", bits, " maskbits:", maskbits);
1565
1566			curvalue = ((*curByte) & (byteMasks[maskbits][curPos]));
1567
1568			shift = ((8-cast(int)curPos) - cast(int)bits);
1569
1570			if (shift > 0) {
1571				curvalue >>= shift;
1572			}
1573			else if (shift < 0) {
1574				curvalue <<= -shift;
1575			}
1576
1577			//writeln("has curvalue:", curvalue);
1578
1579			value |= curvalue;
1580
1581			//writeln("has value:", value);
1582
1583			curPos += maskbits;
1584
1585			if (curPos >= 8) {
1586				bits -= (8 - curPos + maskbits);
1587				curPos = 0;
1588				curByte++;
1589
1590				if (curByte >= audioData.ptr + audioData.length) {
1591					// We have consumed everything in our buffer
1592					return 0;
1593				}
1594
1595				//writeln("CURBYTE ** ", *curByte, " ** ");
1596			}
1597			else {
1598				break;
1599			}
1600		}
1601		return value;
1602	}
1603
1604	StreamData seek(Stream stream, AudioFormat wf, AudioInfo wi, ref Time amount) {
1605		if (decoderState == 0) {
1606			// not inited?
1607			return StreamData.Invalid;
1608		}
1609
1610		if (amount == curTime) {
1611			Console.putln("ON TIME");
1612			return StreamData.Accepted;
1613		}
1614
1615		if (amount > curTime) {
1616			Console.putln("WE NEED TO GO AHEAD");
1617			// good!
1618			// simply find the section we need to be
1619			// we are buffering 2 seconds...
1620			toSeek = amount;
1621			isSeekBack = false;
1622			isSeek = true;
1623			StreamData ret = decode(stream, null, wi);
1624			if (ret == StreamData.Required) { return ret; }
1625
1626			amount -= curTime;
1627			amount.toString();
1628			return ret;
1629		}
1630		else {
1631			Console.putln("WE NEED TO FALL BEHIND");
1632			// for wave files, this is not altogether a bad thing
1633			// for other types of files, it might be
1634			// mp3 can be variable, and would require a seek from the
1635			// beginning or maintaining a cache of some sort.
1636			if (!stream.rewind(cast(ulong)(stream.position - cast(long)posOfFirstFrame)))
1637			{
1638				return StreamData.Required;
1639			}
1640
1641			toSeek = amount;
1642			isSeekBack = false;
1643			isSeek = true;
1644
1645			curTime = Time.init;
1646
1647			StreamData ret =  decode(stream, null, wi);
1648			if (ret == StreamData.Required) { return ret; }
1649
1650			amount -= curTime;
1651			amount.toString();
1652			return ret;
1653		}
1654	}
1655
1656	Time length(Stream stream, ref AudioFormat wf, ref AudioInfo wi) {
1657		Time tme = Time.init;
1658		return tme;
1659	}
1660
1661	Time lengthQuick(Stream stream, ref AudioFormat wf, ref AudioInfo wi) {
1662		Time tme = Time.init;
1663		return tme;
1664	}
1665
1666protected:
1667
1668	bool accepted;
1669
1670	uint mpeg_header;
1671	uint known_sync_bits;
1672
1673	ushort crc;
1674
1675	uint audioDataLength;
1676
1677	ubyte audioData[];
1678	QuantizationClass* allocClass[2][32];
1679	uint scfsi[2][32];
1680
1681	uint scalefactor[2][3][32];
1682	uint samplecode;
1683	uint sample[2][3][32];
1684
1685	double quantSample[2][3][32];
1686
1687	uint channels;
1688
1689	uint samplesLeft;
1690
1691	uint bufferSize;
1692	AudioFormat wf;
1693
1694	Time bufferTime;
1695
1696	long posOfFirstFrame;
1697
1698
1699	// bit building
1700	ubyte* curByte;
1701	uint curPos;
1702
1703	MP2HeaderInformation header;
1704
1705	align(1) struct ID3HeaderInformation {
1706		ubyte[3] signature;
1707		ubyte[2] ver;
1708		ubyte flags;
1709		ubyte[4] len;
1710	}
1711
1712	ID3HeaderInformation id3;
1713	
1714	uint id3length;
1715
1716	int bufOffset[2] = [64,64];
1717
1718	zerodouble BB[2][2*512];
1719
1720	// Import common lookup tables
1721	import decoders.audio.mpegCommon;
1722}