PageRenderTime 156ms CodeModel.GetById 17ms app.highlight 124ms RepoModel.GetById 1ms app.codeStats 1ms

/decoders/audio/mp3.d

http://github.com/wilkie/djehuty
D | 2440 lines | 342 code | 117 blank | 1981 comment | 62 complexity | fa55c9c98c9834a83ed3bbd9f7d0c65d MD5 | raw file

Large files files are truncated, but you can click here to view the full file

   1/*
   2 * mp3.d
   3 *
   4 * This file implements the MP3 audio standard.
   5 *
   6 * Author: Dave Wilkinson
   7 *
   8 */
   9
  10module decoders.audio.mp3;
  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
  24import math.common;
  25
  26// initialize the array to zero
  27typedef double zerodouble = 0.0;
  28
  29template FromBigEndian(uint input) {
  30	version (LittleEndian) {
  31		const auto FromBigEndian = (input >> 24) | ((input >> 8) & 0x0000FF00) | ((input << 8) & 0x00FF0000) | ((input << 24) & 0xFF000000);
  32	}
  33	else {
  34		const auto FromBigEndian = input;
  35	}
  36}
  37
  38template FromBigEndianBitIndex32(uint index) {
  39	version (LittleEndian) {
  40		const auto FromBigEndianBitIndex32 = ((3 - cast(uint)(index/8)) * 8) + (index % 8);
  41	}
  42	else {
  43		const auto FromBigEndianBitIndex32 = index;
  44	}
  45}
  46
  47class MP3Decoder : AudioDecoder {
  48
  49private:
  50
  51	enum : uint {
  52		MP3_STATE_INIT,
  53		MP3_BUFFER_AUDIO,
  54		MP3_READ_HEADER,
  55		MP3_AMBIGUOUS_SYNC,
  56		MP3_READ_CRC,
  57		MP3_READ_AUDIO_DATA,
  58		MP3_READ_AUDIO_DATA_PREAMBLE,
  59		MP3_READ_AUDIO_DATA_SINGLE_CHANNEL,
  60		MP3_READ_AUDIO_DATA_SCALE_FACTORS,
  61		MP3_READ_AUDIO_DATA_JOINT_STEREO,
  62	}
  63
  64	align(1) struct MP3HeaderInformation {
  65		uint ID;
  66		uint Layer;
  67		uint Protected;
  68		uint BitrateIndex;
  69		uint SamplingFrequency;
  70		uint Padding;
  71		uint Private;
  72		uint Mode;
  73		uint ModeExtension;
  74		uint Copyright;
  75		uint Original;
  76		uint Emphasis;
  77	}
  78
  79	align(1) struct ID3HeaderInformation {
  80		ubyte[3] signature;
  81		ubyte[2] ver;
  82		ubyte flags;
  83		ubyte[4] len;
  84	}
  85
  86	const auto MPEG_SYNC_BITS 		= FromBigEndian!(0xFFF00000);
  87	const auto MPEG_ID_BIT    		= FromBigEndian!(0x00080000);
  88	const auto MPEG_LAYER			= FromBigEndian!(0x00060000);
  89	const auto MPEG_LAYER_SHIFT				= FromBigEndianBitIndex32!(17);
  90	const auto MPEG_PROTECTION_BIT	= FromBigEndian!(0x00010000);
  91	const auto MPEG_BITRATE_INDEX	= FromBigEndian!(0x0000F000);
  92	const auto MPEG_BITRATE_INDEX_SHIFT 	= FromBigEndianBitIndex32!(12);
  93	const auto MPEG_SAMPLING_FREQ	= FromBigEndian!(0x00000C00);
  94	const auto MPEG_SAMPLING_FREQ_SHIFT 	= FromBigEndianBitIndex32!(10);
  95	const auto MPEG_PADDING_BIT		= FromBigEndian!(0x00000200);
  96	const auto MPEG_PRIVATE_BIT		= FromBigEndian!(0x00000100);
  97	const auto MPEG_MODE			= FromBigEndian!(0x000000C0);
  98	const auto MPEG_MODE_SHIFT				= FromBigEndianBitIndex32!(6);
  99	const auto MPEG_MODE_EXTENSION	= FromBigEndian!(0x00000030);
 100	const auto MPEG_MODE_EXTENSION_SHIFT 	= FromBigEndianBitIndex32!(4);
 101	const auto MPEG_COPYRIGHT		= FromBigEndian!(0x00000008);
 102	const auto MPEG_ORIGINAL		= FromBigEndian!(0x00000004);
 103	const auto MPEG_EMPHASIS		= FromBigEndian!(0x00000003);
 104	const auto MPEG_EMPHASIS_SHIFT = 0;
 105
 106	// modes
 107
 108	const auto MPEG_MODE_STEREO			= 0;
 109	const auto MPEG_MODE_JOINT_STEREO	= 1;
 110	const auto MPEG_MODE_DUAL_CHANNEL	= 2;
 111	const auto MPEG_MODE_SINGLE_CHANNEL = 3;
 112
 113	const uint byteMasks[9][] = [
 114		[0x00, 0x00, 0x00, 0x00, 0x0, 0x0, 0x0, 0x0],		// 0 bit
 115		[0x80, 0x40, 0x20, 0x10, 0x8, 0x4, 0x2, 0x1],		// 1 bit
 116		[0xC0, 0x60, 0x30, 0x18, 0xC, 0x6, 0x3, 0x1],		// 2 bits
 117		[0xE0, 0x70, 0x38, 0x1C, 0xE, 0x7, 0x3, 0x1],		// 3 bits
 118		[0xF0, 0x78, 0x3C, 0x1E, 0xF, 0x7, 0x3, 0x1],		// 4 bits
 119		[0xF8, 0x7C, 0x3E, 0x1F, 0xF, 0x7, 0x3, 0x1],		// 5 bits
 120		[0xFC, 0x7E, 0x3F, 0x1F, 0xF, 0x7, 0x3, 0x1],		// 6 bits
 121		[0xFE, 0x7F, 0x3F, 0x1F, 0xF, 0x7, 0x3, 0x1],		// 7 bits
 122		[0xFF, 0x7F, 0x3F, 0x1F, 0xF, 0x7, 0x3, 0x1]		// 8 bits
 123	];
 124
 125	// layer 3 bit rates (MPEG-1)
 126	const uint[] bitRates = [ 0, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320 ]; // the first entry is the 'free' bitrate
 127	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
 128
 129	// Scalefactor Band Indices
 130	const uint[23][3] sfindex_long = [
 131		// 44.1
 132		[0, 4, 8, 12, 16, 20, 24, 30, 36, 44, 52, 62, 74, 90, 110, 134, 162, 196, 238, 288, 342, 418, 576],
 133		// 48.0
 134		[0, 4, 8, 12, 16, 20, 24, 30, 36, 42, 50, 60, 72, 88, 106, 128, 156, 190, 230, 276, 330, 384, 576],
 135		// 32.0
 136		[0, 4, 8, 12, 16, 20, 24, 30, 36, 44, 54, 66, 82, 102, 126, 156, 194, 240, 296, 364, 448, 550, 576]
 137	];
 138
 139	const uint[14][3] sfindex_short = [
 140		// 44.1
 141		[0, 4, 8, 12, 16, 22, 30, 40, 52, 66, 84, 106, 136, 192],
 142		// 48.0
 143		[0, 4, 8, 12, 16, 22, 28, 38, 50, 64, 80, 100, 126, 192],
 144		// 32.0
 145		[0, 4, 8, 12, 16, 22, 30, 42, 58, 78, 104, 138, 180, 192]
 146	];
 147	
 148	// Synthesis Filter Working Area:
 149	int bufOffset[2] = [64,64];
 150	zerodouble BB[2][2*512];
 151
 152	// Static Huffman tables
 153
 154	// Imports huffmanTables[][][] and huffmanValues[][]
 155	// These are in an array from 0 - 16 and then table 24 being 17
 156	// Index as: huffmanTables[tableIndex][bitlength][value]
 157	//           huffmanValues[tableIndex][value]
 158	// Both tables correspond in their order.
 159	import decoders.audio.mp3Huffman;
 160
 161	uint[][] curTable;
 162	uint[] curValues;
 163	uint linbits;
 164
 165	// Select the table to use for decoding and reset state.
 166	void initializeHuffman(uint region, uint gr, uint ch) {
 167		uint tableIndex = table_select[region][gr][ch];
 168		
 169		switch (tableIndex) {
 170
 171			case 16:
 172				linbits = 1;
 173				break;
 174
 175			case 17:
 176				linbits = 2;
 177				break;
 178
 179			case 18:
 180				linbits = 3;
 181				break;
 182
 183			case 24:
 184			case 19:
 185				linbits = 4;
 186				break;
 187				
 188			case 25:
 189				linbits = 5;
 190				break;
 191
 192			case 26:
 193			case 20:
 194				linbits = 6;
 195				break;
 196
 197			case 27:
 198				linbits = 7;
 199				break;
 200
 201			case 28:
 202			case 21:
 203				linbits = 8;
 204				break;
 205
 206			case 29:
 207				linbits = 9;
 208				break;
 209
 210			case 22:
 211				linbits = 10;
 212				break;
 213
 214			case 30:
 215				linbits = 11;
 216				break;
 217
 218			case 31:
 219			case 23:
 220				linbits = 13;
 221				break;
 222
 223			default:
 224				linbits = 0;
 225				break;
 226		}
 227
 228		if (tableIndex >= 24) {
 229			tableIndex = 17;
 230		}
 231		else if (tableIndex >= 16) {
 232			tableIndex = 16;
 233		}
 234
 235		// XXX: This silliness is due to a compiler bug in DMD 1.046
 236		if (tableIndex == 17) {
 237			curTable = huffmanTable24;
 238		}
 239		else {
 240			curTable = huffmanTables[tableIndex];
 241		}
 242		curValues = huffmanValues[tableIndex];
 243	}
 244
 245	int[] readCode() {
 246		uint code;
 247		uint bitlength;
 248		uint valoffset;
 249
 250		for(;;) {
 251			code <<= 1;
 252			code |= readBits(1);
 253			
 254			if (bitlength > curTable.length) {
 255				break;
 256			}
 257
 258			foreach(uint i, foo; curTable[bitlength]) {
 259				if (foo == code) {
 260					// found code
 261
 262					// get value offset
 263					valoffset += i;
 264					valoffset *= 2;
 265
 266     				int[] values = [curValues[valoffset], curValues[valoffset+1]];
 267     			//	Console.putln("b:", values[0], " ", values[1]);
 268
 269					// read linbits (x)
 270					if (linbits > 0 && values[0] == 15) {
 271						values[0] += readBits(linbits);
 272					}
 273
 274					if (values[0] > 0) {
 275						if (readBits(1) == 1) {
 276							values[0] = -values[0];
 277						}
 278					}
 279
 280					if (linbits > 0 && values[1] == 15) {
 281						values[1] += readBits(linbits);
 282					}
 283
 284					if (values[1] > 0) {
 285						if (readBits(1) == 1) {
 286							values[1] = -values[1];
 287						}
 288					}
 289
 290     				//Console.putln("a:", values[0], " ", values[1]);
 291					return values;
 292				}
 293			}
 294
 295			valoffset += curTable[bitlength].length;
 296			bitlength++;
 297			if (bitlength >= curTable.length) {
 298				return [128, 128];
 299			}
 300		}
 301
 302		return [128, 128];
 303	}
 304
 305	uint curCountTable;
 306
 307	void initializeQuantizationHuffman(uint gr, uint ch) {
 308		curCountTable = count1table_select[gr][ch];
 309	}
 310
 311	int[] readQuantizationCode() {
 312		uint code = decodeQuantization();
 313
 314		int v = ((code >> 3) & 1);
 315		int w = ((code >> 2) & 1);
 316		int x = ((code >> 1) & 1);
 317		int y = (code & 1);
 318
 319		// Get Sign Bits (for non-zero values)
 320
 321		if (v > 0 && readBits(1) == 1) {
 322			v = -v;
 323		}
 324
 325		if (w > 0 && readBits(1) == 1) {
 326			w = -w;
 327		}
 328
 329		if (x > 0 && readBits(1) == 1) {
 330			x = -x;
 331		}
 332
 333		if (y > 0 && readBits(1) == 1) {
 334			y = -y;
 335		}
 336
 337	//	Console.putln("v: ", v, " w: ", w, " x: ", x , " y: ",y );
 338
 339		return [v,w,x,y];
 340	}
 341
 342	uint decodeQuantization() {
 343		uint code;
 344
 345		if (curCountTable == 1) {
 346			// Quantization Huffman Table B is trivial...
 347			// It is simply the bitwise negation of 4 bits from the stream.
 348			// code = ~readBits(4);
 349			code = readBits(4);
 350			code = ~code;
 351		}
 352		else {
 353			// Quantization Huffman Table A is the only case,
 354			// so it is written here by hand:
 355
 356			// state 1
 357			code = readBits(1);
 358
 359			if (code == 0b1) {
 360				return 0b0000;
 361			}
 362
 363			// state 2
 364			code = readBits(3);
 365
 366			if (code >= 0b0100 && code <= 0b0111) {
 367				uint idx = code - 0b0100;
 368				const uint[] stage2_values = [0b0010, 0b0101, 0b0110, 0b0111];
 369				return stage2_values[idx];
 370			}
 371
 372			// state 3
 373			code <<= 1;
 374			code |= readBits(1);
 375
 376			if (code >= 0b00011 && code <= 0b00111) {
 377				uint idx = code - 0b00011;
 378				const uint[] stage3_values = [0b1001, 0b0110, 0b0011, 0b1010, 0b1100];
 379				return stage3_values[idx];
 380			}
 381
 382			// state 4
 383			code <<= 1;
 384			code |= readBits(1);
 385
 386			if (code <= 0b000101) {
 387				const uint[] stage4_values = [0b1011, 0b1111, 0b1101, 0b1110, 0b0111, 0b0101];
 388				return stage4_values[code];
 389			}
 390
 391			// invalid code;
 392			code = 0;
 393		}
 394
 395		return code;
 396	}
 397
 398	import decoders.audio.mpegCommon;
 399
 400	bool accepted = false;
 401
 402	// number of blocks (of 1728 samples) to buffer
 403	const auto NUM_BLOCKS = 40;
 404	
 405	Wavelet tempBuffer;
 406
 407public:
 408	string name() {
 409		return "MPEG Layer 3";
 410	}
 411
 412	string extension() {
 413		return "mp3";
 414	}
 415
 416	bool firstTime = true;
 417
 418	StreamData decode(Stream stream, Wavelet toBuffer, ref AudioInfo wi) {
 419		for(;;) {
 420			switch (decoderState) {
 421				case MP3_STATE_INIT:
 422
 423					decoderState = MP3_BUFFER_AUDIO;
 424
 425					/* follow through */
 426
 427					// attempts to find the 12-16 sync bits
 428					// if it is unsure of the filetype, it will
 429					// look for only 12 bits (b 1111 1111 1111)
 430					// if it knows its layer it will search for
 431					// the sync bits plus that part of the header
 432				case MP3_BUFFER_AUDIO:
 433
 434					samplesLeft = 1728 * NUM_BLOCKS;
 435
 436					if (toBuffer !is null) {
 437						samplesLeft = cast(int)(toBuffer.length() / 1728) * 1728;
 438						samplesLeft += 1728;
 439						bufferSize = samplesLeft;
 440					}
 441
 442					bufferSize = samplesLeft;
 443
 444					decoderState = MP3_READ_HEADER;
 445
 446					// *** fall through *** //
 447
 448				case MP3_READ_HEADER:
 449					//Console.putln("pos: ", new String("%x", stream.position));
 450
 451					if (!stream.read(mpeg_header)) {
 452						return StreamData.Accepted;
 453					}
 454
 455					decoderState = MP3_AMBIGUOUS_SYNC;
 456
 457
 458					// *** fall through *** //
 459
 460					// look at the sync bits of the header
 461					// if they are not correct, shift the header
 462					// 8 bits and read another byte until the
 463					// sync bits match
 464
 465				case MP3_AMBIGUOUS_SYNC:
 466
 467     				if ((mpeg_header & FromBigEndian!(0xFFFFFF00)) == FromBigEndian!(0x49443300)) {
 468
 469     					if (id3.signature[0] != 0x49) {
 470							if (!stream.read((cast(ubyte*)&id3) + 4, id3.sizeof - 4)) {
 471								return StreamData.Required;
 472							}
 473
 474							id3.signature[0] = 0x49;
 475
 476							id3.ver[0] = cast(ubyte)(mpeg_header & 0xFF);
 477
 478							// skip the ID3 section
 479							foreach(b; id3.len) {
 480								id3length <<= 7;
 481								b &= 0x7f;
 482								id3length |= b;
 483							}
 484
 485							//Console.putln("id3 length: ", new String("%x", id3length));
 486						}
 487
 488						if (!stream.skip(id3length)) {
 489							return StreamData.Required;
 490						}
 491
 492						decoderState = MP3_READ_HEADER;
 493						continue;
 494					}
 495
 496					//Console.putln("mpeg_header ", new String("%x", mpeg_header)	);
 497
 498					if ((mpeg_header & MPEG_SYNC_BITS) == MPEG_SYNC_BITS) {
 499						// sync bits found
 500						//writeln("sync bits found ", stream.getPosition() - 4);
 501
 502						// pull apart header
 503
 504						// the header looks like this:
 505
 506						// SYNCWORD			12 bits
 507						// ID				1 bit
 508						// LAYER			2 bits
 509						// PROTECTION BIT	1 bit
 510						// BITRATE INDEX	4 bits
 511						// SAMPLING FREQ	2 bits
 512						// PADDING BIT		1 bit
 513						// PRIVATE BIT		1 bit
 514						// MODE				2 bits
 515						// MODE EXTENSION	2 bits
 516						// COPYRIGHT		1 bit
 517						// ORIGINAL/HOME	1 bit
 518						// EMPHASIS			2 bits
 519
 520						header.ID = (mpeg_header & MPEG_ID_BIT ? 1 : 0);
 521						header.Layer = (mpeg_header & MPEG_LAYER) >> MPEG_LAYER_SHIFT;
 522
 523						if (header.Layer != 1) {
 524							return StreamData.Invalid;
 525						}
 526
 527						header.Protected = (mpeg_header & MPEG_PROTECTION_BIT ? 1 : 0);
 528						header.BitrateIndex = (mpeg_header & MPEG_BITRATE_INDEX) >> MPEG_BITRATE_INDEX_SHIFT;
 529						header.SamplingFrequency = (mpeg_header & MPEG_SAMPLING_FREQ) >> MPEG_SAMPLING_FREQ_SHIFT;
 530						header.Padding = (mpeg_header & MPEG_PADDING_BIT ? 1 : 0);
 531						header.Private = (mpeg_header & MPEG_PRIVATE_BIT ? 1 : 0);
 532						header.Mode = (mpeg_header & MPEG_MODE) >> MPEG_MODE_SHIFT;
 533						header.ModeExtension = (mpeg_header & MPEG_MODE_EXTENSION) >> MPEG_MODE_EXTENSION_SHIFT;
 534						header.Copyright = (mpeg_header & MPEG_COPYRIGHT ? 1 : 0);
 535						header.Original = (mpeg_header & MPEG_ORIGINAL ? 1 : 0);
 536						header.Emphasis = (mpeg_header & MPEG_EMPHASIS) >> MPEG_EMPHASIS_SHIFT;
 537
 538						/*Console.putln("Header: ", mpeg_header & MPEG_SYNC_BITS, "\n",
 539								"ID: ", header.ID, "\n",
 540								"Layer: ", header.Layer, "\n",
 541								"Protected: ", header.Protected, "\n",
 542								"BitrateIndex: ", header.BitrateIndex, "\n",
 543								"SamplingFrequency: ", header.SamplingFrequency, "\n",
 544								"Padding: ", header.Padding, "\n",
 545								"Private: ", header.Private, "\n",
 546								"Mode: ", header.Mode, "\n",
 547								"ModeExtension: ", header.ModeExtension, "\n",
 548								"Copyright: ", header.Copyright, "\n",
 549								"Original: ", header.Original, "\n",
 550								"Emphasis: ", header.Emphasis); //*/
 551
 552						// Calculate the length of the Audio Data
 553
 554						bufferLength = cast(uint)(144 * (cast(double)bitRates[header.BitrateIndex] / cast(double)samplingFrequencies[header.SamplingFrequency]));
 555						if (header.Padding) {
 556							bufferLength++;
 557						}
 558
 559						// subtract the size of the header
 560						bufferLength -= 4;
 561
 562						// set the format of the wave buffer
 563
 564						if (header.SamplingFrequency == 0) {
 565							// 44.1 kHz
 566							wf.samplesPerSecond = 44100;
 567						}
 568						else if (header.SamplingFrequency == 1) {
 569							// 48 kHz
 570							wf.samplesPerSecond = 48000;
 571						}
 572						else {
 573							// 32 kHz
 574							wf.samplesPerSecond = 32000;
 575						}
 576
 577						wf.compressionType = 1;
 578
 579						switch(header.Mode) {
 580							case MPEG_MODE_STEREO:
 581							case MPEG_MODE_DUAL_CHANNEL:
 582								wf.numChannels = 2;
 583								break;
 584
 585							case MPEG_MODE_SINGLE_CHANNEL:
 586								wf.numChannels = 1;
 587								break;
 588
 589							case MPEG_MODE_JOINT_STEREO:
 590								wf.numChannels = 2;
 591								break;
 592
 593							default: // impossible!
 594								return StreamData.Invalid;
 595						}
 596
 597
 598						wf.averageBytesPerSecond = wf.samplesPerSecond * 2 * wf.numChannels;
 599						wf.blockAlign = 2 * wf.numChannels;
 600						wf.bitsPerSample = 16;
 601
 602						// set the wavelet's audio format
 603						if (toBuffer !is null) {
 604							toBuffer.setAudioFormat(wf);
 605							bufferTime = toBuffer.time;
 606						}
 607
 608						if (header.Protected == 0) {
 609							decoderState = MP3_READ_CRC;
 610						}
 611						else {
 612							decoderState = MP3_READ_AUDIO_DATA;
 613						}
 614						
 615						if (!accepted) {
 616							if (toBuffer !is null) {
 617								if (toBuffer.length() != bufferSize) {
 618									//Console.putln("resize ", bufferSize, " from ", toBuffer.length());
 619									//toBuffer.resize(bufferSize);
 620									//Console.putln("resize ", bufferSize, " from ", toBuffer.length());
 621								}
 622								toBuffer.rewind();
 623							}
 624
 625							if (toBuffer is null && isSeek == false) {
 626								decoderState = MP3_READ_AUDIO_DATA_PREAMBLE;
 627								return StreamData.Accepted;
 628							}
 629						}
 630
 631						accepted = true;
 632
 633						continue;
 634					}
 635					else {
 636						Console.putln("cur test ", mpeg_header & MPEG_SYNC_BITS, " @ ", stream.position - 4);
 637						ubyte curByte;
 638
 639						// test 15K worth
 640						syncAmount++;
 641
 642						if (syncAmount == 1024*15) {
 643							return StreamData.Invalid;
 644						}
 645
 646						if (!stream.read(curByte)) {
 647							return StreamData.Required;
 648						}
 649
 650						mpeg_header <<= 8;
 651						mpeg_header |= (cast(uint)curByte);
 652					}
 653
 654					continue;
 655
 656				case MP3_READ_CRC:
 657
 658					if (!stream.read(crc)) {
 659						return StreamData.Required;
 660					}
 661
 662					decoderState = MP3_READ_AUDIO_DATA;
 663
 664					continue;
 665				
 666				case MP3_READ_AUDIO_DATA_PREAMBLE:
 667				
 668					if (toBuffer !is null) {
 669						samplesLeft = cast(int)(toBuffer.length() / 1728) * 1728;
 670						samplesLeft += 1728;
 671						bufferSize = samplesLeft;
 672					}
 673
 674					decoderState = MP3_READ_AUDIO_DATA;
 675
 676					/* FOLLOW THROUGH */
 677
 678				case MP3_READ_AUDIO_DATA:
 679				//	Console.putln("pos: ", new String("%x", stream.position));
 680
 681					// curByte is currently at the end of the last frame (supposedly)
 682					// main_data_end depicts the end of the data frame
 683
 684					curByte = audioData.length - bufferLength;
 685					curPos = 0;
 686
 687					switch(header.Mode) {
 688						case MPEG_MODE_STEREO:
 689						case MPEG_MODE_DUAL_CHANNEL:
 690							channels = 2;
 691							decoderState = MP3_READ_AUDIO_DATA_SINGLE_CHANNEL;
 692							break;
 693
 694						case MPEG_MODE_SINGLE_CHANNEL:
 695							channels = 1;
 696							decoderState = MP3_READ_AUDIO_DATA_SINGLE_CHANNEL;
 697							break;
 698
 699						case MPEG_MODE_JOINT_STEREO:
 700							channels = 2;
 701							decoderState = MP3_READ_AUDIO_DATA_SINGLE_CHANNEL;
 702							break;
 703
 704						default: // impossible!
 705							return StreamData.Invalid;
 706					}
 707
 708					continue;
 709
 710				case MP3_READ_AUDIO_DATA_SINGLE_CHANNEL:
 711
 712					// Read in enough data for decoding a buffer
 713					audioHeaderLength = 32;
 714
 715					if (channels == 1) { audioHeaderLength = 17; }
 716
 717					//Console.putln("reading ", audioHeaderLength, " info header buffer");
 718
 719					// read in the side info
 720					if (!stream.read(audioHeader.ptr, audioHeaderLength)) {
 721						return StreamData.Required;
 722					}
 723					
 724					// reset bit stream
 725					audioRef = audioHeader;
 726					audioRefLength = audioHeader.length;
 727					curByte = 0;
 728					curPos = 0;
 729
 730					//Console.putln(audioRefLength, " <--- header length");
 731
 732					// The reading of side info
 733
 734					main_data_begin = readBits(9);	// actually main_data_end in the spec,
 735													// but that makes no sense in this context
 736
 737					if (channels == 1) {
 738						readBits(5); // ignore private_bits
 739					}
 740					else {
 741						readBits(3); // ignore private_bits
 742					}
 743
 744					for(uint ch = 0; ch < channels; ch++) {
 745						for(uint scfsi_band = 0; scfsi_band < 4; scfsi_band++) {
 746							scfsi[scfsi_band][ch] = readBits(1);
 747						}
 748					}
 749
 750					// 18 or 16 bits read
 751
 752					for(uint gr=0; gr < 2; gr++) {
 753						for(uint ch = 0; ch < channels; ch++) {
 754
 755							part2_3_length[gr][ch] = readBits(12);
 756							big_values[gr][ch] = readBits(9);
 757							global_gain[gr][ch] = readBits(8);
 758							scalefac_compress[gr][ch] = readBits(4);
 759							blocksplit_flag[gr][ch] = readBits(1);
 760
 761							slen1[gr][ch] = slen1_interpret[scalefac_compress[gr][ch]];
 762							slen2[gr][ch] = slen2_interpret[scalefac_compress[gr][ch]];
 763
 764							if (blocksplit_flag[gr][ch]) {
 765								block_type[gr][ch] = readBits(2);
 766								switch_point[gr][ch] = readBits(1);
 767								for (uint region = 0; region < 2; region++) {
 768									table_select[region][gr][ch] = readBits(5);
 769								}
 770
 771								// window -- Number of actual time slot in case of
 772								// block_type == 2, 0 = window = 2.
 773
 774								for (uint window = 0; window < 3; window++) {
 775									subblock_gain[window][gr][ch] = readBits(3);
 776								}
 777
 778								if (block_type[gr][ch] == 2 && switch_point[gr][ch] == 0) {
 779									region_address1[gr][ch] = 8;
 780								}
 781								else {
 782									region_address1[gr][ch] = 7;
 783								}
 784
 785								region_address2[gr][ch] = 20 - region_address1[gr][ch];
 786
 787								if (switch_point[gr][ch] == 1) {
 788									switch_point_l[gr][ch] = 8;
 789									switch_point_s[gr][ch] = 3;
 790								}
 791								else {
 792									switch_point_l[gr][ch] = 0;
 793									switch_point_s[gr][ch] = 0;
 794								}
 795							}
 796							else {
 797								block_type[gr][ch] = 0;
 798
 799								for (uint region = 0; region < 3; region++) {
 800									table_select[region][gr][ch] = readBits(5);
 801								}
 802
 803								region_address1[gr][ch] = readBits(4);
 804								region_address2[gr][ch] = readBits(3);
 805
 806								switch_point[gr][ch] = 0;
 807								switch_point_l[gr][ch] = 0;
 808								switch_point_s[gr][ch] = 0;
 809							}
 810
 811							preflag[gr][ch] = readBits(1);
 812							scalefac_scale[gr][ch] = readBits(1);
 813							count1table_select[gr][ch] = readBits(1);
 814						}
 815					}
 816
 817					bufferLength -= audioHeaderLength;
 818
 819					//Console.putln("Audio Data Length: ", bufferLength);
 820
 821					// append the buffer
 822					audioData ~= new ubyte[bufferLength];
 823
 824					/* followed by main data (at main_data_end... not immediately following) */
 825
 826					decoderState = MP3_READ_AUDIO_DATA_SCALE_FACTORS;
 827
 828				case MP3_READ_AUDIO_DATA_SCALE_FACTORS:
 829
 830					//Console.putln("reading ", bufferLength, " info decode buffer");
 831
 832					// read in the data
 833					if (!stream.read(&audioData[$ - bufferLength], bufferLength)) {
 834						return StreamData.Required;
 835					}
 836
 837					// reset bit stream
 838					curByte = audioData.length;
 839					curByte -= bufferLength;
 840					curByte -= main_data_begin;
 841
 842					main_data_begin = curByte;
 843
 844					//Console.putln(curByte, " start of read");
 845
 846					audioRefLength = audioData.length;
 847					audioRef = audioData;
 848
 849					curPos = 0;
 850
 851					bool output = false;
 852
 853					for (uint gr = 0; gr < 2; gr++) {
 854						//Console.putln("gr ", gr);
 855						for (uint ch = 0; ch < channels; ch++) {
 856
 857							part2_length = (curByte * 8) + curPos;
 858
 859							// Read the scalefactors for this granule
 860							readScalefactors(gr, ch);
 861
 862							part2_length = ((curByte * 8) + curPos) - part2_length;
 863
 864							// Decode the current huffman data
 865							decodeHuffman(gr, ch);
 866
 867							// Requantize
 868							requantizeSample(gr, ch);
 869							// ro[ch] == quantizedData[ch]
 870							for (uint sb = 0; sb < SBLIMIT; sb++) {
 871								for (uint ss = 0; ss < SSLIMIT; ss++) {
 872									//printf("%f\n", quantizedData[ch][sb][ss]);
 873								}
 874							}
 875						}
 876
 877						// Account for a mode switch from intensity stereo to MS_stereo
 878						normalizeStereo(gr);
 879						for (uint ch = 0; ch < channels; ch++) {
 880							for (uint sb = 0; sb < SBLIMIT; sb++) {
 881								for (uint ss = 0; ss < SSLIMIT; ss++) {
 882									//if (normalizedData[ch][sb][ss] > 0.0) {
 883									//	printf("%f\n", normalizedData[ch][sb][ss]);
 884									//}
 885								}
 886							}
 887						}
 888
 889						for (uint ch = 0; ch < channels; ch++) {
 890							// Reorder the short blocks
 891							reorder(gr, ch);
 892							for (uint sb = 0; sb < SBLIMIT; sb++) {
 893								for (uint ss = 0; ss < SSLIMIT; ss++) {
 894									//if (reorderedData[sb][ss] > 0.0) {
 895										//printf("%f\n", reorderedData[sb][ss]);
 896									//}
 897								}
 898							}
 899
 900							// Perform anti-alias pass on subband butterflies
 901							antialias(gr, ch);
 902							for (uint sb = 0; sb < SBLIMIT; sb++) {
 903								for (uint ss = 0; ss < SSLIMIT; ss++) {
 904								//	if (hybridData[sb][ss] > 0.0) {
 905										//printf("%f\n", hybridData[sb][ss]);
 906								//	}
 907								}
 908							}
 909
 910							// Perform hybrid synthesis pass
 911							for (uint sb; sb < SBLIMIT; sb++) {
 912								hybridSynthesis(gr, ch, sb);
 913							}
 914
 915							// Multiply every second subband's every second input by -1
 916							// To correct for frequency inversion of the polyphase filterbank
 917							for (uint sb; sb < SBLIMIT; sb++) {
 918								for (uint ss; ss < SSLIMIT; ss++) {
 919									if (((ss % 2) == 1) && ((sb % 2) == 1)) {
 920										polysynthData[ch][sb][ss] = -polysynthData[ch][sb][ss];
 921									}
 922								}
 923							}
 924
 925							for (uint sb = 0; sb < SBLIMIT; sb++) {
 926								for (uint ss = 0; ss < SSLIMIT; ss++) {
 927									//if (polysynthData[ch][sb][ss] > 0.0) {
 928									//	printf("%f\n", polysynthData[ch][sb][ss]);
 929									//}
 930								}
 931							}
 932						}
 933
 934						// Polyphase Synthesis
 935						//Console.putln("polyphase");
 936						for (uint ss; ss < 18; ss++) {
 937							polyphaseSynthesis(gr, ss, toBuffer);
 938						}
 939						//Console.putln("polyphase!");
 940					}
 941
 942					samplesLeft -= (3*18*32*channels);
 943
 944					if (samplesLeft <= 0) {
 945						decoderState = MP3_BUFFER_AUDIO;
 946						curTime += bufferTime;
 947							//curTime.toString();
 948						return StreamData.Accepted; /*
 949					toBuffer.rewind();
 950						continue; //*/
 951					}
 952
 953					//Console.putln(curByte, " end of read");
 954					//Console.putln(curByte - main_data_begin, " read");
 955
 956					main_data_end = curByte+1;
 957
 958					/* followed by huffman encoded data */
 959
 960					decoderState = MP3_READ_HEADER;
 961					continue;
 962
 963				case MP3_READ_AUDIO_DATA_JOINT_STEREO:
 964					continue;
 965
 966				default:
 967					break;
 968			}
 969			break;
 970		}
 971		return StreamData.Invalid;
 972	}
 973
 974protected:
 975
 976	void readScalefactors(uint gr, uint ch) {
 977		if (blocksplit_flag[gr][ch] == 1 && block_type[gr][ch] == 2) {
 978			if (switch_point[gr][ch] == 0) {
 979
 980				// Decoding scalefactors for a short window.
 981
 982            	for (uint cb = 0; cb < 6; cb++) {
 983            		for (uint window = 0; window < 3; window++) {
 984						scalefac[gr][ch].short_window[cb][window] = readBits(slen1[gr][ch]);
 985            		}
 986            	}
 987
 988            	for (uint cb = 6; cb < cb_limit_short; cb++) {
 989            		for (uint window = 0; window < 3; window++) {
 990						scalefac[gr][ch].short_window[cb][window] = readBits(slen2[gr][ch]);
 991            		}
 992            	}
 993
 994            	for (uint window = 0; window < 3; window++) {
 995            		scalefac[gr][ch].short_window[12][window] = 0;
 996            	}
 997			}
 998			else {
 999
1000				// Decoding scalefactors for a long window with a switch point to short.
1001
1002				for (uint cb = 0; cb < 8; cb++) {
1003					if ((scfsi[cb][ch] == 0) || (gr == 0)) {
1004						scalefac[gr][ch].long_window[cb] = readBits(slen1[gr][ch]);
1005					}
1006				}
1007
1008				for (uint cb = 3; cb < 6; cb++) {
1009					for (uint window = 0; window < 3; window++) {
1010						if ((scfsi[cb][ch] == 0) || (gr == 0)) {
1011							scalefac[gr][ch].short_window[cb][window] = readBits(slen1[gr][ch]);
1012						}
1013					}
1014				}
1015
1016				for (uint cb = 6; cb < cb_limit_short; cb++) {
1017					for (uint window = 0; window < 3; window++) {
1018						if ((scfsi[cb][ch] == 0) || (gr == 0)) {
1019							scalefac[gr][ch].short_window[cb][window] = readBits(slen2[gr][ch]);
1020						}
1021					}
1022				}
1023
1024				for (uint window = 0; window < 3; window++) {
1025					if ((scfsi[cb_limit_short][ch] == 0) || (gr == 0)) {
1026						scalefac[gr][ch].short_window[cb_limit_short][window] = 0;
1027					}
1028				}
1029			}
1030		}
1031		else {
1032
1033			// The block_type cannot be 2 in this block (so, it must be block 0, 1, or 3).
1034
1035			// Decoding the scalefactors for a long window
1036
1037			if ((scfsi[0][ch] == 0) || (gr == 0)) {
1038        		for (uint cb = 0; cb < 6; cb++) {
1039					scalefac[gr][ch].long_window[cb] = readBits(slen1[gr][ch]);
1040        		}
1041			}
1042
1043			if ((scfsi[1][ch] == 0) || (gr == 0)) {
1044        		for (uint cb = 6; cb < 11; cb++) {
1045					scalefac[gr][ch].long_window[cb] = readBits(slen1[gr][ch]);
1046        		}
1047			}
1048
1049			if ((scfsi[2][ch] == 0) || (gr == 0)) {
1050        		for (uint cb = 11; cb < 16; cb++) {
1051					scalefac[gr][ch].long_window[cb] = readBits(slen2[gr][ch]);
1052        		}
1053			}
1054
1055			if ((scfsi[3][ch] == 0) || (gr == 0)) {
1056        		for (uint cb = 16; cb < 21; cb++) {
1057					scalefac[gr][ch].long_window[cb] = readBits(slen2[gr][ch]);
1058        		}
1059			}
1060
1061			// (The reference implementation does nothing with subband 21)
1062
1063			// We fill it with a high negative integer:
1064			scalefac[gr][ch].long_window[21] = -858993460;
1065
1066			scalefac[gr][ch].long_window[22] = 0;
1067		}
1068	}
1069
1070	const auto SBLIMIT = 32;
1071	const auto SSLIMIT = 18;
1072
1073	// Decoded Huffman Data -- is(i) in the spec
1074	int[SSLIMIT][SBLIMIT] codedData;
1075
1076	// Requantizated Data -- xr(i) in the spec
1077	double[SSLIMIT][SBLIMIT][2] quantizedData;
1078
1079	// Normalized Data -- lr(i)
1080	double[SSLIMIT][SBLIMIT][2] normalizedData;
1081
1082	// reordered data -- re(i)
1083	double[SSLIMIT][SBLIMIT] reorderedData;
1084
1085	// anti-aliased hybrid synthesis data -- hybridIn
1086	double[SSLIMIT][SBLIMIT] hybridData;
1087
1088	// data for the polysynth phase -- hybridOut
1089	double[SSLIMIT][SBLIMIT][2] polysynthData;
1090
1091	void decodeHuffman(uint gr, uint ch) {
1092		// part2_3_length is the length of all of the data
1093		// (huffman + scalefactors). part2_length is just
1094		// the scalefactors by themselves.
1095
1096		// Note: SSLIMIT * SBLIMIT = 32 * 18 = 576
1097
1098//		Console.putln("-=-=-=-");
1099
1100		static const auto max_table_entry = 15;
1101
1102		uint region1Start;
1103		uint region2Start;
1104
1105		if (blocksplit_flag[gr][ch] == 1 && block_type[gr][ch] == 2) {
1106			// Short Blocks
1107			region1Start = 36;
1108			region2Start = 576; // There isn't a region 2 for short blocks
1109		}
1110		else {
1111			// Long Blocks
1112			region1Start = sfindex_long[header.SamplingFrequency][region_address1[gr][ch] + 1];
1113			region2Start = sfindex_long[header.SamplingFrequency][region_address1[gr][ch] + region_address2[gr][ch] + 2];
1114		}
1115		
1116		uint maxBand = big_values[gr][ch] * 2;
1117
1118//		Console.putln(region1Start, " to ", region2Start);
1119
1120		if (region1Start > maxBand) { region1Start = maxBand; }
1121		if (region2Start > maxBand) { region2Start = maxBand; }
1122
1123		uint freqIndex;
1124
1125		uint pos = curByte;
1126		uint posbit = curPos;
1127
1128		// The number of bits used for the huffman data
1129 		uint huffmanLength = (part2_3_length[gr][ch] - part2_length);
1130
1131 		// The bit position in the stream to stop.
1132 		uint maxBit = huffmanLength + curPos + (curByte * 8);
1133
1134		// Region 0
1135		if (freqIndex < region1Start) {
1136			//Console.putln("region 0 -=-=-");
1137			initializeHuffman(0,gr,ch);
1138		}
1139
1140		for (; freqIndex < region1Start; freqIndex+=2) {
1141			int[] code = readCode();
1142			codedData[freqIndex/SSLIMIT][freqIndex%SSLIMIT] = code[0];
1143			codedData[(freqIndex+1)/SSLIMIT][(freqIndex+1)%SSLIMIT] = code[1];
1144		}
1145
1146		// Region 1
1147		if (freqIndex < region2Start) {
1148		//	Console.putln("region 1 -=-=-");
1149			initializeHuffman(1,gr,ch);
1150		}
1151
1152		for (; freqIndex < region2Start; freqIndex+=2) {
1153			int[] code = readCode();
1154			codedData[freqIndex/SSLIMIT][freqIndex%SSLIMIT] = code[0];
1155			codedData[(freqIndex+1)/SSLIMIT][(freqIndex+1)%SSLIMIT] = code[1];
1156		}
1157
1158		// Region 2
1159		if (freqIndex < maxBand) {
1160	//		Console.putln("region 2 -=-=-");
1161			initializeHuffman(2,gr,ch);
1162		}
1163
1164		for (; freqIndex < maxBand; freqIndex+=2) {
1165			int[] code = readCode();
1166			codedData[freqIndex/SSLIMIT][freqIndex%SSLIMIT] = code[0];
1167			codedData[(freqIndex+1)/SSLIMIT][(freqIndex+1)%SSLIMIT] = code[1];
1168		}
1169
1170//		Console.putln("big values decoded -=-=-");
1171
1172		// Read in Count1 Area
1173		initializeQuantizationHuffman(gr,ch);
1174
1175		for (; (curPos + (curByte * 8)) < maxBit && freqIndex < 574; freqIndex += 4) {
1176			int[4] code = readQuantizationCode();
1177			codedData[freqIndex/SSLIMIT][freqIndex%SSLIMIT] = code[0];
1178			codedData[(freqIndex+1)/SSLIMIT][(freqIndex+1)%SSLIMIT] = code[1];
1179			codedData[(freqIndex+2)/SSLIMIT][(freqIndex+2)%SSLIMIT] = code[2];
1180			codedData[(freqIndex+3)/SSLIMIT][(freqIndex+3)%SSLIMIT] = code[3];
1181		}
1182
1183		// Zero rest
1184		for (; freqIndex < 576; freqIndex++) {
1185			codedData[freqIndex/SSLIMIT][freqIndex%SSLIMIT] = 0;
1186		}
1187
1188		// Resync to the correct position
1189		// (where we started + the number of bits that would have been used)
1190		curByte = maxBit / 8;
1191		curPos = maxBit % 8;
1192	}
1193	
1194	void requantizeSample(uint gr, uint ch) {
1195		uint criticalBandBegin;
1196		uint criticalBandWidth;
1197		uint criticalBandBoundary;
1198		uint criticalBandIndex;
1199
1200		const int[22] pretab = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 3, 3, 3, 2, 0];
1201
1202		// Initialize the critical boundary information
1203		if ((blocksplit_flag[gr][ch] == 1) && (block_type[gr][ch] == 2)) {
1204			if (switch_point[gr][ch] == 0) {
1205				// Short blocks
1206				criticalBandBoundary = sfindex_short[header.SamplingFrequency][1] * 3;
1207				criticalBandWidth = sfindex_short[header.SamplingFrequency][1];
1208				criticalBandBegin = 0;
1209			}
1210			else {
1211				// Long blocks come first for switched windows
1212				criticalBandBoundary = sfindex_long[header.SamplingFrequency][1];
1213			}
1214		}
1215		else {
1216			// Long windows
1217			criticalBandBoundary = sfindex_long[header.SamplingFrequency][1];
1218		}
1219
1220		for (uint sb; sb < SBLIMIT; sb++) {
1221			for (uint ss; ss < SSLIMIT; ss++) {
1222
1223				// Get the critical band boundary
1224				if ((sb * 18) + ss == criticalBandBoundary) {
1225					if (blocksplit_flag[gr][ch] == 1 && block_type[gr][ch] == 2) {
1226						if (switch_point[gr][ch] == 0) {
1227							// Requantizing the samples for a short window.
1228							criticalBandIndex++;
1229							criticalBandBoundary = sfindex_short[header.SamplingFrequency][criticalBandIndex+1]*3;
1230							criticalBandWidth = sfindex_short[header.SamplingFrequency][criticalBandIndex + 1] - sfindex_short[header.SamplingFrequency][criticalBandIndex];
1231							criticalBandBegin = sfindex_short[header.SamplingFrequency][criticalBandIndex] * 3;
1232						}
1233						else {
1234							// Requantizing the samples for a long window that switches to short.
1235
1236							// The first two are long windows and the last two are short windows
1237							if (((sb * 18) + ss) == sfindex_long[header.SamplingFrequency][8]) {
1238								criticalBandBoundary = sfindex_short[header.SamplingFrequency][4] * 3;
1239								criticalBandIndex = 3;
1240								criticalBandWidth = sfindex_short[header.SamplingFrequency][criticalBandIndex + 1] - sfindex_short[header.SamplingFrequency][criticalBandIndex];
1241								criticalBandBegin = sfindex_short[header.SamplingFrequency][criticalBandIndex] * 3;
1242							}
1243							else if (((sb * 18) + ss) < sfindex_long[header.SamplingFrequency][8]) {
1244								criticalBandIndex++;
1245								criticalBandBoundary = sfindex_long[header.SamplingFrequency][criticalBandIndex+1];
1246							}
1247							else {
1248								criticalBandIndex++;
1249								criticalBandBoundary = sfindex_short[header.SamplingFrequency][criticalBandIndex + 1] * 3;
1250								criticalBandWidth = sfindex_short[header.SamplingFrequency][criticalBandIndex + 1] - sfindex_short[header.SamplingFrequency][criticalBandIndex];
1251								criticalBandBegin = sfindex_short[header.SamplingFrequency][criticalBandIndex] * 3;
1252							}
1253						}
1254					}
1255					else {
1256						// The block_type cannot be 2 in this block (so, it must be block 0, 1, or 3).
1257
1258						// Requantizing the samples for a long window
1259						criticalBandIndex++;
1260						criticalBandBoundary = sfindex_long[header.SamplingFrequency][criticalBandIndex+1];
1261					}
1262				}
1263
1264				// Global gain
1265				quantizedData[ch][sb][ss] = pow(2.0, (0.25 * (cast(double)global_gain[gr][ch] - 210.0)));
1266         //printf("g : %d %d: %f\n", sb,ss,quantizedData[ch][sb][ss]);
1267static bool output = false;
1268				// Perform the scaling that depends on the type of window
1269				if (blocksplit_flag[gr][ch] == 1
1270					&& (((block_type[gr][ch] == 2) && (switch_point[gr][ch] == 0))
1271					|| ((block_type[gr][ch] == 2) && (switch_point[gr][ch] == 1) && (sb >= 2)))) {
1272
1273					// Short blocks (either via block_type 2 or the last 2 bands for switched windows)
1274
1275					uint sbgainIndex = (((sb * 18) + ss) - criticalBandBegin) / criticalBandWidth;
1276
1277					// if (output) printf("%d %d\n", sbgainIndex, criticalBandIndex);
1278					quantizedData[ch][sb][ss] *= pow(2.0, 0.25 * -8.0
1279						* subblock_gain[sbgainIndex][gr][ch]);
1280					quantizedData[ch][sb][ss] *= pow(2.0, 0.25 * -2.0 * (1.0 + scalefac_scale[gr][ch])
1281						* scalefac[gr][ch].short_window[criticalBandIndex][sbgainIndex]);
1282				}
1283				else {
1284					// Long blocks (either via block_type 0, 1, or 3, or the 1st 2 bands
1285					double powExp = -0.5 * (1.0 + cast(double)scalefac_scale[gr][ch])
1286						* (cast(double)scalefac[gr][ch].long_window[criticalBandIndex]
1287						+ (cast(double)preflag[gr][ch] * cast(double)pretab[criticalBandIndex]));
1288					double powResult = pow(2.0, powExp);
1289						//if (powResult > 0.0) {
1290							//printf("r : %f\nfrom : %f\n", powResult, powExp);
1291							//printf("with : %f %d [%d, %d, %d] %f %f\n", cast(double)scalefac_scale[gr][ch], scalefac[gr][ch].long_window[criticalBandIndex], gr, ch, criticalBandIndex,
1292						//	cast(double)preflag[gr][ch], cast(double)pretab[criticalBandIndex]);
1293						//}
1294					quantizedData[ch][sb][ss] *= powResult;
1295				}
1296
1297				// Scale values
1298
1299				double powResult = pow(cast(double)abs(codedData[sb][ss]), 4.0/3.0);
1300			//	printf("%f\n", powResult);
1301
1302				quantizedData[ch][sb][ss] *= powResult;
1303				if (codedData[sb][ss] < 0) {
1304					quantizedData[ch][sb][ss] = -quantizedData[ch][sb][ss];
1305				}
1306//printf("%d %d: [%d] %.21f\n", sb,ss, codedData[sb][ss], quantizedData[ch][sb][ss]);
1307			}
1308		}
1309	}
1310
1311	void normalizeStereo(uint gr) {
1312
1313		double io;
1314
1315		if ((scalefac_compress[gr][0] % 2) == 1) {
1316			io = 0.707106781188;
1317		}
1318		else {
1319			io = 0.840896415256;
1320		}
1321
1322		short[576] decodedPos;
1323		double[576] decodedRatio;
1324		double[576][2] k;
1325
1326		int i;
1327		int sb;
1328		int ss;
1329		int ch;
1330		
1331		int scalefactorBand;
1332
1333  		// Initialize
1334  		decodedPos[0..$] = 7;
1335
1336  		bool intensityStereo = (header.Mode == MPEG_MODE_JOINT_STEREO) && (header.ModeExtension & 0x1);
1337  		bool msStereo = (header.Mode == MPEG_MODE_JOINT_STEREO) && (header.ModeExtension & 0x2);
1338  		
1339  		if ((channels == 2) && intensityStereo) {
1340			if ((blocksplit_flag[gr][ch] == 1) && (block_type[gr][ch] == 2)) {
1341				if (switch_point[gr][ch] == 0) {
1342					for (uint j = 0; j < 3; j++) {
1343						int scalefactorCount = -1;
1344
1345						for (scalefactorBand = 12; scalefactorBand >= 0; scalefactorBand--) {
1346							int lines = sfindex_short[header.SamplingFrequency][scalefactorBand + 1]
1347								- sfindex_short[header.SamplingFrequency][scalefactorBand];
1348
1349							i = 3 * sfindex_short[header.SamplingFrequency][scalefactorBand]
1350								+ ((j + 1) * lines) - 1;
1351							
1352							for (; lines > 0; lines--) {
1353								if (quantizedData[1][i/SSLIMIT][i%SSLIMIT] != 0.0) {
1354									scalefactorCount = scalefactorBand;
1355									scalefactorBand = -10;
1356									lines = -10;
1357								}
1358								i--;
1359							}
1360						}
1361
1362						scalefactorBand = scalefactorCount + 1;
1363						
1364						for (; scalefactorBand < 12; scalefactorBand++) {
1365							sb = sfindex_short[header.SamplingFrequency][scalefactorBand+1]
1366								- sfindex_short[header.SamplingFrequency][scalefactorBand];
1367
1368							i = 3 * sfindex_short[header.SamplingFrequency][scalefactorBand] + (j * sb);
1369
1370							for ( ; sb > 0; sb--) {
1371								decodedPos[i] = cast(short)scalefac[gr][1].short_window[scalefactorBand][j];
1372								if (decodedPos[i] != 7) {
1373									// IF (MPEG2) { ... }
1374									// ELSE {
1375										decodedRatio[i] = tan(cast(double)decodedPos[i] * (PI / 12));
1376									// }
1377								}
1378								i++;
1379							}
1380						}
1381
1382						sb = sfindex_short[header.SamplingFrequency][12] - sfindex_short[header.SamplingFrequency][11];
1383						scalefactorBand = (3 * sfindex_short[header.SamplingFrequency][11]) + (j * sb);
1384						sb = sfindex_short[header.SamplingFrequency][13] - sfindex_short[header.SamplingFrequency][12];
1385
1386						i = (3 * sfindex_short[header.SamplingFrequency][11]) + (j * sb);
1387
1388						for (; sb > 0; sb--) {
1389							decodedPos[i] = decodedPos[scalefactorBand];
1390							decodedRatio[i] = decodedRatio[scalefactorBand];
1391							k[0][i] = k[0][scalefactorBand];
1392							k[1][i] = k[1][scalefactorBand];
1393							i++;
1394						}
1395					}
1396				}
1397				else {
1398					int maxScalefactorBand;
1399
1400					for (uint j; j<3; j++) {
1401						int scalefactorCount = 2;
1402						for (scalefactorBand = 12; scalefactorBand >= 3; scalefactorBand--) {
1403							int lines = sfindex_short[header.SamplingFrequency][scalefactorBand+1]
1404								- sfindex_short[header.SamplingFrequency][scalefactorBand];
1405
1406							i = 3 * sfindex_short[header.SamplingFrequency][scalefactorBand]
1407								+ ((j + 1) * lines) - 1;
1408							
1409							for (; lines > 0; lines--) {
1410								if (quantizedData[1][i/SSLIMIT][i%SSLIMIT] != 0.0) {
1411									scalefactorCount = scalefactorBand;
1412									scalefactorBand = -10;
1413									lines = -10;
1414								}
1415								i--;
1416							}
1417						}
1418
1419						scalefactorBand = scalefactorCount + 1;
1420
1421						if (scalefactorBand > maxScalefactorBand) {
1422							maxScalefactorBand = scalefactorBand;
1423						}
1424						
1425						for (; scalefactorBand < 12; scalefactorBand++) {
1426							sb = sfindex_short[header.SamplingFrequency][scalefactorBand+1]
1427								- sfindex_short[header.SamplingFrequency][scalefactorBand];
1428
1429							i = 3 * sfindex_short[header.SamplingFrequency][scalefactorBand]
1430								+ (j * sb);
1431
1432							for (; sb > 0; sb--) {
1433								decodedPos[i] = cast(short)scalefac[gr][1].short_window[scalefactorBand][j];
1434								if (decodedPos[i] != 7) {
1435									// IF (MPEG2) { ... }
1436									// ELSE {
1437									decodedRatio[i] = tan(cast(double)decodedPos[i] * (PI / 12.0));
1438									// }
1439								}
1440								i++;
1441							}
1442						}
1443
1444						sb = sfindex_short[header.SamplingFrequency][12]
1445								- sfindex_short[header.SamplingFrequency][11];
1446						scalefactorBand = 3 * sfindex_short[header.SamplingFrequency][11]
1447								+ j * sb;
1448						sb = sfindex_short[header.SamplingFrequency][13]
1449								- sfindex_short[header.SamplingFrequency][12];
1450
1451						i = 3 * sfindex_short[header.SamplingFrequency][11] + j * sb;
1452						for (; sb > 0; sb--) {
1453							decodedPos[i] = decodedPos[scalefactorBand];
1454							decodedRatio[i] = decodedRatio[scalefactorBand];
1455							k[0][i] = k[0][scalefactorBand];
1456							k[1][i] = k[1][scalefactorBand];
1457							i++;
1458						}
1459					}
1460					
1461					if (maxScalefactorBand <= 3) {
1462						i = 2;
1463						ss = 17;
1464						sb = -1;
1465						while (i >= 0) {
1466							if (quantizedData[1][i][ss] != 0.0) {
1467								sb = (i * 18) + ss;
1468								i = -1;
1469							}
1470							else {
1471								ss--;
1472								if (ss < 0) {
1473									i--;
1474									ss = 17;
1475								}
1476							}
1477						}
1478
1479						i = 0;
1480
1481						while (sfindex_long[header.SamplingFrequency][i] <= sb) {
1482							i++;
1483						}
1484						
1485						scalefactorBand = i;
1486						i = sfindex_long[header.SamplingFrequency][i];
1487
1488						for (; scalefactorBand < 8; scalefactorBand++) {
1489							sb = sfindex_long[header.SamplingFrequency][scalefactorBand+1]
1490									- sfindex_long[header.SamplingFrequency][scalefactorBand];
1491							for (; sb > 0; sb--) {
1492								decodedPos[i] = cast(short)scalefac[gr][1].long_window[scalefactorBand];
1493								if (decodedPos[i] != 7) {
1494									// IF (MPEG2) { ... }
1495									// ELSE {
1496										decodedRatio[i] = tan(cast(double)decodedPos[i] * (PI / 12.0));
1497									// }
1498								}
1499								i++;
1500							}
1501						}
1502					}
1503				}
1504			}
1505			else {
1506				i = 31;
1507				ss = 17;
1508				sb = 0;
1509				
1510				while (i >= 0) {
1511					if (quantizedData[1][i][ss] != 0.0) {
1512						sb = (i * 18) + ss;
1513						i = -1;
1514					}
1515					else {
1516						ss--;
1517						if (ss < 0) {
1518							i--;
1519							ss = 17;
1520						}
1521					}
1522				}
1523				i = 0;
1524				
1525				while (sfindex_long[header.SamplingFrequency][i] <= sb) {
1526					i++;
1527				}
1528
1529				scalefactorBand = i;
1530				i = sfindex_long[header.SamplingFrequency][i];
1531
1532				for (; scalefactorBand < 21; scalefactorBand++) {
1533					sb = sfindex_long[header.SamplingFrequency][scalefactorBand+1]
1534						- sfindex_long[header.SamplingFrequency][scalefactorBand];
1535					
1536					for (; sb > 0; sb--) {
1537						decodedPos[i] = cast(short)scalefac[gr][1].long_window[scalefactorBand];
1538						if (decodedPos[i] != 7) {
1539							// IF (MPEG2) { ... }
1540							// ELSE {
1541							decodedRatio[i] = tan(cast(double)decodedPos[i] * (PI / 12.0));
1542							// }
1543						}
1544						i++;
1545					}
1546				}
1547				
1548				scalefactorBand = sfindex_long[header.SamplingFrequency][20];
1549
1550				for (sb = 576 - sfindex_long[header.SamplingFrequency][21]; sb > 0; sb--) {
1551					decodedPos[i] = decodedPos[scalefactorBand];
1552					decodedRatio[i] = decodedRatio[scalefactorBand];
1553					k[0][i] = k[0][scalefactorBand];
1554					k[1][i] = k[1][scalefactorBand];
1555					i++;
1556				}
1557			}
1558  		}
1559
1560		for (ch = 0; ch < 2; ch++) {
1561			for (sb = 0; sb < SBLIMIT; sb++) {
1562				for (ss = 0; ss < SSLIMIT; ss++) {
1563					normalizedData[ch][sb][ss] = 0;
1564				}
1565			}
1566		}
1567
1568        if (channels == 2) {
1569        	for (sb = 0; sb < SBLIMIT; sb++) {
1570        		for (ss = 0; ss < SSLIMIT; ss++) {
1571        			i = (sb * 18) + ss;
1572        			if (decodedPos[i] == 7) {
1573        				if (msStereo) {
1574        					normalizedData[0][sb][ss] = (quantizedData[0][sb][ss] + quantizedData[1][sb][ss])
1575        						/ 1.41421356;
1576        					normalizedData[1][sb][ss] = (quantizedData[0][sb][ss] - quantizedData[1][sb][ss])
1577        						/ 1.41421356;
1578        				}
1579        				else {
1580        					normalizedData[0][sb][ss] = quantizedData[0][sb][ss];
1581        					normalizedData[1][sb][ss] = quantizedData[1][sb][ss];
1582        				}
1583        			}
1584        			else if (intensityStereo) {
1585        				// IF (MPEG2) {
1586        				// normalizedData[0][sb][ss] = quantizedData[0][sb][ss] * k[0][i];
1587        				// normalizedData[1][sb][ss] = quantizedData[0][sb][ss] * k[1][i];
1588        				// }
1589        				// ELSE {
1590        				normalizedData[0][sb][ss] = quantizedData[0][sb][ss] * (decodedRatio[i] / (1 + decodedRatio[i]));
1591        				normalizedData[1][sb][ss] = quantizedData[0][sb][ss] * (1 / (1 + decodedRatio[i]));
1592        				// }
1593        			}
1594        			else {
1595        				// Error ...
1596        			}
1597        		}
1598        	}
1599        }
1600        else { // Mono
1601        	for (sb = 0; sb < SBLIMIT; sb++) {
1602        		for (ss = 0; ss < SSLIMIT; ss++) {
1603        			normalizedData[0][sb][ss] = quantizedData[0][sb][ss];
1604        		}
1605        	}
1606        }
1607	}
1608
1609	void reorder(uint gr, uint ch) {
1610		int sfreq = header.SamplingFrequency;
1611
1612		for (uint sb; sb < SBLIMIT; sb++) {
1613			for (uint ss; ss < SSLIMIT; ss++) {
1614				reorderedData[sb][ss] = 0;
1615			}
1616		}
1617
1618		if ((blocksplit_flag[gr][ch] == 1) && (block_type[gr][ch] == 2)) {
1619			if (switch_point[gr][ch] == 0) {
1620				// Recoder the short blocks
1621				uint scalefactorStart;
1622				uint scalefactorLines;
1623
1624				for (uint scalefactorBand; scalefactorBand < 13; scalefactorBand++) {
1625					scalefactorStart = sfindex_short[sfreq][scalefactorBand];
1626					scalefactorLines = sfindex_short[sfreq][scalefactorBand + 1] - scalefactorStart;
1627
1628					for (uint window; window < 3; window++) {
1629						for (uint freq; freq < scalefactorLines; freq++) {
1630							uint srcLine = (scalefactorStart * 3) + (window * scalefactorLines) + freq;
1631							uint destLine = (scalefactorStart * 3) + window + (freq * 3);
1632							reorderedData[destLine / SSLIMIT][destLine % SSLIMIT] =
1633								normalizedData[ch][srcLine / SSLIMIT][srcLine % SSLIMIT];
1634                                 //   printf("::%d %d %f\n", srcLine, destLine, reorderedData[destLine / SSLIMIT][destLine % SSLIMIT]);
1635						}
1636					}
1637				}
1638			}
1639			else {
1640				// We do not reorder the long blocks
1641				for (uint sb; sb < 2; sb++) {
1642					for (uint ss; ss < SSLIMIT; ss++) {
1643						reorderedData[sb][ss] = normalizedData[ch][sb][ss];
1644					}
1645				}
1646
1647				// We reorder the short blocks
1648				uint scalefactorStart;
1649				uint scalefactorLines;
1650
1651				for (uint scalefactorBand = 3; scalefactorBand < 13; scalefactorBand++) {
1652					scalefactorStart = sfindex_short[sfreq][scalefactorBand];
1653					scalefactorLines = sfindex_short[sfreq][scalefactorBand + 1] - scalefactorStart;
1654
1655					for (uint window; window < 3; window++) {
1656						for (uint freq; freq < scalefactorLines; freq++) {
1657							uint srcLine = (scalefactorStart * 3) + (window * scalefactorLines) + freq;
1658							uint destLine = (scalefactorStart * 3) + window + (freq * 3);
1659							reorderedData[destLine / SSLIMIT][destLine % SSLIMIT] =
1660								normalizedData[ch][srcLine / SSLIMIT][srcLine % SSLIMIT];
1661						}
1662					}
1663				}
1664			}
1665		}
1666		else {
1667			// We do not reorder long blocks
1668			for (uint sb; sb < SBLIMIT; sb++) {
1669				for (uint ss; ss < SSLIMIT; ss++) {
1670					reorderedData[sb][ss] = normalizedData[ch][sb][ss];
1671				}
1672			}
1673		}
1674	}
1675
1676	// Butterfly anti-alias
1677	void antialias(uint gr, uint ch) {
1678		uint subbandLimit = SBLIMIT - 1;
1679		
1680		// Ci[i] = [-0.6,-0.535,-0.33,-0.185,-0.095,-0.041,-0.0142,-0.0037];
1681		// cs[i] = 1.0 / (sqrt(1.0 + (Ci[i] * Ci[i])));
1682		// ca[i] = ca[i] * Ci[i];
1683
1684		const double cs[8] = [
1685			0.85749292571254418689325777610964,
1686			0.88174199731770518177557399759066,
1687			0.94962864910273289204833276115398,
1688			0.98331459249179014599030200066392,
1689			0.99551781606758576429088040422867,
1690			0.99916055817814750452934664352117,
1691			0.99989919524444704626703489425565,
1692			0.99999315507028023572010150517204
1693		];
1694
1695		const double ca[8] = [
1696			-0.5144957554275265121359546656654,
1697			-0.47173196856497227224993208871065,
1698			-0.31337745420390185437594981118049,
1699			-0.18191319961098117700820587012266,
1700			-0.09457419252642064760763363840166,
1701			-0.040965582885304047685703212384361,
1702			-0.014198568572471148056991895498421,
1703			-0.0036999746737600368721643755691364
1704		];
1705
1706		// Init our working array with quantized data
1707		for (uint sb; sb < SBLIMIT; sb++) {
1708			for (uint ss; ss < SSLIMIT; ss++) {
1709				hybridData[sb][ss] = reorderedData[sb][ss];
1710			}
1711		}
1712
1713		if ((blocksplit_flag[gr][ch] == 1) && (block_type[gr][ch] == 2) && (switch_point[gr][ch] == 0)) {
1714			return;
1715		}
1716
1717		if ((blocksplit_flag[gr][ch] == 1) && (block_type[gr][ch] == 2) && (switch_point[gr][ch] == 1)) {
1718			subbandLimit = 1;
1719		}
1720
1721		// 8 butterflies for each pair of subbands
1722		for (uint sb; sb < subbandLimit; sb++) {
1723			for (uint ss; ss < 8; ss++) {
1724				double bu = reorderedData[sb][17 - ss];
1725				double bd = reorderedData[sb + 1][ss];
1726				hybridData[sb][17 - ss] = (bu * cs[ss]) - (bd * ca[ss]);
1727				hybridData[sb + 1][ss] = (bd * cs[ss]) + (bu * ca[ss]);
1728			}
1729		}
1730	}
1731	// zerodouble initializes to 0.0 instead of nil
1732	zerodouble[SSLIMIT][SBLIMIT][2] previousBlock;
1733
1734	void hybridSynthesis(uint gr, uint ch, uint sb) {
1735
1736		int blockType = block_type[gr][ch];
1737
1738		if ((blocksplit_flag[gr][ch] == 1) && (switch_point[gr][ch] == 1) && (sb < 2)) {
1739			blockType = 0;
1740		}
1741
1742		double[36] output = inverseMDCT(hybridData[sb], blockType);
1743
1744		// Overlapping and Adding with Previous Block:
1745		// The last half gets reserved for the next block, and used in this block
1746		for (uint ss; ss < SSLIMIT; ss++) {
1747			polysynthData[ch][sb][ss] = output[ss] + previousBlock[ch][sb][ss];
1748			previousBlock[ch][sb][ss] = cast(zerodouble)output[ss+18];
1749		}
1750	}
1751
1752	double[] inverseMDCT(double[18] working, int blockType) {
1753		double[] ret = new double[36];
1754
1755		// The Constant Parts of the Windowing equations
1756
1757		const double[36][4] win = [
1758			// Block Type 0
1759			// win[i] = sin( (PI / 36) * ( i + 0.5 ) ) ; i = 0 to 35
1760			[
1761				0.043619387365336000084, 0.130526192220051573400, 0.216439613938102876070,
1762				0.300705799504273119100, 0.382683432365089781770, 0.461748613235033911190,
1763				0.537299608346823887030, 0.608761429008720655880, 0.675590207615660132130,
1764				0.737277336810123973260, 0.793353340291235165080, 0.843391445812885720550,
1765				0.887010833178221602670, 0.923879532511286738480, 0.953716950748226821580,
1766				0.976296007119933362260, 0.991444861373810382150, 0.999048221581857798230,
1767				0.999048221581857798230, 0.991444861373810382150, 0.976296007119933362260,
1768				0.953716950748226932610, 0.923879532511286738480, 0.887010833178221824720,
1769				0.843391445812885831570, 0.793353340291235165080, 0.737277336810124084280,
1770				0.675590207615660354170, 0.60876142900

Large files files are truncated, but you can click here to view the full file