Commit 2f562691 authored by Aryan Noshirvnai's avatar Aryan Noshirvnai

Skip embedded ID3v2 cover art when streaming audio for playback

Uploaded mp3s carry an ID3v2 tag that's almost entirely embedded cover
art - tens to hundreds of KB a player must get through before reaching
the first real audio frame, even though the player already gets artwork
from the separate coverart field and never touches the embedded copy.
Adds a shared stream_audio_file() helper that computes the tag's byte
offset and serves everything after it as the logical resource (Range
math included, so seeking is unaffected), and wires it into all 5
playback-stream endpoints that previously used plain FileResponse.
Also adds a long-lived Cache-Control, since every file lives at a
unique generated path and is never rewritten after upload.
Co-Authored-By: 's avatarClaude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019i3NAUkLkHNbsPg5vKfzF9
parent 44617a06
Pipeline #1214 failed with stage
in 17 minutes and 17 seconds
import difflib
import json
import os
from fastapi import APIRouter, Depends, HTTPException, Form
from fastapi.responses import FileResponse
from fastapi import APIRouter, Depends, HTTPException, Form, Request
from pydantic import BaseModel
from sqlalchemy import or_
from sqlalchemy.orm import Session
......@@ -11,6 +10,7 @@ from src.core.database import get_db, LibrarySong, Playlist, PlaylistTrack, User
from src.core.security import get_current_user, get_current_user_for_stream
from src.services.shared_library import give_from_shared_library
from src.services.favorites import liked_song_ids
from src.services.media_stream import stream_audio_file
router = APIRouter(tags=["Library & Playlists"])
......@@ -222,11 +222,11 @@ async def get_album(
}
@router.get("/library/stream/{file_id}")
async def stream_audio(file_id: int, db: Session = Depends(get_db), current_user: User = Depends(get_current_user_for_stream)):
async def stream_audio(file_id: int, request: Request, db: Session = Depends(get_db), current_user: User = Depends(get_current_user_for_stream)):
song = db.query(LibrarySong).filter(LibrarySong.id == file_id, LibrarySong.user_id == current_user.id).first()
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")
return FileResponse(song.file_path, media_type="audio/mpeg")
return stream_audio_file(song.file_path, request)
@router.delete("/library/{file_id}")
async def delete_library_song(file_id: int, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
......
......@@ -2,13 +2,13 @@ import os
import time
from typing import Optional
from fastapi import APIRouter, Depends, HTTPException, WebSocket, WebSocketDisconnect, status
from fastapi.responses import FileResponse
from fastapi import APIRouter, Depends, HTTPException, Request, WebSocket, WebSocketDisconnect, status
from pydantic import BaseModel
from sqlalchemy.orm import Session
from src.core.database import get_db, SessionLocal, User, Post, LiveLocation, LibrarySong, LiveRoom, RoomMessage, UserProfile
from src.core.security import get_current_user, get_current_user_for_stream, user_id_from_ws_token
from src.services.room_manager import room_manager
from src.services.media_stream import stream_audio_file
from datetime import datetime, timedelta, timezone
import math
......@@ -137,7 +137,7 @@ def get_remix_tree(post_id: int, db: Session = Depends(get_db), current_user: Us
@router.get("/posts/{post_id}/stream")
def stream_post_song(post_id: int, db: Session = Depends(get_db), current_user: User = Depends(get_current_user_for_stream)):
def stream_post_song(post_id: int, request: Request, db: Session = Depends(get_db), current_user: User = Depends(get_current_user_for_stream)):
"""Streams a post's song regardless of who uploaded it - a post's song_id isn't
necessarily the poster's own library song, same not-scoped-to-caller reasoning as the
other social stream endpoints (rooms, geo-drop, soundmarks)."""
......@@ -147,7 +147,7 @@ def stream_post_song(post_id: int, db: Session = Depends(get_db), current_user:
song = db.query(LibrarySong).filter(LibrarySong.id == post.song_id).first()
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")
return FileResponse(song.file_path, media_type="audio/mpeg")
return stream_audio_file(song.file_path, request)
LIVE_LOCATION_STALE_AFTER = timedelta(minutes=5) # heartbeats (see the frontend) land well
# inside this - anyone who goes quiet longer
......@@ -238,7 +238,7 @@ def get_nearby_listeners(
@router.get("/live-location/{user_id}/stream")
def stream_live_location_song(user_id: int, db: Session = Depends(get_db), current_user: User = Depends(get_current_user_for_stream)):
def stream_live_location_song(user_id: int, request: Request, db: Session = Depends(get_db), current_user: User = Depends(get_current_user_for_stream)):
"""Streams whatever a nearby user is currently playing, regardless of who uploaded it -
same not-scoped-to-caller reasoning as the other social stream endpoints. 404s the same
way for "not sharing at all" and "sharing but opted out of visibility" - not leaking a
......@@ -251,7 +251,7 @@ def stream_live_location_song(user_id: int, db: Session = Depends(get_db), curre
song = db.query(LibrarySong).filter(LibrarySong.id == loc.song_id).first()
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")
return FileResponse(song.file_path, media_type="audio/mpeg")
return stream_audio_file(song.file_path, request)
@router.post("/rooms", status_code=status.HTTP_201_CREATED)
......@@ -269,7 +269,7 @@ def get_active_rooms(db: Session = Depends(get_db), current_user: User = Depends
@router.get("/rooms/{room_id}/stream")
def stream_room_song(room_id: int, db: Session = Depends(get_db), current_user: User = Depends(get_current_user_for_stream)):
def stream_room_song(room_id: int, request: Request, db: Session = Depends(get_db), current_user: User = Depends(get_current_user_for_stream)):
"""Streams whatever's currently playing in a room, regardless of who uploaded the
underlying LibrarySong - shared social content by design (see the top-of-file note),
mirroring /soundmarks/{id}/stream's same not-scoped-to-caller reasoning."""
......@@ -281,7 +281,7 @@ def stream_room_song(room_id: int, db: Session = Depends(get_db), current_user:
song = db.query(LibrarySong).filter(LibrarySong.id == room.current_song_id).first()
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")
return FileResponse(song.file_path, media_type="audio/mpeg")
return stream_audio_file(song.file_path, request)
# --- Pass-the-Aux: live room WebSocket ---
......
......@@ -4,12 +4,12 @@ from datetime import datetime, timezone
from typing import Optional
import httpx
from fastapi import APIRouter, Depends, HTTPException
from fastapi.responses import FileResponse
from fastapi import APIRouter, Depends, HTTPException, Request
from pydantic import BaseModel
from sqlalchemy.orm import Session
from src.core.config import logger
from src.services.media_stream import stream_audio_file
from src.core.database import (
get_db,
LibrarySong,
......@@ -640,7 +640,7 @@ def delete_soundmark(
@router.get("/{soundmark_id}/stream")
def stream_soundmark_anthem(
soundmark_id: int, db: Session = Depends(get_db), current_user: User = Depends(get_current_user_for_stream)
soundmark_id: int, request: Request, db: Session = Depends(get_db), current_user: User = Depends(get_current_user_for_stream)
):
"""Streams a soundmark's current anthem regardless of which user originally uploaded the
underlying LibrarySong - unlike /library/stream/{id}, this is deliberately not scoped to
......@@ -654,7 +654,7 @@ def stream_soundmark_anthem(
song = db.query(LibrarySong).filter(LibrarySong.id == active_song_id).first()
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")
return FileResponse(song.file_path, media_type="audio/mpeg")
return stream_audio_file(song.file_path, request)
# ---- Suggestions (major/business tier - any authenticated user proposes, owner reviews) ----
......
import os
import re
from fastapi import Request
from fastapi.responses import Response, StreamingResponse
CHUNK_SIZE = 64 * 1024
_RANGE_RE = re.compile(r"bytes=(\d*)-(\d*)")
def _id3v2_tag_size(path: str) -> int:
"""Byte offset where real audio frames begin, skipping a leading ID3v2 tag if present.
On these uploads an ID3v2 tag is almost entirely embedded cover art - tens to hundreds of
KB a player must get past before it reaches anything playable, even though the player
already gets artwork from the separate `coverart` field and never looks at the embedded
copy. ID3v1 (a fixed 128-byte trailer at EOF, not EOH) is left alone - negligible, and at
the wrong end of the file to affect playback start.
"""
try:
with open(path, "rb") as f:
header = f.read(10)
except OSError:
return 0
if len(header) < 10 or header[:3] != b"ID3":
return 0
# Synchsafe integer: high bit of each of the 4 size bytes is always 0.
b1, b2, b3, b4 = header[6:10]
return 10 + ((b1 & 0x7F) << 21 | (b2 & 0x7F) << 14 | (b3 & 0x7F) << 7 | (b4 & 0x7F))
def stream_audio_file(path: str, request: Request) -> Response:
"""Streams an audio file for playback, skipping any leading ID3v2 tag (see
_id3v2_tag_size) so a player reaches the first real audio frame sooner. Handles Range
requests directly instead of delegating to FastAPI's FileResponse, since FileResponse has
no notion of a logical offset into the file - this makes the post-tag region look like the
*entire* resource to the client, Range math included, so seeking still works correctly.
Cached aggressively: every file lives at a unique generated path and is never rewritten in
place after upload (new tags/uploads always get a new path), so it's safe to treat as
permanently immutable.
"""
offset = _id3v2_tag_size(path)
total_size = os.path.getsize(path)
logical_size = max(total_size - offset, 0)
start, end = 0, max(logical_size - 1, 0)
status_code = 200
range_header = request.headers.get("range")
if range_header and logical_size:
match = _RANGE_RE.match(range_header)
if match:
start_str, end_str = match.groups()
start = max(0, min(int(start_str), logical_size - 1)) if start_str else 0
end = max(start, min(int(end_str), logical_size - 1)) if end_str else logical_size - 1
status_code = 206
content_length = (end - start + 1) if logical_size else 0
def iterfile():
with open(path, "rb") as f:
f.seek(offset + start)
remaining = content_length
while remaining > 0:
chunk = f.read(min(CHUNK_SIZE, remaining))
if not chunk:
break
remaining -= len(chunk)
yield chunk
headers = {
"accept-ranges": "bytes",
"content-length": str(content_length),
"cache-control": "public, max-age=31536000, immutable",
}
if status_code == 206:
headers["content-range"] = f"bytes {start}-{end}/{logical_size}"
return StreamingResponse(iterfile(), status_code=status_code, media_type="audio/mpeg", headers=headers)
import os
import tempfile
from src.core.database import LibrarySong
from src.services.media_stream import _id3v2_tag_size
def _synchsafe(size: int) -> bytes:
return bytes([(size >> 21) & 0x7F, (size >> 14) & 0x7F, (size >> 7) & 0x7F, size & 0x7F])
def _make_tagged_mp3(tag_body_size: int, audio: bytes) -> str:
"""Builds a fake mp3 with a real ID3v2 header (as if carrying embedded cover art) followed
by audio bytes, so tests can assert streaming skips exactly the tag portion."""
header = b"ID3" + bytes([4, 0, 0]) + _synchsafe(tag_body_size)
tag_body = b"\x00" * tag_body_size
fd, path = tempfile.mkstemp(suffix=".mp3", dir="/tmp")
with os.fdopen(fd, "wb") as f:
f.write(header + tag_body + audio)
return path
def test_id3v2_tag_size_detects_real_tag():
audio = b"AUDIOFRAMEDATA" * 5
path = _make_tagged_mp3(100, audio)
try:
assert _id3v2_tag_size(path) == 10 + 100
finally:
os.remove(path)
def test_id3v2_tag_size_zero_when_no_tag():
fd, path = tempfile.mkstemp(suffix=".mp3", dir="/tmp")
with os.fdopen(fd, "wb") as f:
f.write(b"\xff\xfbAUDIOFRAMEDATA")
try:
assert _id3v2_tag_size(path) == 0
finally:
os.remove(path)
def test_stream_skips_id3v2_tag_bytes(client, db_session, auth_as):
headers, user = auth_as()
audio = b"REALAUDIOFRAMES1234567890"
path = _make_tagged_mp3(200, audio)
song = LibrarySong(user_id=user.id, title="Tagged", artist="Artist", file_path=path)
db_session.add(song)
db_session.commit()
db_session.refresh(song)
try:
response = client.get(f"/library/stream/{song.id}", headers=headers)
assert response.status_code == 200
assert response.content == audio
assert response.headers["content-length"] == str(len(audio))
assert response.headers["cache-control"] == "public, max-age=31536000, immutable"
finally:
os.remove(path)
def test_stream_range_request_relative_to_post_tag_content(client, db_session, auth_as):
headers, user = auth_as()
audio = b"0123456789ABCDEFGHIJ" # 20 bytes, easy to index
path = _make_tagged_mp3(50, audio)
song = LibrarySong(user_id=user.id, title="Tagged", artist="Artist", file_path=path)
db_session.add(song)
db_session.commit()
db_session.refresh(song)
try:
range_headers = {**headers, "Range": "bytes=5-9"}
response = client.get(f"/library/stream/{song.id}", headers=range_headers)
assert response.status_code == 206
assert response.content == b"56789"
assert response.headers["content-range"] == f"bytes 5-9/{len(audio)}"
finally:
os.remove(path)
def test_stream_without_id3_tag_still_works(client, db_session, auth_as):
# Regression guard: files with no ID3v2 header (the common case in existing tests/uploads
# that predate this) must stream exactly as before - offset 0, full content, 200.
headers, user = auth_as()
fd, path = tempfile.mkstemp(suffix=".mp3", dir="/tmp")
with os.fdopen(fd, "wb") as f:
f.write(b"plain mp3 bytes, no tag")
song = LibrarySong(user_id=user.id, title="Untagged", artist="Artist", file_path=path)
db_session.add(song)
db_session.commit()
db_session.refresh(song)
try:
response = client.get(f"/library/stream/{song.id}", headers=headers)
assert response.status_code == 200
assert response.content == b"plain mp3 bytes, no tag"
finally:
os.remove(path)
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