core icon indicating copy to clipboard operation
core copied to clipboard

YouTube Music: tracks go silent before the end — proxy leaves ffmpeg hanging when googlevideo closes the connection (tested fix included)

Open cdanne opened this issue 3 weeks ago • 4 comments

With YouTube Music, some tracks go silent up to a minute before their end. The UI keeps counting and the next track starts normally. In our logs this affected 5 of 22 tracks. NAS/FLAC playback is not affected.

Cause and a tested fix are below (Fix): when googlevideo closes the connection mid-response, streamInBoundedChunks treats it like "client went away" and leaves ffmpeg's connection open forever. Resuming from the exact byte offset instead brought it down to 0 of 24 silent tracks on our system.

🤖 The analysis and the patch were made with an AI assistant (Claude), from our logs and the v4.0.0-beta.23 source. Sections marked 🤖 are its interpretation; the facts, measurements and listening tests are ours.

Environment

Sonn Core 4.0.0-beta.23 (official image, Node 24.22.2, ffmpeg 7.1.5) · Odroid N2 aarch64, LoxBerry 4.0.1.5, Audioserver4Home 3.3.0 · Squeezelite Multi-Room 1.3.5 · YouTube Music (cookie auth, itag 251 Opus) · consoleLevel=spam

Observed (facts from the logs)

Affected tracks from two albums played start to finish (zone 15, 2026-11-09):

Track Duration Data stopped at Silent ffmpeg end
Hallucination No.4 241 s 231.8 s 9 s SIGKILL
Holiday in Lily Dale 294 s 250.9 s 43 s SIGKILL
Unanswered Questions 282 s 252.7 s 29 s SIGKILL
Insignificant Other 354 s 307.4 s 47 s SIGKILL
Sunday 295 s 230.6 s 64 s SIGKILL

The other 17 tracks ended with ffmpeg exited code=0 and playback ended elapsed=<duration>. It is not deterministic: a track cut off one day played through the next.

For every affected track the log shows the same thing (example Holiday in Lily Dale, UTC):

13:45:30.621 [DEBUG][Http|AudioProxy]  proxy windowed first attempt  clientRange=bytes=0- sentRange=bytes=0-4194303 status=206
13:49:40.997 [SPAM ][Audio|Session]    pipe throughput   <- last one; then 48 s without any entry for this session
13:50:29.272 [DEBUG][Output|SqueezeliteCore] title="Holiday in Lily Dale" elapsedMs=250825 state=buffering
13:50:31.277 [INFO ][Audio|Session]    ffmpeg exited  code=null signal=SIGKILL runMs=301224
  • No warning or error at all, no ffmpeg stderr, no reconnect (no second /streams/proxy request), no playback ended.
  • Squeezelite runs dry exactly where the data stops. The next track starts only because the duration ran out.
  • ffmpeg input: -reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5 -re -i http://127.0.0.1:7090/streams/proxy?u=… (no -rw_timeout).

Cause 🤖

src/adapters/http/streams/audioProxyHandler.ts:

  • pipeChunk() resolves false both when the client closes (res close) and when the upstream body errors (body error).
  • streamInBoundedChunks() treats every false as "client went away" (l. 501–504) and returns without res.end() / res.destroy() and without logging.
  • ffmpeg's connection to /streams/proxy therefore stays open with no more data. ffmpeg sees neither EOF nor an error, so -reconnect never fires. Nothing in the chain has an inactivity timeout: the upstream fetch() has no signal, and ffmpeg has no -rw_timeout.

The trigger was confirmed with the patched build: the googlevideo body fails with undici's terminated, so the connection is closed before the response is complete. Because the proxy reads googlevideo far ahead of playback (e.g. 5.0 MB fetched while ffmpeg had consumed 1.4 MB), the silence only becomes audible minutes later, once ffmpeg has drained that backlog. Why googlevideo closes the connection is unknown. It happened in the first window, the second window and in a resumed window alike.

Fix

🤖 Patch to streamInBoundedChunks / pipeChunk, tested as a bind-mounted replacement of the compiled dist/adapters/http/streams/audioProxyHandler.js:

  1. pipeChunk returns end / client-gone / upstream-error plus the bytes written to res.
  2. On upstream-error: log proxy upstream read failed; resuming and re-request from the exact byte offset already written (Range: bytes=<pos>-…, a 206 is required). Up to 3 attempts without progress, then res.destroy() so ffmpeg's own -reconnect can take over.
  3. Stall detection: no data for 20 s while the client is not backpressuring (!res.writableNeedDrain) counts as upstream-error.
  4. If the stream ends short of the advertised length, res.destroy() instead of a clean res.end().

Result, the same two albums with the patch:

Without patch With patch
Tracks 22 24
Ending in silence / SIGKILL 5 0
Audible dropouts (listening test) 3 noticed none

The patch caught 4 terminations on 3 tracks and resumed each within 35–70 ms with no gap in pipe throughput. One example: Insignificant Other, which went silent at 5:07 without the patch, played to the end:

15:23:58.934 [WARN][Http|AudioProxy] proxy upstream read failed; resuming  pos=4997120 reason=terminated total=5900693 windowStart=4194304
15:23:58.972 [INFO][Http|AudioProxy] proxy upstream resumed  pos=4997120 resumes=1 status=206
15:28:28.535 [INFO][Audio|Manager]   playback ended  duration=354 elapsed=354

The stall detection (3) never fired in practice. Beforehand, a harness inside the container exercised all paths against a local 206 upstream (SHA-256 identical output each time): upstream error in window 1 and in window 2, silent stall, and a client pausing for 26 s, which must not trigger the stall detection.

Patch (diff against the compiled dist/…/audioProxyHandler.js of 4.0.0-beta.23)
--- a/dist/adapters/http/streams/audioProxyHandler.js (v4.0.0-beta.23)
+++ b/dist/adapters/http/streams/audioProxyHandler.js (patched)
@@ -10,6 +10,17 @@
 const MAX_PLAYLIST_HOPS = 3;
 const MAX_PLAYLIST_ENTRIES = 3;
 const RANGE_CHUNK_BYTES = 4 * 1024 * 1024;
+// ---- LOCAL PATCH helpers (ytmusic proxy stall) ----
+const PATCH_UPSTREAM_IDLE_MS = 20000;
+const PATCH_MAX_RESUME_FAILURES = 3;
+const PATCH_RESUME_BACKOFF_MS = 500;
+const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
+/** SONN_PROXY_TEST_FAULT="error:<byte>" | "stall:<byte>" - fires once per proxied stream. */
+function parseTestFault(value) {
+    const m = /^(error|stall):(\d+)$/.exec((value ?? '').trim());
+    return m ? { kind: m[1], atByte: Number(m[2]), used: false } : null;
+}
+// ---- END LOCAL PATCH helpers ----
 function isHlsManifest(body) {
     if (!/^\s*#EXTM3U/.test(body)) {
         return false;
@@ -294,10 +305,21 @@
         });
         res.end(rewritten);
     }
+    // ---- LOCAL PATCH (ytmusic proxy stall), based on v4.0.0-beta.23 ----------------
+    // Upstream read failures used to be treated like "client went away": the response
+    // to ffmpeg was neither ended nor destroyed and nothing was logged, so ffmpeg hung
+    // until the next track SIGKILLed it. Now: an upstream error or an upstream stall
+    // (no data while the client is not backpressuring) is logged and the stream is
+    // resumed from the exact byte position already written to the client.
     async streamInBoundedChunks(res, target, baseHeaders, startByte, firstChunk, firstRange, opts) {
+        const host = (() => { try { return new URL(target).host; } catch { return '?'; } })();
+        const fault = parseTestFault(process.env.SONN_PROXY_TEST_FAULT);
         let pos = startByte;
         let total = firstRange.total;
         let wroteHead = false;
+        let failuresWithoutProgress = 0;
+        let resuming = false;
+        let resumes = 0;
         let pending = {
             response: firstChunk,
             range: firstRange,
@@ -320,17 +342,33 @@
                 }
                 catch (error) {
                     this.log.warn('proxy chunk fetch failed', {
-                        target,
+                        host,
                         pos,
+                        resuming,
                         message: error instanceof Error ? error.message : String(error),
                     });
+                    if (resuming && ++failuresWithoutProgress <= PATCH_MAX_RESUME_FAILURES) {
+                        await sleep(PATCH_RESUME_BACKOFF_MS * failuresWithoutProgress);
+                        continue;
+                    }
                     break;
                 }
-                if (!chunk.ok || !chunk.body) {
-                    this.log.warn('proxy chunk rejected mid-stream', { target, pos, status: chunk.status });
+                // A resumed window must be a real partial starting at `pos`; a 200 would
+                // restart the file from byte 0 and splice garbage into the stream.
+                if (!chunk.ok || !chunk.body || (resuming && chunk.status !== 206)) {
+                    this.log.warn('proxy chunk rejected mid-stream', { host, pos, status: chunk.status, resuming });
+                    await this.discardBody(chunk, 'discarding rejected window', target).catch(() => { });
+                    if (resuming && ++failuresWithoutProgress <= PATCH_MAX_RESUME_FAILURES) {
+                        await sleep(PATCH_RESUME_BACKOFF_MS * failuresWithoutProgress);
+                        continue;
+                    }
                     break;
                 }
                 parsed = parseContentRange(chunk.headers.get('content-range'));
+                if (resuming) {
+                    this.log.info('proxy upstream resumed', { host, pos, status: chunk.status, resumes });
+                    resuming = false;
+                }
             }
             if (!chunk.body) {
                 break;
@@ -354,10 +392,41 @@
                 wroteHead = true;
             }
             const body = node_stream_1.Readable.fromWeb(chunk.body);
-            const finished = await this.pipeChunk(body, res);
-            if (!finished) {
+            const outcome = await this.pipeChunk(body, res, { fault, streamPos: pos });
+            if (outcome.status === 'client-gone') {
                 return;
             }
+            if (outcome.status === 'upstream-error') {
+                const resumeAt = pos + outcome.written;
+                if (outcome.written > 0) {
+                    failuresWithoutProgress = 0;
+                }
+                failuresWithoutProgress += 1;
+                resumes += 1;
+                this.log.warn('proxy upstream read failed; resuming', {
+                    host,
+                    pos: resumeAt,
+                    total,
+                    windowStart: pos,
+                    writtenInWindow: outcome.written,
+                    reason: outcome.reason,
+                    attempt: failuresWithoutProgress,
+                });
+                if (failuresWithoutProgress > PATCH_MAX_RESUME_FAILURES) {
+                    // Give up loudly: destroying the response lets ffmpeg's own
+                    // -reconnect take over instead of waiting forever.
+                    this.log.warn('proxy upstream resume budget exhausted', { host, pos: resumeAt, total });
+                    res.destroy(new Error('upstream failed'));
+                    return;
+                }
+                pos = resumeAt;
+                resuming = true;
+                if (failuresWithoutProgress > 1) {
+                    await sleep(PATCH_RESUME_BACKOFF_MS * (failuresWithoutProgress - 1));
+                }
+                continue;
+            }
+            failuresWithoutProgress = 0;
             const advanced = parsed ? parsed.end + 1 : pos + RANGE_CHUNK_BYTES;
             if (advanced <= pos) {
                 break;
@@ -372,35 +441,87 @@
             res.end(JSON.stringify({ error: 'proxy-chunk-failed' }));
             return;
         }
+        if (total !== null && pos < total) {
+            // Ended short of the advertised length: make it an error, not a clean EOF.
+            this.log.warn('proxy stream ended short', { host, pos, total });
+            res.destroy(new Error('upstream ended short'));
+            return;
+        }
         res.end();
     }
-    pipeChunk(body, res) {
+    /**
+     * Pipe one window into the response, keeping it open.
+     * Resolves { status: 'end' | 'client-gone' | 'upstream-error', written, reason }.
+     */
+    pipeChunk(body, res, opts = {}) {
         return new Promise((resolve) => {
             let settled = false;
-            const done = (ok) => {
+            let written = 0;
+            let lastActivity = Date.now();
+            let faultFired = false;
+            const done = (status, reason) => {
                 if (settled)
                     return;
                 settled = true;
+                clearInterval(idleTimer);
+                body.removeListener('data', onData);
                 body.removeListener('end', onEnd);
                 body.removeListener('error', onError);
                 res.removeListener('close', onClose);
-                resolve(ok);
+                res.removeListener('drain', onDrain);
+                body.unpipe(res);
+                resolve({ status, written, reason });
+            };
+            const onData = (buf) => {
+                written += buf.length;
+                lastActivity = Date.now();
+                const fault = opts.fault;
+                if (fault && !fault.used && !faultFired && (opts.streamPos ?? 0) + written >= fault.atByte) {
+                    faultFired = true;
+                    fault.used = true;
+                    if (fault.kind === 'error') {
+                        setImmediate(() => body.destroy(new Error('test fault: injected upstream error')));
+                    }
+                    else {
+                        // Simulate a silent stall: stop forwarding, keep the socket open.
+                        body.unpipe(res);
+                        body.removeListener('data', onData);
+                        body.pause();
+                    }
+                }
+            };
+            const onDrain = () => {
+                lastActivity = Date.now();
             };
-            const onEnd = () => done(true);
-            const onError = () => {
+            const onEnd = () => done('end');
+            const onError = (error) => {
                 body.destroy();
-                done(false);
+                done('upstream-error', error instanceof Error ? error.message : String(error));
             };
             const onClose = () => {
                 body.destroy();
-                done(false);
+                done('client-gone');
             };
+            const idleTimer = setInterval(() => {
+                if (res.writableNeedDrain) {
+                    // Client is backpressuring (paused / slow reader) - not an upstream stall.
+                    lastActivity = Date.now();
+                    return;
+                }
+                if (Date.now() - lastActivity > PATCH_UPSTREAM_IDLE_MS) {
+                    body.destroy();
+                    done('upstream-error', `upstream idle > ${PATCH_UPSTREAM_IDLE_MS} ms`);
+                }
+            }, 2000);
+            body.on('data', onData);
             body.on('end', onEnd);
             body.on('error', onError);
             res.on('close', onClose);
+            res.on('drain', onDrain);
             body.pipe(res, { end: false });
         });
     }
+    // ---- END LOCAL PATCH ------------------------------------------------------------
     async readTextResponse(upstream) {
         const length = upstream.headers.get('content-length');
         const size = length ? Number(length) : null;

The SONN_PROXY_TEST_FAULT hook is only there for the harness and can be dropped.

Further suggestions 🤖

  • -rw_timeout on ffmpeg HTTP inputs, and/or input-stall detection in the audio session, as defence in depth.
  • If googlevideo answers the resume with 403, the patch gives up after 3 attempts and the track ends early. A proper fix for that case would re-resolve the stream URL. It did not happen in our test.

Happy to test a build or open a PR with the TypeScript version.

cdanne avatar Nov 09 '26 17:11 cdanne

Follow-up after two more runs with the patched build (same system, three zones, 2026-11-09 evening):

Result: ~49 YouTube tracks with the patch, 0 silent. The patch caught 8 upstream failures, all resumed on the first attempt within 35–70 ms. The 20 s stall detection and the 3-attempt budget were never needed. A resumed connection also survived a 21-minute pause.

For the last run I added error.cause and some state to the log line. This is what the failure looks like:

21:08:22.871 [WARN][Http|AudioProxy] proxy upstream read failed; resuming
  causeCode=ECONNRESET causeMessage="read ECONNRESET" host=rr2---sn-xfxuxa-4hvs.googlevideo.com
  windowStart=4194304 pos=5144576 total=5900693 writtenInWindow=950272
  windowAgeMs=83274 msSinceData=13 clientNeedDrain=false clientBuffered=0
21:08:22.907 [INFO][Http|AudioProxy] proxy upstream resumed  pos=5144576 resumes=1 status=206

What the data shows. 🤖 marks interpretation.

  • The connection is reset (RST). It is not a graceful close (UND_ERR_SOCKET / "other side closed") and not a timeout on our side. Data was still flowing 13 ms before the reset, and nothing was backpressuring towards ffmpeg at that moment.

  • Repeatable per track, tied to time and not to bytes. Insignificant Other was reset in all three runs about 84 s after the track started, always in window 2, but at different byte offsets (4.96 / 5.00 / 5.14 MB). Window 2 opens about 0.7 s after the start, because the proxy pushes the first 4 MiB into the buffers towards ffmpeg almost at once. After that it reads at playback speed. Failures in window 1 came 56–60 s after the request (4 of 5).

  • Only two edge nodes. All 8 failures came from rr2---sn-xfxuxa-4hvs (6) and rr3---sn-xfxuxa-4hvl (2). rr1---* served 28+ streams without a single failure. 🤖 A local router or NAT would not single out two googlevideo nodes, so the reset most likely comes from Google's side.

  • Not reproducible with a plain client. From the same host, with still-valid URLs from rr1 and rr2, googlevideo sends the whole file in 0.25 s. None of these led to a reset:

    • a 30/50/70/120 s zero-window stall,
    • 150 s of reading at 16 kB/s,
    • a 3–3.6 MB burst followed by a 16 kB/s trickle.

    🤖 So it is not a simple idle or slow-reader timeout. Whatever triggers it on those nodes, the client has to expect a mid-body reset on a long-lived, slowly read range response.

🤖 This supports the approach of the patch: resume from the exact offset on any upstream error. Another option would be to avoid long-lived upstream connections altogether. googlevideo delivers a 3–6 MB Opus file in well under a second, so the proxy could read each window (or the whole track) at full speed into memory and serve ffmpeg from there. That needs more memory per zone, though, and the resume logic is still needed for real network errors.

cdanne avatar Nov 09 '26 21:11 cdanne

Thanks for the thorough analysis and the tested patch, it made this easy. The fix is on dev now and will be in the next beta. It follows your approach: a window that breaks off resumes from the exact byte already written, only a 206 is accepted as its continuation, repeated failures without progress or a stream that ends short destroy the response so ffmpeg's own reconnect takes over, and 20 s of upstream silence while the client keeps up counts as a failure. The warning includes the cause code (e.g. ECONNRESET). Let me know how it holds up on your system.

rudyberends avatar Nov 11 '26 16:11 rudyberends

Thank you for the quick response and the fix! Looking forward to the next beta to remove my local fix. Keep up the good work 👍

cdanne avatar Nov 12 '26 08:11 cdanne

This fix is in beta.24, so I'm closing this. If it still happens on beta.24 or later, just leave a comment here and I'll reopen it.

rudyberends avatar Nov 28 '26 18:11 rudyberends