You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

640 line
16KB

  1. /* Audio Library for Teensy 3.X
  2. * Copyright (c) 2014, Paul Stoffregen, paul@pjrc.com
  3. *
  4. * Development of this audio library was funded by PJRC.COM, LLC by sales of
  5. * Teensy and Audio Adaptor boards. Please support PJRC's efforts to develop
  6. * open source software by purchasing Teensy or other PJRC products.
  7. *
  8. * Permission is hereby granted, free of charge, to any person obtaining a copy
  9. * of this software and associated documentation files (the "Software"), to deal
  10. * in the Software without restriction, including without limitation the rights
  11. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  12. * copies of the Software, and to permit persons to whom the Software is
  13. * furnished to do so, subject to the following conditions:
  14. *
  15. * The above copyright notice, development funding notice, and this permission
  16. * notice shall be included in all copies or substantial portions of the Software.
  17. *
  18. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  19. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  20. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  21. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  22. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  23. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  24. * THE SOFTWARE.
  25. */
  26. #include <Arduino.h>
  27. #include "play_sd_wav.h"
  28. #include "spi_interrupt.h"
  29. #define STATE_DIRECT_8BIT_MONO 0 // playing mono at native sample rate
  30. #define STATE_DIRECT_8BIT_STEREO 1 // playing stereo at native sample rate
  31. #define STATE_DIRECT_16BIT_MONO 2 // playing mono at native sample rate
  32. #define STATE_DIRECT_16BIT_STEREO 3 // playing stereo at native sample rate
  33. #define STATE_CONVERT_8BIT_MONO 4 // playing mono, converting sample rate
  34. #define STATE_CONVERT_8BIT_STEREO 5 // playing stereo, converting sample rate
  35. #define STATE_CONVERT_16BIT_MONO 6 // playing mono, converting sample rate
  36. #define STATE_CONVERT_16BIT_STEREO 7 // playing stereo, converting sample rate
  37. #define STATE_PARSE1 8 // looking for 20 byte ID header
  38. #define STATE_PARSE2 9 // looking for 16 byte format header
  39. #define STATE_PARSE3 10 // looking for 8 byte data header
  40. #define STATE_PARSE4 11 // ignoring unknown chunk after "fmt "
  41. #define STATE_PARSE5 12 // ignoring unknown chunk before "fmt "
  42. #define STATE_PAUSED 13
  43. #define STATE_STOP 14
  44. void AudioPlaySdWav::begin(void)
  45. {
  46. state = STATE_STOP;
  47. state_play = STATE_STOP;
  48. data_length = 0;
  49. if (block_left) {
  50. release(block_left);
  51. block_left = NULL;
  52. }
  53. if (block_right) {
  54. release(block_right);
  55. block_right = NULL;
  56. }
  57. }
  58. bool AudioPlaySdWav::play(const char *filename)
  59. {
  60. stop();
  61. bool irq = false;
  62. if (NVIC_IS_ENABLED(IRQ_SOFTWARE)) {
  63. NVIC_DISABLE_IRQ(IRQ_SOFTWARE);
  64. irq = true;
  65. }
  66. #if defined(HAS_KINETIS_SDHC)
  67. if (!(SIM_SCGC3 & SIM_SCGC3_SDHC)) AudioStartUsingSPI();
  68. #else
  69. AudioStartUsingSPI();
  70. #endif
  71. wavfile = SD.open(filename);
  72. if (!wavfile) {
  73. #if defined(HAS_KINETIS_SDHC)
  74. if (!(SIM_SCGC3 & SIM_SCGC3_SDHC)) AudioStopUsingSPI();
  75. #else
  76. AudioStopUsingSPI();
  77. #endif
  78. if (irq) NVIC_ENABLE_IRQ(IRQ_SOFTWARE);
  79. return false;
  80. }
  81. buffer_length = 0;
  82. buffer_offset = 0;
  83. state_play = STATE_STOP;
  84. data_length = 20;
  85. header_offset = 0;
  86. state = STATE_PARSE1;
  87. if (irq) NVIC_ENABLE_IRQ(IRQ_SOFTWARE);
  88. return true;
  89. }
  90. void AudioPlaySdWav::stop(void)
  91. {
  92. bool irq = false;
  93. if (NVIC_IS_ENABLED(IRQ_SOFTWARE)) {
  94. NVIC_DISABLE_IRQ(IRQ_SOFTWARE);
  95. irq = true;
  96. }
  97. if (state != STATE_STOP) {
  98. audio_block_t *b1 = block_left;
  99. block_left = NULL;
  100. audio_block_t *b2 = block_right;
  101. block_right = NULL;
  102. state = STATE_STOP;
  103. if (b1) release(b1);
  104. if (b2) release(b2);
  105. wavfile.close();
  106. #if defined(HAS_KINETIS_SDHC)
  107. if (!(SIM_SCGC3 & SIM_SCGC3_SDHC)) AudioStopUsingSPI();
  108. #else
  109. AudioStopUsingSPI();
  110. #endif
  111. }
  112. if (irq) NVIC_ENABLE_IRQ(IRQ_SOFTWARE);
  113. }
  114. void AudioPlaySdWav::togglePlayPause(void) {
  115. // take no action if wave header is not parsed OR
  116. // state is explicitly STATE_STOP
  117. if(state_play >= 8 || state == STATE_STOP) return;
  118. // toggle back and forth between state_play and STATE_PAUSED
  119. switch(state) {
  120. case state_play:
  121. state = STATE_PAUSED
  122. break;
  123. case STATE_PAUSED:
  124. state = state_play;
  125. break;
  126. }
  127. }
  128. void AudioPlaySdWav::update(void)
  129. {
  130. int32_t n;
  131. // only update if we're playing and not paused
  132. if (state == STATE_STOP || state == STATE_PAUSED) return;
  133. // allocate the audio blocks to transmit
  134. block_left = allocate();
  135. if (block_left == NULL) return;
  136. if (state < 8 && (state & 1) == 1) {
  137. // if we're playing stereo, allocate another
  138. // block for the right channel output
  139. block_right = allocate();
  140. if (block_right == NULL) {
  141. release(block_left);
  142. return;
  143. }
  144. } else {
  145. // if we're playing mono or just parsing
  146. // the WAV file header, no right-side block
  147. block_right = NULL;
  148. }
  149. block_offset = 0;
  150. //Serial.println("update");
  151. // is there buffered data?
  152. n = buffer_length - buffer_offset;
  153. if (n > 0) {
  154. // we have buffered data
  155. if (consume(n)) return; // it was enough to transmit audio
  156. }
  157. // we only get to this point when buffer[512] is empty
  158. if (state != STATE_STOP && wavfile.available()) {
  159. // we can read more data from the file...
  160. readagain:
  161. buffer_length = wavfile.read(buffer, 512);
  162. if (buffer_length == 0) goto end;
  163. buffer_offset = 0;
  164. bool parsing = (state >= 8);
  165. bool txok = consume(buffer_length);
  166. if (txok) {
  167. if (state != STATE_STOP) return;
  168. } else {
  169. if (state != STATE_STOP) {
  170. if (parsing && state < 8) goto readagain;
  171. else goto cleanup;
  172. }
  173. }
  174. }
  175. end: // end of file reached or other reason to stop
  176. wavfile.close();
  177. #if defined(HAS_KINETIS_SDHC)
  178. if (!(SIM_SCGC3 & SIM_SCGC3_SDHC)) AudioStopUsingSPI();
  179. #else
  180. AudioStopUsingSPI();
  181. #endif
  182. state_play = STATE_STOP;
  183. state = STATE_STOP;
  184. cleanup:
  185. if (block_left) {
  186. if (block_offset > 0) {
  187. for (uint32_t i=block_offset; i < AUDIO_BLOCK_SAMPLES; i++) {
  188. block_left->data[i] = 0;
  189. }
  190. transmit(block_left, 0);
  191. if (state < 8 && (state & 1) == 0) {
  192. transmit(block_left, 1);
  193. }
  194. }
  195. release(block_left);
  196. block_left = NULL;
  197. }
  198. if (block_right) {
  199. if (block_offset > 0) {
  200. for (uint32_t i=block_offset; i < AUDIO_BLOCK_SAMPLES; i++) {
  201. block_right->data[i] = 0;
  202. }
  203. transmit(block_right, 1);
  204. }
  205. release(block_right);
  206. block_right = NULL;
  207. }
  208. }
  209. // https://ccrma.stanford.edu/courses/422/projects/WaveFormat/
  210. // Consume already buffered data. Returns true if audio transmitted.
  211. bool AudioPlaySdWav::consume(uint32_t size)
  212. {
  213. uint32_t len;
  214. uint8_t lsb, msb;
  215. const uint8_t *p;
  216. p = buffer + buffer_offset;
  217. start:
  218. if (size == 0) return false;
  219. #if 0
  220. Serial.print("AudioPlaySdWav consume, ");
  221. Serial.print("size = ");
  222. Serial.print(size);
  223. Serial.print(", buffer_offset = ");
  224. Serial.print(buffer_offset);
  225. Serial.print(", data_length = ");
  226. Serial.print(data_length);
  227. Serial.print(", space = ");
  228. Serial.print((AUDIO_BLOCK_SAMPLES - block_offset) * 2);
  229. Serial.print(", state = ");
  230. Serial.println(state);
  231. #endif
  232. switch (state) {
  233. // parse wav file header, is this really a .wav file?
  234. case STATE_PARSE1:
  235. len = data_length;
  236. if (size < len) len = size;
  237. memcpy((uint8_t *)header + header_offset, p, len);
  238. header_offset += len;
  239. buffer_offset += len;
  240. data_length -= len;
  241. if (data_length > 0) return false;
  242. // parse the header...
  243. if (header[0] == 0x46464952 && header[2] == 0x45564157) {
  244. //Serial.println("is wav file");
  245. if (header[3] == 0x20746D66) {
  246. // "fmt " header
  247. if (header[4] < 16) {
  248. // WAV "fmt " info must be at least 16 bytes
  249. break;
  250. }
  251. if (header[4] > sizeof(header)) {
  252. // if such .wav files exist, increasing the
  253. // size of header[] should accomodate them...
  254. //Serial.println("WAVEFORMATEXTENSIBLE too long");
  255. break;
  256. }
  257. //Serial.println("header ok");
  258. header_offset = 0;
  259. state = STATE_PARSE2;
  260. } else {
  261. // first chuck is something other than "fmt "
  262. //Serial.print("skipping \"");
  263. //Serial.printf("\" (%08X), ", __builtin_bswap32(header[3]));
  264. //Serial.print(header[4]);
  265. //Serial.println(" bytes");
  266. header_offset = 12;
  267. state = STATE_PARSE5;
  268. }
  269. p += len;
  270. size -= len;
  271. data_length = header[4];
  272. goto start;
  273. }
  274. //Serial.println("unknown WAV header");
  275. break;
  276. // check & extract key audio parameters
  277. case STATE_PARSE2:
  278. len = data_length;
  279. if (size < len) len = size;
  280. memcpy((uint8_t *)header + header_offset, p, len);
  281. header_offset += len;
  282. buffer_offset += len;
  283. data_length -= len;
  284. if (data_length > 0) return false;
  285. if (parse_format()) {
  286. //Serial.println("audio format ok");
  287. p += len;
  288. size -= len;
  289. data_length = 8;
  290. header_offset = 0;
  291. state = STATE_PARSE3;
  292. goto start;
  293. }
  294. //Serial.println("unknown audio format");
  295. break;
  296. // find the data chunk
  297. case STATE_PARSE3: // 10
  298. len = data_length;
  299. if (size < len) len = size;
  300. memcpy((uint8_t *)header + header_offset, p, len);
  301. header_offset += len;
  302. buffer_offset += len;
  303. data_length -= len;
  304. if (data_length > 0) return false;
  305. //Serial.print("chunk id = ");
  306. //Serial.print(header[0], HEX);
  307. //Serial.print(", length = ");
  308. //Serial.println(header[1]);
  309. p += len;
  310. size -= len;
  311. data_length = header[1];
  312. if (header[0] == 0x61746164) {
  313. //Serial.print("wav: found data chunk, len=");
  314. //Serial.println(data_length);
  315. // TODO: verify offset in file is an even number
  316. // as required by WAV format. abort if odd. Code
  317. // below will depend upon this and fail if not even.
  318. leftover_bytes = 0;
  319. state = state_play;
  320. if (state & 1) {
  321. // if we're going to start stereo
  322. // better allocate another output block
  323. block_right = allocate();
  324. if (!block_right) return false;
  325. }
  326. total_length = data_length;
  327. } else {
  328. state = STATE_PARSE4;
  329. }
  330. goto start;
  331. // ignore any extra unknown chunks (title & artist info)
  332. case STATE_PARSE4: // 11
  333. if (size < data_length) {
  334. data_length -= size;
  335. buffer_offset += size;
  336. return false;
  337. }
  338. p += data_length;
  339. size -= data_length;
  340. buffer_offset += data_length;
  341. data_length = 8;
  342. header_offset = 0;
  343. state = STATE_PARSE3;
  344. //Serial.println("consumed unknown chunk");
  345. goto start;
  346. // skip past "junk" data before "fmt " header
  347. case STATE_PARSE5:
  348. len = data_length;
  349. if (size < len) len = size;
  350. buffer_offset += len;
  351. data_length -= len;
  352. if (data_length > 0) return false;
  353. p += len;
  354. size -= len;
  355. data_length = 8;
  356. state = STATE_PARSE1;
  357. goto start;
  358. // playing mono at native sample rate
  359. case STATE_DIRECT_8BIT_MONO:
  360. return false;
  361. // playing stereo at native sample rate
  362. case STATE_DIRECT_8BIT_STEREO:
  363. return false;
  364. // playing mono at native sample rate
  365. case STATE_DIRECT_16BIT_MONO:
  366. if (size > data_length) size = data_length;
  367. data_length -= size;
  368. while (1) {
  369. lsb = *p++;
  370. msb = *p++;
  371. size -= 2;
  372. block_left->data[block_offset++] = (msb << 8) | lsb;
  373. if (block_offset >= AUDIO_BLOCK_SAMPLES) {
  374. transmit(block_left, 0);
  375. transmit(block_left, 1);
  376. release(block_left);
  377. block_left = NULL;
  378. data_length += size;
  379. buffer_offset = p - buffer;
  380. if (block_right) release(block_right);
  381. if (data_length == 0) state = STATE_STOP;
  382. return true;
  383. }
  384. if (size == 0) {
  385. if (data_length == 0) break;
  386. return false;
  387. }
  388. }
  389. //Serial.println("end of file reached");
  390. // end of file reached
  391. if (block_offset > 0) {
  392. // TODO: fill remainder of last block with zero and transmit
  393. }
  394. state = STATE_STOP;
  395. return false;
  396. // playing stereo at native sample rate
  397. case STATE_DIRECT_16BIT_STEREO:
  398. if (size > data_length) size = data_length;
  399. data_length -= size;
  400. if (leftover_bytes) {
  401. block_left->data[block_offset] = header[0];
  402. //PAH fix problem with left+right channels being swapped
  403. leftover_bytes = 0;
  404. goto right16;
  405. }
  406. while (1) {
  407. lsb = *p++;
  408. msb = *p++;
  409. size -= 2;
  410. if (size == 0) {
  411. if (data_length == 0) break;
  412. header[0] = (msb << 8) | lsb;
  413. leftover_bytes = 2;
  414. return false;
  415. }
  416. block_left->data[block_offset] = (msb << 8) | lsb;
  417. right16:
  418. lsb = *p++;
  419. msb = *p++;
  420. size -= 2;
  421. block_right->data[block_offset++] = (msb << 8) | lsb;
  422. if (block_offset >= AUDIO_BLOCK_SAMPLES) {
  423. transmit(block_left, 0);
  424. release(block_left);
  425. block_left = NULL;
  426. transmit(block_right, 1);
  427. release(block_right);
  428. block_right = NULL;
  429. data_length += size;
  430. buffer_offset = p - buffer;
  431. if (data_length == 0) state = STATE_STOP;
  432. return true;
  433. }
  434. if (size == 0) {
  435. if (data_length == 0) break;
  436. leftover_bytes = 0;
  437. return false;
  438. }
  439. }
  440. // end of file reached
  441. if (block_offset > 0) {
  442. // TODO: fill remainder of last block with zero and transmit
  443. }
  444. state = STATE_STOP;
  445. return false;
  446. // playing mono, converting sample rate
  447. case STATE_CONVERT_8BIT_MONO :
  448. return false;
  449. // playing stereo, converting sample rate
  450. case STATE_CONVERT_8BIT_STEREO:
  451. return false;
  452. // playing mono, converting sample rate
  453. case STATE_CONVERT_16BIT_MONO:
  454. return false;
  455. // playing stereo, converting sample rate
  456. case STATE_CONVERT_16BIT_STEREO:
  457. return false;
  458. // ignore any extra data after playing
  459. // or anything following any error
  460. case STATE_STOP:
  461. return false;
  462. // this is not supposed to happen!
  463. //default:
  464. //Serial.println("AudioPlaySdWav, unknown state");
  465. }
  466. state_play = STATE_STOP;
  467. state = STATE_STOP;
  468. return false;
  469. }
  470. /*
  471. 00000000 52494646 66EA6903 57415645 666D7420 RIFFf.i.WAVEfmt
  472. 00000010 10000000 01000200 44AC0000 10B10200 ........D.......
  473. 00000020 04001000 4C495354 3A000000 494E464F ....LIST:...INFO
  474. 00000030 494E414D 14000000 49205761 6E742054 INAM....I Want T
  475. 00000040 6F20436F 6D65204F 76657200 49415254 o Come Over.IART
  476. 00000050 12000000 4D656C69 73736120 45746865 ....Melissa Ethe
  477. 00000060 72696467 65006461 746100EA 69030100 ridge.data..i...
  478. 00000070 FEFF0300 FCFF0400 FDFF0200 0000FEFF ................
  479. 00000080 0300FDFF 0200FFFF 00000100 FEFF0300 ................
  480. 00000090 FDFF0300 FDFF0200 FFFF0100 0000FFFF ................
  481. */
  482. // SD library on Teensy3 at 96 MHz
  483. // 256 byte chunks, speed is 443272 bytes/sec
  484. // 512 byte chunks, speed is 468023 bytes/sec
  485. #define B2M_44100 (uint32_t)((double)4294967296000.0 / AUDIO_SAMPLE_RATE_EXACT) // 97352592
  486. #define B2M_22050 (uint32_t)((double)4294967296000.0 / AUDIO_SAMPLE_RATE_EXACT * 2.0)
  487. #define B2M_11025 (uint32_t)((double)4294967296000.0 / AUDIO_SAMPLE_RATE_EXACT * 4.0)
  488. bool AudioPlaySdWav::parse_format(void)
  489. {
  490. uint8_t num = 0;
  491. uint16_t format;
  492. uint16_t channels;
  493. uint32_t rate, b2m;
  494. uint16_t bits;
  495. format = header[0];
  496. //Serial.print(" format = ");
  497. //Serial.println(format);
  498. if (format != 1) return false;
  499. rate = header[1];
  500. //Serial.print(" rate = ");
  501. //Serial.println(rate);
  502. if (rate == 44100) {
  503. b2m = B2M_44100;
  504. } else if (rate == 22050) {
  505. b2m = B2M_22050;
  506. num |= 4;
  507. } else if (rate == 11025) {
  508. b2m = B2M_11025;
  509. num |= 4;
  510. } else {
  511. return false;
  512. }
  513. channels = header[0] >> 16;
  514. //Serial.print(" channels = ");
  515. //Serial.println(channels);
  516. if (channels == 1) {
  517. } else if (channels == 2) {
  518. b2m >>= 1;
  519. num |= 1;
  520. } else {
  521. return false;
  522. }
  523. bits = header[3] >> 16;
  524. //Serial.print(" bits = ");
  525. //Serial.println(bits);
  526. if (bits == 8) {
  527. } else if (bits == 16) {
  528. b2m >>= 1;
  529. num |= 2;
  530. } else {
  531. return false;
  532. }
  533. bytes2millis = b2m;
  534. //Serial.print(" bytes2millis = ");
  535. //Serial.println(b2m);
  536. // we're not checking the byte rate and block align fields
  537. // if they're not the expected values, all we could do is
  538. // return false. Do any real wav files have unexpected
  539. // values in these other fields?
  540. state_play = num;
  541. return true;
  542. }
  543. bool AudioPlaySdWav::isPlaying(void)
  544. {
  545. uint8_t s = *(volatile uint8_t *)&state;
  546. return (s < 8);
  547. }
  548. bool AudioPlaySdWav::isPaused(void)
  549. {
  550. uint8_t s = *(volatile uint8_t *)&state;
  551. return (s == STATE_PAUSED);
  552. }
  553. bool AudioPlaySdWav::isStopped(void)
  554. {
  555. uint8_t s = *(volatile uint8_t *)&state;
  556. return (s == STATE_STOP);
  557. }
  558. uint32_t AudioPlaySdWav::positionMillis(void)
  559. {
  560. uint8_t s = *(volatile uint8_t *)&state;
  561. if (s >= 8) return 0;
  562. uint32_t tlength = *(volatile uint32_t *)&total_length;
  563. uint32_t dlength = *(volatile uint32_t *)&data_length;
  564. uint32_t offset = tlength - dlength;
  565. uint32_t b2m = *(volatile uint32_t *)&bytes2millis;
  566. return ((uint64_t)offset * b2m) >> 32;
  567. }
  568. uint32_t AudioPlaySdWav::lengthMillis(void)
  569. {
  570. uint8_t s = *(volatile uint8_t *)&state;
  571. if (s >= 8) return 0;
  572. uint32_t tlength = *(volatile uint32_t *)&total_length;
  573. uint32_t b2m = *(volatile uint32_t *)&bytes2millis;
  574. return ((uint64_t)tlength * b2m) >> 32;
  575. }