diff --git a/README.md b/README.md index 8249b7e..1c309f7 100644 --- a/README.md +++ b/README.md @@ -158,7 +158,7 @@ AudioOutputI2S: Interface for any I2S 16-bit DAC. Sends stereo or mono signals AudioOutputI2SNoDAC: Abuses the I2S interface to play music without a DAC. Turns it into a 32x (or higher) oversampling delta-sigma DAC. Use the schematic below to drive a speaker or headphone from the I2STx pin (i.e. Rx). Note that with this interface, depending on the transistor used, you may need to disconnect the Rx pin from the driver to perform serial uploads. Mono-only output, of course. -AudioOutputSPDIF (experimental): Another way to abuse the I2S peripheral to send out BMC encoded S/PDIF bitstream. To interface with S/PDIF receiver it needs optical or coaxial transceiver, for which some examples can be found at https://www.epanorama.net/documents/audio/spdif.html. It should work even with the simplest form with red LED and current limiting resistor, fed into TOSLINK cable. Due to BMC coding, actual symbol rate on the pin is 4x normal I2S data rate and for each 16bit sample it needs to send out 64bits. On ESP32 with APLL it seems to work well, for up to 48KHz sample rate source. On ESP8266, it seems to hit some hardware limits and your mileage may wary. So far, it seems to work only with 32KHz sampling rate (probably due to whole number clock division), which is the minimum sample rate specified for the SPDIF interface. +AudioOutputSPDIF (experimental): Another way to abuse the I2S peripheral to send out BMC encoded S/PDIF bitstream. To interface with S/PDIF receiver it needs optical or coaxial transceiver, for which some examples can be found at https://www.epanorama.net/documents/audio/spdif.html. It should work even with the simplest form with red LED and current limiting resistor, fed into TOSLINK cable. Minimum sample rate supported by is 32KHz. Due to BMC coding, actual symbol rate on the pin is 4x normal I2S data rate, which drains DMA buffers quickly. See more details inside [AudioOutputSPDIF.cpp](src/AudioOutputSPDIF.cpp#L17) AudioOutputSerialWAV: Writes a binary WAV format with headers to the Serial port. If you capture the serial output to a file you can play it back on your development system. @@ -248,9 +248,7 @@ ESP Pin -------|____|--------+ | Ground ---------------------+ ``` -For ESP8266 with red LED (~1.9Vf drop) you need minimum 150Ohm resistor (12mA max per pin). - -On ESP8266 output pin is fixed (GPIO3/RX0), while on ESP32 it is confgurable with `AuditOutputSPDIF(gpio_num)`. +For ESP8266 with red LED (~1.9Vf drop) you need minimum 150Ohm resistor (12mA max per pin), and output pin is fixed (GPIO3/RX0).On ESP32 it is confgurable with `AudioOutputSPDIF(gpio_num)`. ## Using external SPI RAM to increase buffer A class allows you to use a 23lc1024 SPI RAM from Microchip as input buffer. This chip connects to ESP8266 HSPI port and uses an [external SPI RAM library](https://github.com/Gianbacchio/ESP8266_Spiram). diff --git a/examples/PlayFLAC-SD-SPDIF/PlayFLAC-SD-SPDIF.ino b/examples/PlayFLAC-SD-SPDIF/PlayFLAC-SD-SPDIF.ino new file mode 100644 index 0000000..3c12788 --- /dev/null +++ b/examples/PlayFLAC-SD-SPDIF/PlayFLAC-SD-SPDIF.ino @@ -0,0 +1,68 @@ +#include +#include "AudioFileSourceSD.h" +#include "AudioOutputSPDIF.h" +#include "AudioGeneratorFLAC.h" + +// For this sketch, you need connected SD card with '.flac' music files in the root +// directory. Some samples with various sampling rates are available from i.e. +// Espressif Audio Development Framework at: +// https://docs.espressif.com/projects/esp-adf/en/latest/design-guide/audio-samples.html +// +// On ESP8266 you might need to reencode FLAC files with max '-2' compression level +// (i.e. 1152 maximum block size) or you will run out of memory. FLAC files will be +// slightly bigger but you don't loose audio quality with reencoding (lossles codec). + +// You may need a fast SD card. Set this as high as it will work (40MHz max). +#define SPI_SPEED SD_SCK_MHZ(40) + +// On ESP32 you can adjust the SPDIF_OUT_PIN (GPIO number). +// On ESP8266 it is fixed to GPIO3/RX0 and this setting has no effect +#define SPDIF_OUT_PIN 27 + +File dir; +AudioFileSourceSD *source = NULL; +AudioOutputSPDIF *output = NULL; +AudioGeneratorFLAC *decoder = NULL; + +void setup() { + Serial.begin(115200); + Serial.println(); + delay(1000); + + audioLogger = &Serial; + source = new AudioFileSourceSD(); + output = new AudioOutputSPDIF(SPDIF_OUT_PIN); + decoder = new AudioGeneratorFLAC(); + + // NOTE: SD.begin(...) should be called AFTER AudioOutputSPDIF() + // to takover the the SPI pins if they share some with I2S + // (i.e. D8 on Wemos D1 mini is both I2S BCK and SPI SS) + #if defined(ESP8266) + SD.begin(SS, SPI_SPEED); + #else + SD.begin(); + #endif + dir = SD.open("/"); +} + +void loop() { + if ((decoder) && (decoder->isRunning())) { + if (!decoder->loop()) decoder->stop(); + } else { + File file = dir.openNextFile(); + if (file) { + if (String(file.name()).endsWith(".flac")) { + source->close(); + if (source->open(file.name())) { + Serial.printf_P(PSTR("Playing '%s' from SD card...\n"), file.name()); + decoder->begin(source, output); + } else { + Serial.printf_P(PSTR("Error opening '%s'\n"), file.name()); + } + } + } else { + Serial.println(F("Playback form SD card done\n")); + delay(1000); + } + } +} diff --git a/examples/PlayMP3ToSPDIF/PlayMP3ToSPDIF.ino b/examples/PlayMP3ToSPDIF/PlayMP3ToSPDIF.ino index 97ed91f..02dfb98 100644 --- a/examples/PlayMP3ToSPDIF/PlayMP3ToSPDIF.ino +++ b/examples/PlayMP3ToSPDIF/PlayMP3ToSPDIF.ino @@ -44,13 +44,14 @@ void setup() { Serial.begin(115200); delay(1000); + Serial.println(); audioLogger = &Serial; SPIFFS.begin(); file = new AudioFileSourceSPIFFS(); id3 = NULL; out = new AudioOutputSPDIF(); mp3 = new AudioGeneratorMP3(); - const char* fileName = NULL; + String fileName = ""; // Find first MP3 file in SPIFF and play it @@ -59,7 +60,7 @@ void setup() while ((dir = root.openNextFile())) { if (String(dir.name()).endsWith(".mp3")) { if (file->open(dir.name())) { - fileName = dir.name(); + fileName = String(dir.name()); break; } } @@ -70,18 +71,18 @@ void setup() while (dir.next()) { if (dir.fileName().endsWith(".mp3")) { if (file->open(dir.fileName().c_str())) { - fileName = dir.fileName().c_str(); + fileName = dir.fileName(); break; } } } #endif - if (fileName != NULL) { + if (fileName.length() > 0) { id3 = new AudioFileSourceID3(file); id3->RegisterMetadataCB(MDCallback, (void*)"ID3TAG"); mp3->begin(id3, out); - Serial.printf("Playback of '%s' begins...\n", fileName); + Serial.printf("Playback of '%s' begins...\n", fileName.c_str()); } else { Serial.println("Can't find .mp3 file in SPIFFS"); } diff --git a/keywords.txt b/keywords.txt index b00d2dd..fbdde89 100644 --- a/keywords.txt +++ b/keywords.txt @@ -25,3 +25,4 @@ AudioOutputSerialWAV KEYWORD1 AudioOutputSPIFFSWAV KEYWORD1 AudioOutputMixer KEYWORD1 AudioOutputMixerStub KEYWORD1 +AudioOutputSPDIF KEYWORD1 diff --git a/src/AudioGeneratorFLAC.cpp b/src/AudioGeneratorFLAC.cpp index 01f7e90..4878a6e 100644 --- a/src/AudioGeneratorFLAC.cpp +++ b/src/AudioGeneratorFLAC.cpp @@ -30,6 +30,7 @@ AudioGeneratorFLAC::AudioGeneratorFLAC() buff[1] = NULL; buffPtr = 0; buffLen = 0; + running = false; } AudioGeneratorFLAC::~AudioGeneratorFLAC() @@ -188,9 +189,11 @@ void AudioGeneratorFLAC::metadata_cb(const FLAC__StreamDecoder *decoder, const F (void) metadata; audioLogger->printf_P(PSTR("Metadata\n")); } +char AudioGeneratorFLAC::error_cb_str[64]; void AudioGeneratorFLAC::error_cb(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status) { (void) decoder; - cb.st((int)status, FLAC__StreamDecoderErrorStatusString[status]); + strncpy_P(error_cb_str, FLAC__StreamDecoderErrorStatusString[status], 64); + cb.st((int)status, error_cb_str); } diff --git a/src/AudioGeneratorFLAC.h b/src/AudioGeneratorFLAC.h index b8a5022..716cd0c 100644 --- a/src/AudioGeneratorFLAC.h +++ b/src/AudioGeneratorFLAC.h @@ -81,6 +81,7 @@ class AudioGeneratorFLAC : public AudioGenerator FLAC__bool eof_cb(const FLAC__StreamDecoder *decoder); FLAC__StreamDecoderWriteStatus write_cb(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 *const buffer[]); void metadata_cb(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata); + static char error_cb_str[64]; void error_cb(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status); }; diff --git a/src/AudioOutputSPDIF.cpp b/src/AudioOutputSPDIF.cpp index ecbb37f..8c993c5 100644 --- a/src/AudioOutputSPDIF.cpp +++ b/src/AudioOutputSPDIF.cpp @@ -14,6 +14,14 @@ Adapted for ESP8266Audio + NOTE: This module operates I2S at 4x sampling rate, as it needs to + send out each bit as two output symbols, packed into + 32-bit words. Even for mono sound, S/PDIF is specified minimum + for 2 channels, each as 32-bits sub-frame. This drains I2S + buffers 4x more quickly so you may need 4x bigger output + buffers than usual, configurable with 'dma_buf_count' + constructor parameter. + Copyright (C) 2020 Ivan Kostoski This program is free software: you can redistribute it and/or modify @@ -31,10 +39,11 @@ */ #include -#ifdef ESP32 +#if defined(ESP32) #include "driver/i2s.h" -#else - #include + #include "soc/rtc.h" +#elif defined(ESP8266) + #include "driver/SinglePinI2SDriver.h" #endif #include "AudioOutputSPDIF.h" @@ -77,7 +86,7 @@ static const uint16_t spdif_bmclookup[256] PROGMEM = { AudioOutputSPDIF::AudioOutputSPDIF(int dout_pin, int port, int dma_buf_count) { this->portNo = port; -#ifdef ESP32 +#if defined(ESP32) // Configure ESP32 I2S to roughly compatible to ESP8266 peripheral i2s_config_t i2s_config_spdif = { .mode = (i2s_mode_t)(I2S_MODE_MASTER | I2S_MODE_TX), @@ -87,21 +96,23 @@ AudioOutputSPDIF::AudioOutputSPDIF(int dout_pin, int port, int dma_buf_count) .communication_format = (i2s_comm_format_t)(I2S_COMM_FORMAT_I2S | I2S_COMM_FORMAT_I2S_MSB), .intr_alloc_flags = ESP_INTR_FLAG_LEVEL1, // lowest interrupt priority .dma_buf_count = dma_buf_count, - .dma_buf_len = 256, // 4 x bigger buffers + .dma_buf_len = DMA_BUF_SIZE_DEFAULT, // bigger buffers, reduces interrupts .use_apll = true // Audio PLL is needed for low clock jitter }; if (i2s_driver_install((i2s_port_t)portNo, &i2s_config_spdif, 0, NULL) != ESP_OK) { - audioLogger->println("ERROR: Unable to install I2S drives\n"); + audioLogger->println(F("ERROR: Unable to install I2S drivers")); + return; } i2s_zero_dma_buffer((i2s_port_t)portNo); - //SetPinout(I2S_PIN_NO_CHANGE, I2S_PIN_NO_CHANGE, dout_pin); - SetPinout(25, 32, dout_pin); - rate_multiplier = 2; // For 32bit words -#else + SetPinout(I2S_PIN_NO_CHANGE, I2S_PIN_NO_CHANGE, dout_pin); + rate_multiplier = 2; // 2x32bit words +#elif defined(ESP8266) (void) dout_pin; - (void) dma_buf_count; - i2s_begin(); - rate_multiplier = 4; // For 16bit words + if (!I2SDriver.begin(dma_buf_count, DMA_BUF_SIZE_DEFAULT)) { + audioLogger->println(F("ERROR: Unable to start I2S driver")); + return; + } + rate_multiplier = 4; // 4x16 bit words #endif i2sOn = true; mono = false; @@ -109,26 +120,27 @@ AudioOutputSPDIF::AudioOutputSPDIF(int dout_pin, int port, int dma_buf_count) channels = 2; frame_num = 0; SetGain(1.0); - SetRate(44100); // Default + hertz = 0; + SetRate(44100); } AudioOutputSPDIF::~AudioOutputSPDIF() { -#ifdef ESP32 +#if defined(ESP32) if (i2sOn) { i2s_stop((i2s_port_t)this->portNo); audioLogger->printf("UNINSTALL I2S\n"); i2s_driver_uninstall((i2s_port_t)this->portNo); //stop & destroy i2s driver } -#else - if (i2sOn) i2s_end(); +#elif defined(ESP8266) + if (i2sOn) I2SDriver.stop(); #endif i2sOn = false; } bool AudioOutputSPDIF::SetPinout(int bclk, int wclk, int dout) { -#ifdef ESP32 +#if defined(ESP32) i2s_pin_config_t pins = { .bck_io_num = bclk, .ws_io_num = wclk, @@ -150,15 +162,25 @@ bool AudioOutputSPDIF::SetPinout(int bclk, int wclk, int dout) bool AudioOutputSPDIF::SetRate(int hz) { - this->hertz = hz; - audioLogger->printf("S/PDIF Set Rate: %d\n", AdjustI2SRate(hz)); if (!i2sOn) return false; -#ifdef ESP32 - if (i2s_set_sample_rates((i2s_port_t)portNo, AdjustI2SRate(hz)) != ESP_OK) { + if (hz < 32000) return false; + if (hz == this->hertz) return true; + this->hertz = hz; + int adjustedHz = AdjustI2SRate(hz); +#if defined(ESP32) + if (i2s_set_sample_rates((i2s_port_t)portNo, adjustedHz) == ESP_OK) { + if (adjustedHz == 88200) { + // Manually fix the APLL rate for 44100. + // See: https://github.com/espressif/esp-idf/issues/2634 + // sdm0 = 28, sdm1 = 8, sdm2 = 5, odir = 0 -> 88199.977 + rtc_clk_apll_enable(1, 28, 8, 5, 0); + } + } else { audioLogger->println("ERROR changing S/PDIF sample rate"); } -#else - i2s_set_rate(AdjustI2SRate(hz)); +#elif defined(ESP8266) + I2SDriver.setRate(adjustedHz); + audioLogger->printf_P(PSTR("S/PDIF rate set: %.3f\n"), I2SDriver.getActualRate()/4); #endif return true; } @@ -193,9 +215,6 @@ bool AudioOutputSPDIF::begin() bool AudioOutputSPDIF::ConsumeSample(int16_t sample[2]) { if (!i2sOn) return true; // Sink the data -#ifndef ESP32 - if (i2s_is_full()) return false; -#endif int16_t ms[2]; uint16_t hi, lo, aux; uint32_t buf[4]; @@ -243,18 +262,14 @@ bool AudioOutputSPDIF::ConsumeSample(int16_t sample[2]) aux = 0xb333 ^ (((uint32_t)((int16_t)lo)) >> 17); buf[3] = VUCP_PREAMBLE_W | aux; -// Assume DMA buffers are multiples of 16 bytes. Either we write all bytes or none. -#ifdef ESP32 +#if defined(ESP32) + // Assume DMA buffers are multiples of 16 bytes. Either we write all bytes or none. uint32_t bytes_written; esp_err_t ret = i2s_write((i2s_port_t)portNo, (const char*)&buf, 8 * channels, &bytes_written, 0); // If we didn't write all bytes, return false early and do not increment frame_num if ((ret != ESP_OK) || (bytes_written != (8 * channels))) return false; -#else - // NOTE: Order of buffer words is different for ESP8266 - i2s_write_sample_nb(buf[1]); - i2s_write_sample_nb(buf[0]); - i2s_write_sample_nb(buf[3]); - if (!i2s_write_sample_nb(buf[2])) return false; // Return early and do not increment frame_num +#elif defined(ESP8266) + if (!I2SDriver.writeInterleaved(buf)) return false; #endif // Increment and rotate frame number if (++frame_num > 191) frame_num = 0; @@ -263,8 +278,10 @@ bool AudioOutputSPDIF::ConsumeSample(int16_t sample[2]) bool AudioOutputSPDIF::stop() { -#ifdef ESP32 +#if defined(ESP32) i2s_zero_dma_buffer((i2s_port_t)portNo); +#elif defined(ESP8266) + I2SDriver.stop(); #endif frame_num = 0; return true; diff --git a/src/AudioOutputSPDIF.h b/src/AudioOutputSPDIF.h index 08badeb..92a4e46 100644 --- a/src/AudioOutputSPDIF.h +++ b/src/AudioOutputSPDIF.h @@ -35,12 +35,20 @@ #include "AudioOutput.h" +#if defined(ESP32) #define SPDIF_OUT_PIN_DEFAULT 27 +#define DMA_BUF_COUNT_DEFAULT 8 +#define DMA_BUF_SIZE_DEFAULT 256 +#elif defined(ESP8266) +#define SPDIF_OUT_PIN_DEFAULT 3 +#define DMA_BUF_COUNT_DEFAULT 32 +#define DMA_BUF_SIZE_DEFAULT 64 +#endif class AudioOutputSPDIF : public AudioOutput { public: - AudioOutputSPDIF(int dout_pin=SPDIF_OUT_PIN_DEFAULT, int port=0, int dma_buf_count = 8); + AudioOutputSPDIF(int dout_pin=SPDIF_OUT_PIN_DEFAULT, int port=0, int dma_buf_count = DMA_BUF_COUNT_DEFAULT); virtual ~AudioOutputSPDIF() override; bool SetPinout(int bclkPin, int wclkPin, int doutPin); virtual bool SetRate(int hz) override; @@ -65,4 +73,4 @@ class AudioOutputSPDIF : public AudioOutput uint8_t rate_multiplier; }; -#endif +#endif // _AUDIOOUTPUTSPDIF_H diff --git a/src/driver/SinglePinI2SDriver.cpp b/src/driver/SinglePinI2SDriver.cpp new file mode 100644 index 0000000..cd87fda --- /dev/null +++ b/src/driver/SinglePinI2SDriver.cpp @@ -0,0 +1,279 @@ +/* + SinglePinI2SDriver + ESP8266Audio I2S Minimal driver + + Most of this code is taken and reworked from ESP8266 Arduino core, + which itsef is reworked from Espessif's I2S examples. + Original code is licensed under LGPL 2.1 or above + + Reasons for rewrite: + - Non-configurable size of DMA buffers + - We only need GPIO3 connected to I2SO_DATA + - No API to queue data from ISR. Callbacks are unusable + as i2s_write_* functions are not in IRAM and may re-enable + SLC interrupt before returning + - ISR overhead is not needed + + Copyright (C) 2020 Ivan Kostoski + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +#include "SinglePinI2SDriver.h" + +SinglePinI2SDriver::~SinglePinI2SDriver() +{ + stopI2S(); + freeBuffers(bufCount); +} + +bool SinglePinI2SDriver::begin(uint8_t bufCount, uint16_t bufSize) +{ + if (bufCount < 4) return false; + if ((bufSize < 32) || (bufSize > 1020) || ((bufSize % 4) != 0)) return false; + + stopSLC(); + + if ((bufCount != this->bufCount) || (bufSize != this->bufSize)) freeBuffers(this->bufCount); + this->bufCount = bufCount; + this->bufSize = bufSize; + if (!allocateBuffers()) return false; + + zeroBuffers(); + configureSLC(); + startI2S(); + + // Send out at least one buffer, so we have valid address of + // finished descriptor in SLCRXEDA + head = &descriptors[0]; + head->owner = 1; + startSLC(); + while (!lastSentDescriptor()) delayMicroseconds(1); + // By here, SLC should be stalled (next descriptor owner is 0) + head->owner = 0; + head = head->next_link_ptr; + headPos = 0; + underflowCount = -1; + return true; +}; + +void SinglePinI2SDriver::stop() +{ + stopI2S(); +} + +bool SinglePinI2SDriver::allocateBuffers() +{ + // Allocate output (RXLINK) descriptors and bufferss + if (descriptors) return true; + descriptors = (SLCDecriptor*) calloc(bufCount, sizeof(SLCDecriptor)); + if (!descriptors) return false; + int allocated; + for (allocated = 0; allocated < bufCount; allocated++) { + uint32_t* buffer = (uint32_t*)malloc(bufSize * sizeof(uint32_t)); + if (!buffer) break; + auto descriptor = &descriptors[allocated]; + descriptor->eof = 1; // Needed for SLC to update SLCRXEDA + descriptor->datalen = bufSize * sizeof(uint32_t); + descriptor->blocksize = bufSize * sizeof(uint32_t); + descriptor->buf_ptr = buffer; + descriptor->next_link_ptr = &descriptors[(allocated+1) % bufCount]; + } + // Release memory if not all buffers were allocated + if (allocated < bufCount) { + freeBuffers(allocated); + return false; + } + zeroBuffers(); + return true; +} + +void SinglePinI2SDriver::freeBuffers(int allocated) +{ + if (!descriptors) return; + while (--allocated >= 0) { + if (descriptors[allocated].buf_ptr) { + free(descriptors[allocated].buf_ptr); + descriptors[allocated].buf_ptr = NULL; + } + } + free(descriptors); + descriptors = NULL; +} + +void SinglePinI2SDriver::zeroBuffers() +{ + for(int i = 0; i < bufCount; i++) { + auto descriptor = &descriptors[i]; + ets_memset((void *)descriptor->buf_ptr, 0, bufSize * sizeof(uint32_t)); + } +} + +inline void SinglePinI2SDriver::advanceHead(const SLCDecriptor *lastSent) +{ + if (headPos >= bufSize) { + head->owner = 1; // Owned by SLC + head = head->next_link_ptr; + head->owner = 0; // Owned by CPU + headPos = 0; + // If SLC stopped, fill-up the buffers before (re)starting + if (isSLCStopped() && (head->next_link_ptr == lastSent)) { + underflowCount++; + startSLC(); + } + } +} + +bool SinglePinI2SDriver::write(uint32_t sample) +{ + auto lastSent = lastSentDescriptor(); + if (isSLCRunning() && (lastSent->next_link_ptr == head)) return false; + head->buf_ptr[headPos++] = sample; + advanceHead(lastSent); + return true; +}; + +bool SinglePinI2SDriver::writeInterleaved(uint32_t samples[4]) +{ + auto lastSent = lastSentDescriptor(); + if (isSLCRunning() && (lastSent->next_link_ptr == head)) return false; + uint32_t* buf = head->buf_ptr; + buf[headPos++] = samples[1]; + buf[headPos++] = samples[0]; + buf[headPos++] = samples[3]; + buf[headPos++] = samples[2]; + advanceHead(lastSent); + return true; +}; + +void SinglePinI2SDriver::configureSLC() +{ + ETS_SLC_INTR_DISABLE(); + // Reset SLC, clear interrupts + SLCC0 |= SLCRXLR | SLCTXLR; + SLCC0 &= ~(SLCRXLR | SLCTXLR); + SLCIC = 0xFFFFFFFF; + // Configure SLC DMA in mode 1 + SLCC0 &= ~(SLCMM << SLCM); + SLCC0 |= (1 << SLCM); + SLCRXDC |= SLCBINR | SLCBTNR; + SLCRXDC &= ~(SLCBRXFE | SLCBRXEM | SLCBRXFM); + // RXLINK is output DMA, but TXLINK must be configured with valid descriptr + SLCTXL &= ~(SLCTXLAM << SLCTXLA); + SLCRXL &= ~(SLCRXLAM << SLCRXLA); + SLCTXL |= (uint32)&descriptors[0] << SLCTXLA; + SLCRXL |= (uint32)&descriptors[0] << SLCRXLA; + // Not setting up interrupts. Not starting DMA here +} + +void SinglePinI2SDriver::stopSLC() +{ + // Stop SLC, reset descriptors and clear interrupts + ETS_SLC_INTR_DISABLE(); + SLCTXL |= SLCTXLE; + SLCRXL |= SLCRXLE; + SLCTXL &= ~(SLCTXLAM << SLCTXLA); + SLCRXL &= ~(SLCRXLAM << SLCRXLA); + SLCIC = 0xFFFFFFFF; +} + +void SinglePinI2SDriver::setDividers(uint8_t div1, uint8_t div2) +{ + // Ensure dividers fit in bit fields + div1 &= I2SBDM; + div2 &= I2SCDM; + // trans master(active low), recv master(active_low), !bits mod(==16 bits/chanel), clear clock dividers + I2SC &= ~(I2STSM | I2SRSM | (I2SBMM << I2SBM) | (I2SBDM << I2SBD) | (I2SCDM << I2SCD)); + // I2SRF = Send/recv right channel first + // I2SMR = MSB recv/xmit first + // I2SRMS, I2STMS = We don't really care about WS delay here + // div1, div2 = Set I2S WS clock frequency. BCLK seems to be generated from 32x this + I2SC |= I2SRF | I2SMR | I2SRMS | I2STMS | (div1 << I2SBD) | (div2 << I2SCD); +} + +void SinglePinI2SDriver::setRate(const uint32_t rateHz) +{ + if (rateHz == currentRate) return; + currentRate = rateHz; + + uint32_t scaledBaseFreq = I2SBASEFREQ / 32; + float bestDelta = scaledBaseFreq; + uint8_t sbdDivBest=1; + uint8_t scdDivBest=1; + for (uint8_t i = 1; i < 64; i++) { + for (uint8_t j = i; j < 64; j++) { + float delta = fabs(((float)scaledBaseFreq/i/j) - rateHz); + if (delta < bestDelta){ + bestDelta = delta; + sbdDivBest = i; + scdDivBest = j; + } + } + } + + setDividers(sbdDivBest, scdDivBest); +} + +float SinglePinI2SDriver::getActualRate() +{ + return (float)I2SBASEFREQ/32/((I2SC>>I2SBD) & I2SBDM)/((I2SC >> I2SCD) & I2SCDM); +} + +void SinglePinI2SDriver::startI2S() +{ + // Setup only I2S SD pin for output + pinMode(I2SO_DATA, FUNCTION_1); + I2S_CLK_ENABLE(); + // Reset I2S + I2SIC = 0x3F; + I2SIE = 0; + I2SC &= ~(I2SRST); + I2SC |= I2SRST; + I2SC &= ~(I2SRST); + // I2STXFMM, I2SRXFMM=0 => 16-bit, dual channel data + I2SFC &= ~(I2SDE | (I2STXFMM << I2STXFM) | (I2SRXFMM << I2SRXFM)); + I2SFC |= I2SDE; // Enable DMA + // I2STXCMM, I2SRXCMM=0 => Dual channel mode, RX/TX CHAN_MOD=0 + I2SCC &= ~((I2STXCMM << I2STXCM) | (I2SRXCMM << I2SRXCM)); + // Set dividers to something resonable + currentRate = 0; + setRate(44100); + // Start I2S peripheral + I2SC |= I2STXS; +} + +void SinglePinI2SDriver::stopI2S() +{ + // Disable any I2S send or receive + I2SC &= ~(I2STXS | I2SRXS); + // Reset I2S + I2SC &= ~(I2SRST); + I2SC |= I2SRST; + I2SC &= ~(I2SRST); + + stopSLC(); + // Reconnect RX0 ? + //pinMode(I2SO_DATA, SPECIAL); +} + +int SinglePinI2SDriver::getUnderflowCount() +{ + int count = underflowCount; + underflowCount = 0; + return count; +} + +// Global instance +SinglePinI2SDriver I2SDriver; diff --git a/src/driver/SinglePinI2SDriver.h b/src/driver/SinglePinI2SDriver.h new file mode 100644 index 0000000..7348410 --- /dev/null +++ b/src/driver/SinglePinI2SDriver.h @@ -0,0 +1,85 @@ +/* + SinglePinI2SDriver + ESP8266Audio I2S Minimal driver + + Copyright (C) 2020 Ivan Kostoski + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +#pragma once +#if !defined(ESP8266) +#error "This driver is ESP8266 specific, only include it on ESP8266" +#endif + +#include +#include "osapi.h" +#include "ets_sys.h" +#include "i2s_reg.h" + +struct SLCDecriptor { + uint32_t blocksize : 12; + uint32_t datalen : 12; + uint32_t unused : 5; + uint32_t sub_sof : 1; + uint32_t eof : 1; + volatile uint32_t owner : 1; + uint32_t* buf_ptr; + SLCDecriptor* next_link_ptr; +}; + +class SinglePinI2SDriver +{ + public: + enum : uint8_t { I2SO_DATA = 3 }; // GPIO3/RX0 + + SinglePinI2SDriver(): descriptors(NULL), bufCount(0), bufSize(0) {}; + ~SinglePinI2SDriver(); + + bool begin(uint8_t bufCount, uint16_t bufSize); + void stop(); + void setRate(const uint32_t rateHz); + float getActualRate(); + bool write(uint32_t sample); + bool writeInterleaved(uint32_t samples[4]); + int getUnderflowCount(); + + protected: + bool allocateBuffers(); + void freeBuffers(int allocated); + void zeroBuffers(); + void advanceHead(const SLCDecriptor *finished); + void configureSLC(); + void stopSLC(); + void setDividers(uint8_t div1, uint8_t div2); + void startI2S(); + void stopI2S(); + SLCDecriptor *descriptors; + uint16_t bufCount; + uint16_t bufSize; + SLCDecriptor *head; + uint32_t headPos; + uint32_t currentRate; + int underflowCount; + + // (Re)Start transmission ("TX" DMA always needed to be enabled) + static inline void startSLC() { SLCTXL |= SLCTXLS; SLCRXL |= SLCRXLS; } + static inline uint32_t isSLCRunning() { return (SLCRXS & SLCRXF); }; + static inline uint32_t isSLCStopped() { return (SLCRXS & SLCRXE); }; + static inline SLCDecriptor *lastSentDescriptor() { return (SLCDecriptor*)SLCRXEDA; } +}; + +// Global instance +extern SinglePinI2SDriver I2SDriver; diff --git a/src/libflac/bitreader.c b/src/libflac/bitreader.c index e1ee14d..1223d57 100644 --- a/src/libflac/bitreader.c +++ b/src/libflac/bitreader.c @@ -99,7 +99,12 @@ typedef FLAC__uint64 brword; * also depends on the CPU cache size and other factors; some twiddling * may be necessary to squeeze out the best performance. */ +#if defined(ESP8266) +/* Reduced bitreader buffer, saves some RAM */ +static const unsigned FLAC__BITREADER_DEFAULT_CAPACITY = 8192u / FLAC__BITS_PER_WORD; /* in words */ +#else static const unsigned FLAC__BITREADER_DEFAULT_CAPACITY = 65536u / FLAC__BITS_PER_WORD; /* in words */ +#endif struct FLAC__BitReader { /* any partially-consumed word at the head will stay right-justified as bits are consumed from the left */ diff --git a/src/libflac/format.c b/src/libflac/format.c index c1b1f13..cd831ae 100644 --- a/src/libflac/format.c +++ b/src/libflac/format.c @@ -146,6 +146,8 @@ FLAC_API const unsigned FLAC__SUBFRAME_TYPE_VERBATIM_BYTE_ALIGNED_MASK = 0x02; FLAC_API const unsigned FLAC__SUBFRAME_TYPE_FIXED_BYTE_ALIGNED_MASK = 0x10; FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LPC_BYTE_ALIGNED_MASK = 0x40; +// Not used in AudioGeneratorFLAC, possibly save some RAM +/* FLAC_API const char * const FLAC__SubframeTypeString[] = { "CONSTANT", "VERBATIM", @@ -198,6 +200,7 @@ FLAC_API const char * const FLAC__StreamMetadata_Picture_TypeString[] = { "Band/artist logotype", "Publisher/Studio logotype" }; +*/ FLAC_API FLAC__bool FLAC__format_sample_rate_is_valid(unsigned sample_rate) { diff --git a/src/libflac/stream_decoder.c b/src/libflac/stream_decoder.c index 0934233..08a93d9 100644 --- a/src/libflac/stream_decoder.c +++ b/src/libflac/stream_decoder.c @@ -33,6 +33,8 @@ //#ifdef HAVE_CONFIG_H # include "config.h" //#endif +#include +#include //#include #include /* for malloc() */ @@ -176,6 +178,8 @@ typedef struct FLAC__StreamDecoderPrivate { * ***********************************************************************/ +// Not used in AudioGeneratorFLAC, save some RAM +/* FLAC_API const char FLAC__StreamDecoderStateString[][48] = { "FLAC__STREAM_DECODER_SEARCH_FOR_METADATA", "FLAC__STREAM_DECODER_READ_METADATA", @@ -226,8 +230,9 @@ FLAC_API const char FLAC__StreamDecoderWriteStatusString[][48] = { "FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE", "FLAC__STREAM_DECODER_WRITE_STATUS_ABORT" }; +*/ -FLAC_API const char FLAC__StreamDecoderErrorStatusString[][64] = { +FLAC_API const char FLAC__StreamDecoderErrorStatusString[][64] PROGMEM = { "FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC", "FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER", "FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH", @@ -863,10 +868,12 @@ FLAC_API FLAC__StreamDecoderState FLAC__stream_decoder_get_state(const FLAC__Str return decoder->protected_->state; } +/* FLAC_API const char *FLAC__stream_decoder_get_resolved_state_string(const FLAC__StreamDecoder *decoder) { return &FLAC__StreamDecoderStateString[decoder->protected_->state][0]; } +*/ FLAC_API FLAC__bool FLAC__stream_decoder_get_md5_checking(const FLAC__StreamDecoder *decoder) {