Commit 3ec09358 authored by Aryan Noshirvnai's avatar Aryan Noshirvnai

Radio: stream from the live offset directly instead of seeking after the fact

The old /radio/{id}/stream always served the file from byte 0 and relied on
the frontend seeking afterward once it knew the duration - a visible delay
before any audio played, and meaningless for a live broadcast with no stable
timeline to seek within anyway. stream_audio_from_offset uses ffmpeg's
demuxer-level -ss (seeks before decoding, -acodec copy avoids a re-encode) so
the response itself starts exactly where the station actually is right now.
Co-Authored-By: 's avatarClaude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019i3NAUkLkHNbsPg5vKfzF9
parent 6c4cb3ed
Pipeline #1224 failed with stage
in 3 minutes and 19 seconds
...@@ -2,7 +2,7 @@ import os ...@@ -2,7 +2,7 @@ import os
from datetime import datetime, timezone from datetime import datetime, timezone
from typing import List, Optional from typing import List, Optional
from fastapi import APIRouter, Depends, HTTPException, Request, UploadFile, File from fastapi import APIRouter, Depends, HTTPException, UploadFile, File
from pydantic import BaseModel from pydantic import BaseModel
from sqlalchemy.orm import Session from sqlalchemy.orm import Session
...@@ -10,7 +10,7 @@ from src.core.database import get_db, LibrarySong, Radio, RadioTrack, User ...@@ -10,7 +10,7 @@ from src.core.database import get_db, LibrarySong, Radio, RadioTrack, User
from src.core.security import get_current_user, get_current_user_for_stream from src.core.security import get_current_user, get_current_user_for_stream
from src.services.audio_processing import probe_duration_seconds from src.services.audio_processing import probe_duration_seconds
from src.services.geo import haversine_meters from src.services.geo import haversine_meters
from src.services.media_stream import stream_audio_file from src.services.media_stream import stream_audio_from_offset
from src.services import storage from src.services import storage
router = APIRouter(prefix="/radio", tags=["radio"]) router = APIRouter(prefix="/radio", tags=["radio"])
...@@ -381,10 +381,14 @@ def get_now_playing(radio_id: int, db: Session = Depends(get_db), current_user: ...@@ -381,10 +381,14 @@ def get_now_playing(radio_id: int, db: Session = Depends(get_db), current_user:
@router.get("/{radio_id}/stream") @router.get("/{radio_id}/stream")
def stream_radio(radio_id: int, request: Request, db: Session = Depends(get_db), current_user: User = Depends(get_current_user_for_stream)): async def stream_radio(radio_id: int, db: Session = Depends(get_db), current_user: User = Depends(get_current_user_for_stream)):
"""Re-derives the current song fresh on every request via compute_now_playing - so a """Re-derives the current song fresh on every request via compute_now_playing - so a
listener who starts playing 10 minutes after tuning in correctly gets whatever is actually listener who starts playing 10 minutes after tuning in correctly gets whatever is actually
on now, not whatever was on when they first connected.""" on now, not whatever was on when they first connected. Starts the stream itself at that
exact offset (stream_audio_from_offset) rather than serving from byte 0 and relying on the
player to seek afterward - radio has no stable timeline for a client-side seek to land on
correctly anyway, and the extra round trip that pattern needs was adding a visible delay
before any audio was actually heard."""
radio = _get_radio_or_404(db, radio_id) radio = _get_radio_or_404(db, radio_id)
now_playing = compute_now_playing(db, radio) now_playing = compute_now_playing(db, radio)
if not now_playing["on_air"] or not now_playing["song"]: if not now_playing["on_air"] or not now_playing["song"]:
...@@ -392,7 +396,7 @@ def stream_radio(radio_id: int, request: Request, db: Session = Depends(get_db), ...@@ -392,7 +396,7 @@ def stream_radio(radio_id: int, request: Request, db: Session = Depends(get_db),
song = db.query(LibrarySong).filter(LibrarySong.id == now_playing["song"]["id"]).first() song = db.query(LibrarySong).filter(LibrarySong.id == now_playing["song"]["id"]).first()
if not song or not song.file_path or not os.path.exists(song.file_path): if not song or not song.file_path or not os.path.exists(song.file_path):
raise HTTPException(status_code=404, detail="Audio file not found") raise HTTPException(status_code=404, detail="Audio file not found")
return stream_audio_file(song.file_path, request) return await stream_audio_from_offset(song.file_path, now_playing["offset_seconds"] or 0.0)
@router.post("/{radio_id}/artwork") @router.post("/{radio_id}/artwork")
......
import asyncio
import os import os
import re import re
...@@ -75,3 +76,43 @@ def stream_audio_file(path: str, request: Request) -> Response: ...@@ -75,3 +76,43 @@ def stream_audio_file(path: str, request: Request) -> Response:
headers["content-range"] = f"bytes {start}-{end}/{logical_size}" headers["content-range"] = f"bytes {start}-{end}/{logical_size}"
return StreamingResponse(iterfile(), status_code=status_code, media_type="audio/mpeg", headers=headers) return StreamingResponse(iterfile(), status_code=status_code, media_type="audio/mpeg", headers=headers)
async def stream_audio_from_offset(file_path: str, offset_seconds: float) -> StreamingResponse:
"""Starts an audio stream partway through the file, for Radio's "join wherever the loop
actually is right now" playback - a plain byte-Range request (stream_audio_file above)
can't do this, since the correct start point isn't byte 0 and isn't known without decoding.
Without this, the player has to start from 0, wait for duration to load, then seek - a
second network round trip that visibly delayed how long it took for actual audio to be
heard, and (worse) made "pause" and "scrub" look like meaningful actions on what's actually
a live position with no stable timeline to rewind to. ffmpeg's demuxer-level `-ss` (before
`-i`, so it seeks before decoding anything) with `-acodec copy` (no re-encode, just a
different start point in the same codec/container) gets there in one request. No Range
support and no caching here - unlike the static per-user library files stream_audio_file
serves, this response is generated fresh per request and was never a fixed byte range to
begin with."""
proc = await asyncio.create_subprocess_exec(
"ffmpeg", "-v", "quiet",
"-ss", f"{max(0.0, offset_seconds):.3f}",
"-i", file_path,
"-acodec", "copy",
"-f", "mp3",
"-",
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.DEVNULL,
)
async def body():
assert proc.stdout
try:
while True:
chunk = await proc.stdout.read(CHUNK_SIZE)
if not chunk:
break
yield chunk
finally:
if proc.returncode is None:
proc.kill()
await proc.wait()
return StreamingResponse(body(), media_type="audio/mpeg")
...@@ -637,6 +637,38 @@ def test_stream_serves_the_current_song(client, auth_as): ...@@ -637,6 +637,38 @@ def test_stream_serves_the_current_song(client, auth_as):
assert response.status_code == 200 assert response.status_code == 200
def test_stream_actually_starts_at_the_computed_offset(client, auth_as):
"""Regression test for the real seek, not just a 200 status - proves ffmpeg's -ss is
actually being applied rather than silently serving the track from its own beginning."""
from pydub import AudioSegment
headers, user = auth_as()
fd, real_path = tempfile.mkstemp(suffix=".mp3", dir="/tmp")
os.close(fd)
AudioSegment.silent(duration=10_000).export(real_path, format="mp3") # 10s track
song_id = _make_library_song(user_id=user.id, file_path=real_path, duration_seconds=10.0)
# Started 4s ago -> now-playing offset should be ~4s into this one 10s track.
started = datetime.now(timezone.utc) - timedelta(seconds=4)
radio_id = _make_radio(user.id, reference_started_at=started)
_add_track(radio_id, song_id, 0)
response = client.get(f"/radio/{radio_id}/stream", headers=headers)
assert response.status_code == 200
out_fd, out_path = tempfile.mkstemp(suffix=".mp3", dir="/tmp")
with os.fdopen(out_fd, "wb") as f:
f.write(response.content)
try:
streamed_duration = len(AudioSegment.from_file(out_path)) / 1000.0
finally:
os.remove(out_path)
os.remove(real_path)
# Should be the *remaining* ~6s, not the full 10s track from the start.
assert 4.5 <= streamed_duration <= 7.0
def test_stream_accepts_token_query_param(client, auth_as): def test_stream_accepts_token_query_param(client, auth_as):
import re import re
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment