Repository navigation
Replies: 2 comments
|
ok |
0 replies
|
did you test this against ffmpeg with libcurl support |
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
stream.c
When listening to live HTTP audio streams (Icecast/SHOUTcast MP3, AAC, Ogg, FLAC), brief network drops or CDN edge-server switches interrupt the TCP connection. Standard reconnection mechanisms (such as FFmpeg's built-in reconnect_streamed=1) simply reopen the HTTP stream and pass the new bytes straight to the demuxer.
Because Icecast/SHOUTcast servers maintain a burst-on-connect buffer (typically 5 to 30 seconds of recent audio), reconnecting causes two major issues:
Audio Duplication or Gaps: The server immediately sends overlapping audio from its burst buffer, resulting in an audible repeat of several seconds of the track—or a sudden jump forward.
Exponential Backoff Delays & Decoder Errors: FFmpeg's default reconnect logic uses exponential backoff (1s -> 3s -> 7s -> 15s...), and mid-frame drops often trigger decoder errors (mp3: Header missing, invalid new backstep) or premature EOF.
Core Idea & Architecture
Instead of letting FFmpeg handle reconnection blindly, we disable FFmpeg's internal reconnect (reconnect=0) so that socket errors immediately bubble up to mpv's stream layer (stream/stream.c).
When a drop occurs, mpv reconnects at the stream layer and performs codec-agnostic, byte-level resynchronization using its internal ring buffer:
History Retention: Keep at least 512 KB (~32 seconds of 128 kbps audio) of read history behind s->buf_cur in the ring buffer.
Head Signature Matching: Upon reconnecting, read the first 20 bytes (sig) of the new stream (after FFmpeg's AVIOContext strips any ICY metadata headers) and perform a reverse search (rfind_bytes) in the ring buffer history.
Stream Alignment (Fast-Forward or Rewind):
• Match is ahead of buf_cur (unconsumed tail): Rewind s->buf_end back to the match position to trim duplicate buffered data, then append the new stream seamlessly.
• Match is behind buf_cur: Calculate the exact byte distance to s->buf_end (to_skip) and fast-forward (discard) the overlapping bytes from the new socket until it catches up to the exact byte where the old stream stopped.
Tail Signature Verification (tail_sig): Around the expected cut point (to_skip ± 2048 bytes), search for the last 20 bytes that were written to the old buffer right before the drop (s->buffer[buf_end - 20 .. buf_end)). This guarantees 0-byte alignment across any audio codec or CDN edge server without parsing container/frame headers.
Safe Teardown & Fixed Retry Interval: Retry at a constant 1000 ms interval (canceling immediately on player exit) and safely detach stream callbacks if reconnection is aborted so free_stream() never dereferences a NULL s->priv.
Where Everything Happens in the Code
• stream/stream.h:
• Added bool need_resync; and int reconnect_attempts; to struct stream.
• stream/stream.c:
• stream_read_partial(): Prevents bypassing the ring buffer on large reads for network streams (STREAM_ORIGIN_NET) so the 512 KB history window is always preserved.
• stream_read_more(): Ensures RESYNC_HISTORY_KEEP (512 KB) is retained behind s->buf_cur during buffer resizing and triggers stream_resync_buffer() immediately when stream_read_unbuffered() signals a reconnect (-2).
• stream_read_unbuffered(): Intercepts read errors (res <= 0) when cancellation is not active and triggers stream_reconnect().
• stream_reconnect(): Closes the dead driver instance once, loops with a fixed 1000 ms cancelable sleep (resync_sleep_cancelable()), reopens the stream via open2()/open(), and nullifies driver callbacks on abort to prevent Segmentation fault during free_stream().
• stream_resync_buffer(): Captures the 20-byte signature, locates it via rfind_bytes(), fast-forwards or rewinds the stream pointers, verifies exact byte alignment via tail_sig, and appends clean audio bytes via ring_append().
A. stream/stream.h
Add the state fields to typedef struct stream:
B. stream/stream.c
Add the resync constants, helpers, and updated stream read/reconnect functions:
And in
stream_read_more()/stream_read_partial():To ensure FFmpeg immediately hands network drops over to mpv without exponential backoff delays, run with:
bash
mpv --audio-device="alsa/bluealsa" --msg-level=all=v,ffmpeg=debug
--stream-lavf-o="seekable=0,reconnect=0,reconnect_at_eof=1,reconnect_streamed=0,reconnect_delay_max=0,reconnect_on_network_error=1,reconnect_max_retries=1000"
--demuxer-lavf-o=live_start_index=-1,http_persistent=0,http_multiple=0
--cache-pause-wait=10
--cache-pause-initial=yes
--loop-playlist='inf'
--network-timeout=4
--cache=yes --demuxer-readahead-secs=5 --demuxer-max-bytes=3056000 http://smoothjazz.cdnstream1.com/2585_128.mp3
• reconnect=0: Disables FFmpeg's internal reconnect loop so stream.c handles recovery and byte-level stitching.
• network-timeout=4: Forces FFmpeg to abort stalled socket reads after 3 seconds (3,000,000 µs) even if the server keeps the TCP connection open during ad breaks.
• demuxer-readahead-secs=5: Keeps enough decoded/packetized audio ahead of playback so reconnection and fast-forwarding complete without audio underruns.
Result:
[ffmpeg] tcp: Connection to tcp://smoothjazz.cdnstream1.com:80 failed: Network is unreachable
[ffmpeg] http: Will retry at 0 in 0 second(s).
[ffmpeg] tcp: Starting connection attempt to 66.85.89.177 port 80
[ffmpeg] tcp: Connected attempt failed: Network is unreachable
[ffmpeg] tcp: Connection to tcp://smoothjazz.cdnstream1.com:80 failed: Network is unreachable
[ffmpeg] [RESYNC] Reopen attempt #6 failed with error code: 0
[ffmpeg] [RESYNC] Waiting 1000 ms before reconnect attempt 7...
[ffmpeg] [RESYNC] Stream dropped! Attempting reconnect #7 for URL: http://smoothjazz.cdnstream1.com/2585_128.mp3
[ffmpeg] tcp: Starting connection attempt to 66.85.89.177 port 80
[ffmpeg] tcp: Connected attempt failed: Network is unreachable
[ffmpeg] tcp: Connection to tcp://smoothjazz.cdnstream1.com:80 failed: Network is unreachable
[ffmpeg] http: Will retry at 0 in 0 second(s).
[ffmpeg] tcp: Starting connection attempt to 66.85.89.177 port 80
[ffmpeg] tcp: Connected attempt failed: Network is unreachable
[ffmpeg] tcp: Connection to tcp://smoothjazz.cdnstream1.com:80 failed: Network is unreachable
[ffmpeg] [RESYNC] Reopen attempt #7 failed with error code: 0
[ffmpeg] [RESYNC] Waiting 1000 ms before reconnect attempt 8...
[ffmpeg] [RESYNC] Stream dropped! Attempting reconnect #8 for URL: http://smoothjazz.cdnstream1.com/2585_128.mp3
[ffmpeg] tcp: Starting connection attempt to 66.85.89.177 port 80
[ffmpeg] tcp: Successfully connected to 66.85.89.177 port 80
[ffmpeg] Could not set AVOption tls_verify='1'
[ffmpeg] [RESYNC] Reconnected successfully on attempt #8! Entering resync state.
[ffmpeg] [RESYNC] stream_read_unbuffered returned -2, starting resync immediately.
[ffmpeg] [RESYNC] Starting buffer resync: reading 20 signature bytes from new stream...
[ffmpeg] [RESYNC] Read 20 bytes after reconnect, resetting reconnect_attempts.
[ffmpeg] [RESYNC] Signature read chunk: r=20 (got 20/20)
[ffmpeg] [RESYNC] Captured 20-byte signature: [FF FB 92 60 00 00 03 D1 66 DA 6B 2F 2B 72 42 03 EB 2D 3D]
[ffmpeg] [RESYNC] Buffer state before search: buf_start=0, buf_cur=809980, buf_end=809980 (total_avail=809980, history_left=809980, forward_right=0, search_len=524288)
[ffmpeg] [RESYNC] Copied 524288 bytes from ring buffer (starting at 285692) for reverse search.
[ffmpeg] [RESYNC] MATCH FOUND! offset_in_window=194125, new_end=479817, buf_cur=809980, buf_end=809980, to_skip=330143
[ffmpeg] http: Metadata update for StreamTitle: Mindi Abair - Falling in Love (radio edit)
[ffmpeg] http: Metadata update for StreamUrl:
[ffmpeg] http: Metadata update for StreamArtwork:
[ffmpeg] [RESYNC] EXACT TAIL MATCH! Adjusted skip 330143 -> 330143 (CDN shift: +0 bytes).
[ffmpeg] [RESYNC] Fast-forward complete! Cut at 330143 bytes, pushing 4096 aligned bytes at buf_end=809980.
[ffmpeg] [RESYNC] ring_append: writing 4096 bytes at ring pos=809980 (buf_start=0, buf_cur=809980, buf_end=809980, mask=0xfffff)
[ffmpeg] [RESYNC] Resync finished. New buffer state: buf_start=0, buf_cur=809980, buf_end=814076 (forward_avail=4096)
[ffmpeg] ICY_STREAM_RAW_TAG: Mindi Abair - Falling in Love (radio edit)
[ffmpeg] http: Metadata update for StreamTitle: SmoothJazz.com - Listening Loft
[ffmpeg] http: Metadata update for StreamUrl:
[ffmpeg] http: Metadata update for StreamArtwork:
[ffmpeg] ICY_STREAM_RAW_TAG: SmoothJazz.com - Listening Loft
All reactions