Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions components/lightsnapcast/Kconfig.projbuild
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
menu "Lightsnapcast Player Settings"
config PLAYER_QUEUE_EMPTY_THRESHOLD
int "Queue empty threshold for hard resync"
range 1 10
default 3
help
Number of consecutive empty queue reads before triggering hard resync.
Higher values tolerate brief WiFi dropouts better.
Default: 3 (covers ~78ms of delay)

config PLAYER_QUEUE_INSERT_TIMEOUT_MS
int "Queue insert timeout (ms)"
range 1 200
default 50
help
Timeout for inserting audio chunks into the playback queue.
Higher values allow queue to drain during burst arrivals.
Default: 50ms
endmenu
32 changes: 14 additions & 18 deletions components/lightsnapcast/player.c
Original file line number Diff line number Diff line change
Expand Up @@ -1196,8 +1196,7 @@ int32_t insert_pcm_chunk(pcm_chunk_message_t *pcmChunk) {
// free_pcm_chunk(element);
// }

// if (xQueueSend(pcmChkQHdl, &pcmChunk, pdMS_TO_TICKS(10)) != pdTRUE) {
if (xQueueSend(pcmChkQHdl, &pcmChunk, pdMS_TO_TICKS(1)) != pdTRUE) {
if (xQueueSend(pcmChkQHdl, &pcmChunk, pdMS_TO_TICKS(CONFIG_PLAYER_QUEUE_INSERT_TIMEOUT_MS)) != pdTRUE) {
ESP_LOGV(TAG, "send: pcmChunkQueue full, messages waiting %d",
uxQueueMessagesWaiting(pcmChkQHdl));

Expand Down Expand Up @@ -1279,20 +1278,7 @@ static void player_task(void *pvParameters) {
adjust_apll(0);
#endif

// if (pcmChkQHdl == NULL) {
// int entries = ceil(((float)scSet.sr / (float)scSet.chkInFrames) *
// ((float)scSet.buf_ms / 1000));
//
// // some chunks are placed in DMA buffer
// // so we can save a little RAM here
// entries -= (i2sDmaBufMaxLen * i2sDmaBufCnt) / scSet.chkInFrames;
//
// queueCreatedWithChkInFrames = scSet.chkInFrames;
//
// pcmChkQHdl = xQueueCreate(entries, sizeof(pcm_chunk_message_t *));
//
// ESP_LOGI(TAG, "created new queue with %d", entries);
// }
// Queue is now created in start_player() for proper initialization
audio_set_mute(scSet.muted);

// wait for early time syncs to be ready
Expand Down Expand Up @@ -1367,7 +1353,7 @@ static void player_task(void *pvParameters) {

pcmChkQHdl = xQueueCreate(entries, sizeof(pcm_chunk_message_t *));

ESP_LOGI(TAG, "created new queue with %d", entries);
ESP_LOGI(TAG, "created new queue with %d entries", entries);
}

if ((scSet.sr != __scSet.sr) || (scSet.bits != __scSet.bits) ||
Expand Down Expand Up @@ -1800,9 +1786,19 @@ static void player_task(void *pvParameters) {

int msgWaiting = uxQueueMessagesWaiting(pcmChkQHdl);

// Track consecutive empty queue reads for hysteresis
static int consecutive_empty_count = 0;

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is this really necessary? I have a feeling if you run out of samples there will be an audible offset between clients if you tolerate this.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You raise a fair point but this was to help on bad networks -

How it works: When the queue empties, the I2S DMA clock keeps running independently (looping its buffer). With
threshold=3, that's ~78ms where no fresh samples are written. When new data arrives, the player is behind by the
duration of the gap, and soft-sync (APLL/sample insertion) gradually corrects it, but during that window, clients
could be slightly out of sync.

Why it exists: On congested WiFi (my network regularly sees ping spikes to 1400ms), a single empty queue read with threshold=1 triggers a full hard resync, mute, stop I2S, reset initialSync, re-establish sync from scratch. its a
multi-second audible disruption for what might be a 26ms network hiccup that resolves on its own. This hysteresis
avoids that.

Threshold=1 gives tightest multi-client sync but is fragile on imperfect networks. Threshold=3 tolerates brief WiFi hiccups but risks ~78ms transient offset that soft-sync corrects over a few seconds. Both have audible impact, it's a question of which is less disruptive for the user's environment.

That's why it's a Kconfig setting (PLAYER_QUEUE_EMPTY_THRESHOLD, range 1-10, default 3) rather than a hardcoded change, users on clean networks can set it to 1 for tight sync, while those on congested WiFi can increase it to avoid constant resyncs.

Happy to adjust the default if you think 1 is more appropriate for the typical use case, what do you think?

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

multi-second audible disruption

I am wondering, the hard resync never takes that long, normally it's just a short "click" in the speakers and if you don't listen carefully and this just happens once it's almost not noticeable.

Is this a board/DAC specific problem maybe?


if (msgWaiting == 0) {
consecutive_empty_count++;
} else {
consecutive_empty_count = 0;
}

// resync hard if we are getting very late / early.
// rest gets tuned in through apll speed control or sample insertion
if ((msgWaiting == 0) ||
// Use hysteresis for queue empty to tolerate brief WiFi dropouts
if ((consecutive_empty_count >= CONFIG_PLAYER_QUEUE_EMPTY_THRESHOLD) ||
(MEDIANFILTER_isFull(&shortMedianFilter, 0) &&
((shortMedian > hardResyncThreshold) ||
(shortMedian < -hardResyncThreshold))))
Expand Down
25 changes: 25 additions & 0 deletions main/Kconfig.projbuild
Original file line number Diff line number Diff line change
Expand Up @@ -51,3 +51,28 @@ menu "Snapclient Configuration"
Both approaches have similar performance keeping clients in sync <= 500µs

endmenu

menu "WiFi Resilience Settings"
config WIFI_TCP_NODELAY
bool "Enable TCP_NODELAY"
default y
help
Disable Nagle's algorithm for lower latency on TCP connections.
Recommended for real-time audio streaming.

config WIFI_RECONNECT_MIN_DELAY_MS
int "Reconnect minimum delay (ms)"
range 100 5000
default 1000
help
Initial delay before reconnection attempt.
Default: 1000 (1 second)

config WIFI_RECONNECT_MAX_DELAY_MS
int "Reconnect maximum delay (ms)"
range 5000 60000
default 30000
help
Maximum delay with exponential backoff.
Default: 30000 (30 seconds)
endmenu
40 changes: 32 additions & 8 deletions main/main.c
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
#include "lwip/sockets.h"
#include "lwip/sys.h"
#include "lwip/tcp.h"
#include "esp_random.h"
#include "mdns.h"
#include "net_functions.h"
#include "network_interface.h"
Expand Down Expand Up @@ -461,7 +462,8 @@ static void http_get_task(void *pvParameters) {
int rc1 = ERR_OK, rc2 = ERR_OK;
struct netbuf *firstNetBuf = NULL;
uint16_t len;
uint64_t timeout;
uint64_t timeout = FAST_SYNC_LATENCY_BUF;
static uint32_t reconnect_attempts = 0; // For exponential backoff
char *codecString = NULL;
char *codecPayload = NULL;
char *serverSettingsString = NULL;
Expand Down Expand Up @@ -688,9 +690,18 @@ static void http_get_task(void *pvParameters) {

continue;
}

// netconn_set_flags(lwipNetconn, TF_NODELAY);


#if CONFIG_WIFI_TCP_NODELAY
// Disable Nagle's algorithm for lower latency
{
struct tcp_pcb *pcb = (struct tcp_pcb *)lwipNetconn->pcb.tcp;
if (pcb != NULL) {
tcp_nagle_disable(pcb);
ESP_LOGI(TAG, "TCP_NODELAY enabled for lower latency");
}
}
#endif

#define USE_INTERFACE_BIND

#ifdef USE_INTERFACE_BIND // use interface to bind connection
Expand All @@ -717,20 +728,33 @@ static void http_get_task(void *pvParameters) {
if (rc2 != ERR_OK) {
ESP_LOGE(TAG, "can't connect to remote %s:%d, err %d",
ipaddr_ntoa(&remote_ip), remotePort, rc2);

#if !SNAPCAST_SERVER_USE_MDNS
vTaskDelay(pdMS_TO_TICKS(1000));
#endif
}

if (rc1 != ERR_OK || rc2 != ERR_OK) {
netconn_close(lwipNetconn);
netconn_delete(lwipNetconn);
lwipNetconn = NULL;

// Exponential backoff with jitter for reconnection
uint32_t delay_ms = (uint32_t)CONFIG_WIFI_RECONNECT_MIN_DELAY_MS << reconnect_attempts;
if (delay_ms > (uint32_t)CONFIG_WIFI_RECONNECT_MAX_DELAY_MS) {
delay_ms = (uint32_t)CONFIG_WIFI_RECONNECT_MAX_DELAY_MS;
}
delay_ms += (esp_random() % 500); // Add jitter

ESP_LOGW(TAG, "Reconnect attempt %lu, waiting %lums",
(unsigned long)reconnect_attempts, (unsigned long)delay_ms);
vTaskDelay(pdMS_TO_TICKS(delay_ms));

if (reconnect_attempts < 10) { // Cap attempts counter
reconnect_attempts++;
}

continue;
}

// Reset backoff on successful connection
reconnect_attempts = 0;
ESP_LOGI(TAG, "netconn connected using %s", network_get_ifkey(netif));

//if (reset_latency_buffer() < 0) {
Expand Down