Giter Club home page Giter Club logo

esp32_vs1053_stream's Introduction

ESP32_VS1053_Stream

Codacy Badge

A streaming library for esp32, esp32-wrover, esp32-s2 and esp32-s3 with a separate VS1053 codec chip.
This library plays mp3, ogg, aac, aac+ and flac files and streams and uses ESP_VS1053_Library to communicate with the decoder.

Supports http, https (insecure mode) and chunked audio streams.

Visit eStreamPlayer32_VS1053 for PIO to see a PlatformIO project using this library.

How to install and use

Install ESP_VS1053_Library and this library in your Arduino library folder.

Take care to install the master branch of the VS1053 library or at least a version from commit ba1803f or later because the getChipVersion() call that is needed is not included in the latest release.
See #23

Use the latest Arduino ESP32 core version.

Example code

#include <Arduino.h>
#include <VS1053.h>               /* https://github.com/baldram/ESP_VS1053_Library */
#include <ESP32_VS1053_Stream.h>

#define SPI_CLK_PIN 18
#define SPI_MISO_PIN 19
#define SPI_MOSI_PIN 23

#define VS1053_CS 5
#define VS1053_DCS 21
#define VS1053_DREQ 22

ESP32_VS1053_Stream stream;

const char* SSID = "xxx";
const char* PSK = "xxx";

void setup() {
#if defined(CONFIG_IDF_TARGET_ESP32S2) && ARDUHAL_LOG_LEVEL != ARDUHAL_LOG_LEVEL_NONE
    delay(3000);
    Serial.setDebugOutput(true);
#endif

    Serial.begin(115200);

    WiFi.begin(SSID, PSK);
    
    WiFi.setSleep(false); 
    /* important to set this right! See issue #15 */

    Serial.println("\n\nSimple vs1053 Streaming example.");

    while (!WiFi.isConnected())
        delay(10);
    Serial.println("wifi connected - starting decoder");

    SPI.setHwCs(true);
    SPI.begin(SPI_CLK_PIN, SPI_MISO_PIN, SPI_MOSI_PIN);  /* start SPI before starting decoder */

    if (!stream.startDecoder(VS1053_CS, VS1053_DCS, VS1053_DREQ) || !stream.isChipConnected())
    {
        Serial.println("Decoder not running");
        while (1) delay(100);
    };

    Serial.println("decoder running - starting stream");

    stream.connecttohost("http://icecast.omroep.nl/radio6-bb-mp3");

    Serial.print("codec: ");
    Serial.println(stream.currentCodec());

    Serial.print("bitrate: ");
    Serial.print(stream.bitrate());
    Serial.println("kbps");

}

void loop() {
    stream.loop();
    //Serial.printf("Buffer status: %s\n", stream.bufferStatus());
    delay(5);
}

void audio_showstation(const char* info) {
    Serial.printf("showstation: %s\n", info);
}

void audio_showstreamtitle(const char* info) {
    Serial.printf("streamtitle: %s\n", info);
}

void audio_eof_stream(const char* info) {
    Serial.printf("eof: %s\n", info);
}

Tips for troublefree streaming

WiFi setup

Do not forget to switch WiFi out of power save mode:

...
WiFi.begin(SSID, PSK);
WiFi.setSleep(false); 
...

Prevent reboots while playing

Early version of the esp32 have issues with the external psram cache, resulting in reboots.
Workarounds are possible depending on the hardware revision.

Revision V0.0

No workarounds are possible for this revision other than not using the psram.

Revision V1.0

On revision V1.0 psram can be used with the following build flags:

-D BOARD_HAS_PSRAM
-mfix-esp32-psram-cache-issue
-mfix-esp32-psram-cache-strategy=memw

Revision V3.0

On revision V3.0 psram can be used with the following build flag:

-D BOARD_HAS_PSRAM

Source: esp-idf api guide on external ram.

Find your hardware revision

In PIO you can find out what hardware revision you have by running esptool.py flash_id in a terminal.

In Arduino IDE go to File->Preferences and find the Show verbose output during option. Check the box marked upload.
You can now see the hardware revision when you upload a sketch.


Functions

Initialize the VS1053 codec

bool startDecoder(CS, DCS, DREQ)

Check if VS1053 is responding

bool isChipConnected()

Start or resume a stream

bool connecttohost(url)
bool connecttohost(url, offset)
bool connecttohost(url, user, pwd)
bool connecttohost(url, user, pwd, offset)

Stop a stream

void stopSong()

Feed the decoder

void loop()

This function has to called every couple of ms to feed the decoder with data.
For bitrates up to 320kbps somewhere between 5-25 ms is about right.


Check if stream is running

bool isRunning()

Get the current volume

uint8_t getVolume()

Set the volume

void setVolume(uint8_t volume)

Value should be between 0-100.


Set bass and treble

uint8_t rtone[4]  = {toneha, tonehf, tonela, tonelf};
void setTone(rtone)

Values for rtone:

toneha       = <0..15>        // Setting treble gain (0 off, 1.5dB steps)
tonehf       = <0..15>        // Setting treble frequency lower limit x 1000 Hz
tonela       = <0..15>        // Setting bass gain (0 = off, 1dB steps)
tonelf       = <0..15>        // Setting bass frequency lower limit x 10 Hz

Get the current used codec

const char* currentCodec()

Returns STOPPED if no stream is running.


Get the current stream url

const char* lastUrl()

The current stream url might differ from the request url if the request url points to a playlist.


Get the filesize

size_t size()

Returns 0 if the stream is a radio stream.


Get the current position in the file

size_t position()

Returns 0 if the stream is a radio stream.


Get the buffer fill status

const char *bufferStatus()

Returns 0/0 if there is no buffer.
Otherwise returns something like 4096/65536 which means 4kB waiting in a 64kB buffer.

void bufferStatus(size_t &used, size_t &capacity)

There is also a version that takes two size_t variables by reference.
Works the same as the const char * version.

A buffer will only be allocated if there is enough free psram.


Event callbacks

Station name callback.

void audio_showstation(const char* info)

Stream information callback.

void audio_showstreamtitle(const char* info)

End of file callback.

void audio_eof_stream(const char* info)

Returns the eof url.
Also called if a stream times out/errors.

Handy function for coding a playlist.
You can use connecttohost() inside this function to start the next item.


License

MIT License

Copyright (c) 2021 Cellie

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

esp32_vs1053_stream's People

Contributors

3kudelta avatar celliesprojects avatar codacy-badger avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

esp32_vs1053_stream's Issues

codec: UNKNOWN library not start any stream since esp32 core 2.0.3

I got this messages from serial monitor:

0:18:00.977 -> Simple vs1053 Streaming example.
20:18:03.259 -> wifi connected - starting decoder
20:18:06.519 -> decoder running - starting stream
20:18:06.566 -> codec: UNKNOWN

I tryed several url:

http://streams.regenbogen.de/rr-eurodance-128-mp3

http://mp3.ffh.de/ffhchannels/hqeurodance.mp3

http://mp3.hitradiort1.c.nmdn.net/rt1eurodancewl/livestream.mp3

http://89.39.189.52:8000/stream/1/

I have used expressif esp32 board with vs1053, set these pins:

#define VS1053_CS 5
#define VS1053_DCS 16
#define VS1053_DREQ 4

'class VS1053' has no member named 'getChipVersion'

I get an error when compiling in Arduino 1.8.19:

D:\Arduino\libraries\ESP32_VS1053_Stream\src\ESP32_VS1053_Stream.cpp: In member function 'bool ESP32_VS1053_Stream::startDecoder(uint8_t, uint8_t, uint8_t)':
D:\Arduino\libraries\ESP32_VS1053_Stream\src\ESP32_VS1053_Stream.cpp:153:18: error: 'class VS1053' has no member named 'getChipVersion'
     if (_vs1053->getChipVersion() == 4)
                  ^~~~~~~~~~~~~~

I installed latest version of VS1053 (1.1.4) is there an earlier version that should be used? I can see it in the source:
https://github.com/baldram/ESP_VS1053_Library/blob/824f82cff459bba2b3184b29bc21f7547bc6c516/src/VS1053.cpp#L378C23-L378C23

Watchdog

Can we have a some kind of watchdog here? i.e. callback function when no data send to VS1053 for some time?

Error compiling simple.ino

Compiling the example file simple,ino in Arduino IDE 1.8.19 results in "Error compiling for board ...." In my case the board is Doit Esp32 Devkit V1 but other ESP32 boards give the same error,
The only error I noticed in the error output stream is the following: "...error: 'StaticRingbuffer_t' does not name a type
StaticRingbuffer_t *_buffer_struct;"

What can be the problem?

error: 'StaticRingbuffer_t' does not name a type

I've added my SSID and psk to the file.

When compiling get:

C:\Documents\Arduino\libraries\ESP32_VS1053_Stream-master\src/ESP32_VS1053_Stream.h:75:5: error: 'StaticRingbuffer_t' does not name a type
StaticRingbuffer_t *_buffer_struct;

Please help me resolve this issue so I can use your library in my esp32 internet radio project.

Thank you for your creation and support of this library.

Gord

stream stop when call setvolume(), Buffer is zero

Hi CelliesProjects,

your code works very well but when i call the stream.setvolume function the streams stops for 1-2s. So when i call the stream.bufferStatus() there is always zero. I tried it with an ESP32 Revision V1.0 and an ESP32 mini D1 Revision V3.0.

what could be the problem or what else should I try?

Thanks in advance and greetings from Germany

ICY name problem?

Im using more weeks my wifi radio what using your library. We know some station have configuration problem, and impossible to receive the station name.

But there was two station, whats worked well, but now, i dont know why the library or my code unable to decode the icy name.

I have asked the radio server owner about any changes in these weeks, but response was, there is no problem icy name is ok. He sendet me about a picture, what i have attached.

Can you check with your method this problem?

http://retro.dancewave.online/retrodance.ogg

http://retro.dancewave.online/retrodance.mp3

On https chunked stream, stream->available() returns 31 or less and hangs , but stream unblocks if we read these bytes

On some https streams I observe weird behaviour (most probably related to the media server) :

It starts to play, plays less than second and hangs.

Here in

void ESP32_VS1053_Stream::_handleChunkedStream(WiFiClient *const stream)

call of "stream->available()" returns 31 or less. It's quite strange that it remains the same on subsequent calls until we try to read some bytes from the stream.

So I locally made this change, but not sure whether it is a proper fix or there could be a more elegant way:

            if (stream->available() < BYTES_TO_READ)
                break;

replaced with

            int BYTES_IN_BUFFER = 0;
            if (stream->available() < BYTES_TO_READ)
            {
                log_i("Not enough data in web stream buffer, trying to read byte-by-byte");
                while(stream->available() && BYTES_IN_BUFFER < VS1053_PLAYBUFFER_SIZE)
                {
                    _vs1053Buffer[BYTES_IN_BUFFER++] = stream->read();
                }
            }
            else
            {
                BYTES_IN_BUFFER = stream->readBytes(_vs1053Buffer, BYTES_TO_READ);
            }

Somehow it unblocks/unlocks the stream and after that it runs fine.
I believe there could be more beautiful approach but this rough fix did the trick.

lot of compilation errors with arduino Arduino ESP32 pre-release version 3.0.0-aplha 3

Hello i use version
The Arduino ESP32 pre-release version 3.0.0-aplha 3 is based on the ESP-IDF v5.1 (release notes) and is major release supporting new version of ESP-IDF 5.1. This release introduce breaking changes and support for new SoCs, ESP32-H2 and ESP32-C6.

beecause i need to use a ESP32-C6 device and I get many errors with le library. I have try with an ESP32 wroom same errors ......
error.log

ci attached above log

ESP32 core 2.0.4 most of the stations do not play anymore

Hello, I am a big fan of your library and I am using it for my web radio.

This is just to inform that after the update to ESP32 2.0.4 most of my favourite station do not play anymore. They just play perfect on 2.0.2 (so I stay on 2.0.2 for the moment). I am using a ESP32 Dev Board V1 with plain vanilla settings.

Just one station is still running:

"https://stream.srg-ssr.ch/m/rsp/mp3_128",

where as these stations do not play anymore:

  "http://mp3.ffh.de/radioffh/hqlivestream.mp3", 
  "http://mp3.ffh.de/ffhchannels/hqlounge.mp3", 
  "http://mp3.ffh.de/ffhchannels/hqsummerfeeling.mp3", 
  "http://mp3.ffh.de/ffhchannels/hqvoting.mp3", 
  "http://deluxe.hoerradar.de/deluxe-easy-mp3-hq",
  "http://ais-sa5.cdnstream1.com/b05055_128mp3",
  "http://energyhits.ice.infomaniak.ch/energyhits-high.mp3",
  "http://energymetime.ice.infomaniak.ch/energymetime-high.mp3" 

It would be great if you could keep your lovely library updated to the latest Espressif versions.

Unable to play ogg streams, flac ogg playing but no sound

When i try play ogg streams with the library i get false to streamisrunning and codec: unknow and code fail to play ogg streams, no sound.

Tested normal ogg streams:

http://retro.dancewave.online/retrodance.ogg https://icast.connectmedia.hu/4765/mr2.ogg https://www.jazzradio.hu:8000/jazzradio_192.ogg
https://icast.connectmedia.hu/4765/mr2.ogg
http://dancewave.online/dance.ogg

If i try flac ogg (maybe not supported), library detect codec: ogg and streamisrunning true but no sound.

Tested Flac type ogg stream: http://retro.dancewave.online/retrodance.flac.ogg

Im not sure, the problem is with the library or the ogg format not supported.

The high-bitrate web radio is not working

If the stream speed is 196 kbit/s or higher, the ESP32 goes into 'sleep' mode after receiving a certain amount of bytes. At my home, the Internet speed is 10 Mbit/s, and the sound gets interrupted. If a higher Internet speed is used, some radio stations start playing normally.
Example code:
WiFi.begin(SSID, PSK);
You need to insert the function:
WiFi.setSleep(false);
For example, try these stations:
http://listen1.myradio24.com:9000/5967
https://stream.realhardstyle.nl/320
http://89.223.45.5:8000/progressive-160
http://streamer.radiovseti.ru:8000/320
http://icecast.err.ee/klarajazzkorge.mp3
http://audio.bfmtv.com/bfmradio_128.mp3

How to use an existing buffer

Hi, I have used your app to listen to some radios and works great. Now I have developed a small app that provides a buffer in a loop with some aac audio data in chunks of about 1600 bytes coming from an decoded HLS stream. The buffer has this format: uint8 * data.
I can play the data using Adafruit VS1053 library with this code
if(vs_player.readyForData())
vs_player.playData(data,read);
but the sound is hashed and sometimes some bits are skipped.
I thought that using a circular buffer like esp32 Stream vs1053 might be better but I don't see how to feed the data to the stream.
I see that the main function stream.connectTohost is used to create a stream from a website, how can I instead feed by data buffer to the stream and get it played from vs1053?
Thanks for your help.

Compiler errors

Hi Cellie,
thank you very much for providing this piece of software! Looking forward to make use of it.
Compiling the simple example, I get these messages:

Arduino: 1.8.15 (Linux), Board: "DOIT ESP32 DEVKIT V1, 80MHz, 921600, None"

/home/wolfgang/Arduino/libraries/ESP32_VS1053_Stream/src/ESP32_VS1053_Stream.cpp: In member function 'bool ESP32_VS1053_Stream::startDecoder(uint8_t, uint8_t, uint8_t)':
/home/wolfgang/Arduino/libraries/ESP32_VS1053_Stream/src/ESP32_VS1053_Stream.cpp:60:14: error: 'class VS1053' has no member named 'loadDefaultVs1053Patches'
     _vs1053->loadDefaultVs1053Patches();
              ^
/home/wolfgang/Arduino/libraries/ESP32_VS1053_Stream/src/ESP32_VS1053_Stream.cpp: In member function 'bool ESP32_VS1053_Stream::connecttohost(const String&)':
/home/wolfgang/Arduino/libraries/ESP32_VS1053_Stream/src/ESP32_VS1053_Stream.cpp:126:12: error: 'class HTTPClient' has no member named 'setFollowRedirects'
     _http->setFollowRedirects(HTTPC_STRICT_FOLLOW_REDIRECTS);
            ^
/home/wolfgang/Arduino/libraries/ESP32_VS1053_Stream/src/ESP32_VS1053_Stream.cpp:126:31: error: 'HTTPC_STRICT_FOLLOW_REDIRECTS' was not declared in this scope
     _http->setFollowRedirects(HTTPC_STRICT_FOLLOW_REDIRECTS);
                               ^
exit status 1
Error compiling for board DOIT ESP32 DEVKIT V1.

Could you maybe point me to how to resolve that ?

Thank you very much & kind regards,
Wolfgang

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.