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