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

Fix "Can't sync to MPEG frame": permissive ffmpeg fallback + stop leaking errors to clients

Confirmed from a real webapp upload (dev server log): a file Shazam
successfully identified ("Invisible" by Duran Duran, despite the local
AcoustID fingerprinter also struggling with the same file - symphonia's
demuxer logged dozens of "skipping junk"/"invalid mpeg audio header"
warnings but still recovered enough to match) then failed outright at the
ffmpeg conversion step with "Can't sync to MPEG frame", killing the whole
request with a 500 even though identification had already succeeded. This
is exactly the "messy real-world MP3s" scenario the product is meant to
handle, not an edge case worth ignoring.

- audio_processing.py: on CouldntDecodeError from pydub's default (strict)
  ffmpeg invocation, retry once via a direct ffmpeg subprocess with
  -err_detect ignore_err -fflags +igndts+discardcorrupt, which tells ffmpeg
  to skip past bad frames instead of giving up. New AudioDecodeError is
  raised only if that also fails, distinct from a bare Exception so callers
  can show a clean message instead of raw ffmpeg stderr.
- music.py: both /music/upload and /music/tag now catch AudioDecodeError
  specifically (422, clean user-facing message) and everything else via
  logger.exception + a generic 500 message - previously upload_direct did
  `raise HTTPException(500, detail=str(e))`, which is exactly the raw
  ffmpeg stderr the user saw rendered directly in the webapp's error
  banner, and logged nothing server-side for future diagnosis.

Verified: full 104-test suite still passes, module imports cleanly, dev
server restarted successfully.
Co-Authored-By: 's avatarClaude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019i3NAUkLkHNbsPg5vKfzF9
parent 893240bd
Pipeline #1040 passed with stage
in 3 minutes and 31 seconds
...@@ -13,7 +13,7 @@ from src.core.config import logger ...@@ -13,7 +13,7 @@ from src.core.config import logger
from src.core.database import IdentifiedTrack, LibrarySong, User, get_db from src.core.database import IdentifiedTrack, LibrarySong, User, get_db
from src.core.security import get_current_user from src.core.security import get_current_user
from src.services import storage from src.services import storage
from src.services.audio_processing import tag_and_convert_audio from src.services.audio_processing import AudioDecodeError, tag_and_convert_audio
from src.services.music_identification import ( from src.services.music_identification import (
compute_fingerprint, compute_fingerprint,
fetch_lyrics, fetch_lyrics,
...@@ -175,7 +175,16 @@ async def tag_music( ...@@ -175,7 +175,16 @@ async def tag_music(
except Exception as e: except Exception as e:
raise HTTPException(status_code=404, detail=f"Could not download audio from chat: {e}") raise HTTPException(status_code=404, detail=f"Could not download audio from chat: {e}")
try:
result = await _identify_tag_and_store(db, current_user, raw_file_path, request, req.language_preference) result = await _identify_tag_and_store(db, current_user, raw_file_path, request, req.language_preference)
except AudioDecodeError as e:
logger.error(f"Audio decode failed for user {current_user.id}'s chat tag request: {e}")
raise HTTPException(status_code=422, detail="Couldn't process this audio file - it may be corrupted or in an unsupported format.")
except HTTPException:
raise
except Exception:
logger.exception(f"Unexpected error tagging chat audio for user {current_user.id}")
raise HTTPException(status_code=500, detail="Something went wrong processing this file. Please try again.")
return result return result
...@@ -202,6 +211,10 @@ async def upload_direct( ...@@ -202,6 +211,10 @@ async def upload_direct(
try: try:
result = await _identify_tag_and_store(db, current_user, temp_path, request) result = await _identify_tag_and_store(db, current_user, temp_path, request)
except Exception as e: except AudioDecodeError as e:
raise HTTPException(status_code=500, detail=str(e)) logger.error(f"Audio decode failed for user {current_user.id}'s upload: {e}")
raise HTTPException(status_code=422, detail="Couldn't process this audio file - it may be corrupted or in an unsupported format.")
except Exception:
logger.exception(f"Unexpected error tagging upload for user {current_user.id}")
raise HTTPException(status_code=500, detail="Something went wrong processing this file. Please try again.")
return result return result
import asyncio
import os import os
import shutil import shutil
import aiohttp import aiohttp
from pydub import AudioSegment from pydub import AudioSegment
from pydub.exceptions import CouldntDecodeError
from mutagen.mp3 import MP3 from mutagen.mp3 import MP3
from mutagen.id3 import ID3, APIC, USLT, TIT2, TPE1, TALB, TDRC, TCON, TRCK, error from mutagen.id3 import ID3, APIC, USLT, TIT2, TPE1, TALB, TDRC, TCON, TRCK, error
from src.core.config import logger from src.core.config import logger
...@@ -13,6 +15,32 @@ async def download_image(url: str) -> bytes: ...@@ -13,6 +15,32 @@ async def download_image(url: str) -> bytes:
if response.status == 200: return await response.read() if response.status == 200: return await response.read()
return None return None
class AudioDecodeError(Exception):
"""Raised when a source file can't be decoded even with permissive-decode fallback -
distinct from a plain Exception so callers can show a clean, user-facing message
instead of leaking raw ffmpeg stderr."""
async def _convert_with_permissive_ffmpeg(raw_file_path: str, mp3_file_path: str):
"""Fallback for files that trip ffmpeg's default (strict) demuxer probing - garbage-
prefixed or slightly malformed real-world MP3s in particular (exactly what this project
is meant to handle - see the "messy MP3s" product goal). -err_detect ignore_err/+discardcorrupt
tell ffmpeg to skip past bad frames instead of giving up entirely, which is often enough
to recover audio that a decoder like Shazam's (a different, more lenient decoder) already
identified successfully moments earlier in the same request."""
proc = await asyncio.create_subprocess_exec(
"ffmpeg", "-y",
"-err_detect", "ignore_err",
"-fflags", "+igndts+discardcorrupt",
"-i", raw_file_path,
"-acodec", "libmp3lame", "-b:a", "192k",
mp3_file_path,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
)
_stdout, stderr = await proc.communicate()
if proc.returncode != 0 or not os.path.exists(mp3_file_path):
raise AudioDecodeError(stderr.decode(errors="replace")[-2000:])
async def tag_and_convert_audio(raw_file_path: str, candidate: dict) -> str: async def tag_and_convert_audio(raw_file_path: str, candidate: dict) -> str:
"""Converts audio to MP3 and applies all ID3 tags. Returns the path to the tagged MP3.""" """Converts audio to MP3 and applies all ID3 tags. Returns the path to the tagged MP3."""
...@@ -22,8 +50,12 @@ async def tag_and_convert_audio(raw_file_path: str, candidate: dict) -> str: ...@@ -22,8 +50,12 @@ async def tag_and_convert_audio(raw_file_path: str, candidate: dict) -> str:
shutil.copyfile(raw_file_path, mp3_file_path) shutil.copyfile(raw_file_path, mp3_file_path)
else: else:
mp3_file_path = f"{raw_file_path}.mp3" mp3_file_path = f"{raw_file_path}.mp3"
try:
audio = AudioSegment.from_file(raw_file_path) audio = AudioSegment.from_file(raw_file_path)
audio.export(mp3_file_path, format="mp3", bitrate="192k") audio.export(mp3_file_path, format="mp3", bitrate="192k")
except CouldntDecodeError as e:
logger.error(f"Standard decode failed, retrying with permissive ffmpeg flags: {e}")
await _convert_with_permissive_ffmpeg(raw_file_path, mp3_file_path)
# 2. Add ID3 Tags # 2. Add ID3 Tags
mp3 = MP3(mp3_file_path, ID3=ID3) mp3 = MP3(mp3_file_path, ID3=ID3)
......
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